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 "prims/methodHandles.hpp"
  39 #include "runtime/biasedLocking.hpp"
  40 #include "runtime/flags/flagSetting.hpp"
  41 #include "runtime/interfaceSupport.inline.hpp"
  42 #include "runtime/objectMonitor.hpp"
  43 #include "runtime/os.hpp"
  44 #include "runtime/safepoint.hpp"
  45 #include "runtime/safepointMechanism.hpp"
  46 #include "runtime/sharedRuntime.hpp"
  47 #include "runtime/stubRoutines.hpp"
  48 #include "runtime/thread.hpp"
  49 #include "utilities/macros.hpp"
  50 #include "crc32c.h"
  51 #ifdef COMPILER2
  52 #include "opto/intrinsicnode.hpp"
  53 #endif
  54 
  55 #ifdef PRODUCT
  56 #define BLOCK_COMMENT(str) /* nothing */
  57 #define STOP(error) stop(error)
  58 #else
  59 #define BLOCK_COMMENT(str) block_comment(str)
  60 #define STOP(error) block_comment(error); stop(error)
  61 #endif
  62 
  63 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  64 
  65 #ifdef ASSERT
  66 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  67 #endif
  68 
  69 static Assembler::Condition reverse[] = {
  70     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  71     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  72     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  73     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  74     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  75     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  76     Assembler::above          /* belowEqual    = 0x6 */ ,
  77     Assembler::belowEqual     /* above         = 0x7 */ ,
  78     Assembler::positive       /* negative      = 0x8 */ ,
  79     Assembler::negative       /* positive      = 0x9 */ ,
  80     Assembler::noParity       /* parity        = 0xa */ ,
  81     Assembler::parity         /* noParity      = 0xb */ ,
  82     Assembler::greaterEqual   /* less          = 0xc */ ,
  83     Assembler::less           /* greaterEqual  = 0xd */ ,
  84     Assembler::greater        /* lessEqual     = 0xe */ ,
  85     Assembler::lessEqual      /* greater       = 0xf, */
  86 
  87 };
  88 
  89 
  90 // Implementation of MacroAssembler
  91 
  92 // First all the versions that have distinct versions depending on 32/64 bit
  93 // Unless the difference is trivial (1 line or so).
  94 
  95 #ifndef _LP64
  96 
  97 // 32bit versions
  98 
  99 Address MacroAssembler::as_Address(AddressLiteral adr) {
 100   return Address(adr.target(), adr.rspec());
 101 }
 102 
 103 Address MacroAssembler::as_Address(ArrayAddress adr) {
 104   return Address::make_array(adr);
 105 }
 106 
 107 void MacroAssembler::call_VM_leaf_base(address entry_point,
 108                                        int number_of_arguments) {
 109   call(RuntimeAddress(entry_point));
 110   increment(rsp, number_of_arguments * wordSize);
 111 }
 112 
 113 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 114   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 115 }
 116 
 117 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 118   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 119 }
 120 
 121 void MacroAssembler::cmpoop_raw(Address src1, jobject obj) {
 122   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 123 }
 124 
 125 void MacroAssembler::cmpoop_raw(Register src1, jobject obj) {
 126   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 127 }
 128 
 129 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 130   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
 131   bs->obj_equals(this, src1, obj);
 132 }
 133 
 134 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 135   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
 136   bs->obj_equals(this, src1, obj);
 137 }
 138 
 139 void MacroAssembler::extend_sign(Register hi, Register lo) {
 140   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 141   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 142     cdql();
 143   } else {
 144     movl(hi, lo);
 145     sarl(hi, 31);
 146   }
 147 }
 148 
 149 void MacroAssembler::jC2(Register tmp, Label& L) {
 150   // set parity bit if FPU flag C2 is set (via rax)
 151   save_rax(tmp);
 152   fwait(); fnstsw_ax();
 153   sahf();
 154   restore_rax(tmp);
 155   // branch
 156   jcc(Assembler::parity, L);
 157 }
 158 
 159 void MacroAssembler::jnC2(Register tmp, Label& L) {
 160   // set parity bit if FPU flag C2 is set (via rax)
 161   save_rax(tmp);
 162   fwait(); fnstsw_ax();
 163   sahf();
 164   restore_rax(tmp);
 165   // branch
 166   jcc(Assembler::noParity, L);
 167 }
 168 
 169 // 32bit can do a case table jump in one instruction but we no longer allow the base
 170 // to be installed in the Address class
 171 void MacroAssembler::jump(ArrayAddress entry) {
 172   jmp(as_Address(entry));
 173 }
 174 
 175 // Note: y_lo will be destroyed
 176 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 177   // Long compare for Java (semantics as described in JVM spec.)
 178   Label high, low, done;
 179 
 180   cmpl(x_hi, y_hi);
 181   jcc(Assembler::less, low);
 182   jcc(Assembler::greater, high);
 183   // x_hi is the return register
 184   xorl(x_hi, x_hi);
 185   cmpl(x_lo, y_lo);
 186   jcc(Assembler::below, low);
 187   jcc(Assembler::equal, done);
 188 
 189   bind(high);
 190   xorl(x_hi, x_hi);
 191   increment(x_hi);
 192   jmp(done);
 193 
 194   bind(low);
 195   xorl(x_hi, x_hi);
 196   decrementl(x_hi);
 197 
 198   bind(done);
 199 }
 200 
 201 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 202     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 203 }
 204 
 205 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 206   // leal(dst, as_Address(adr));
 207   // see note in movl as to why we must use a move
 208   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 209 }
 210 
 211 void MacroAssembler::leave() {
 212   mov(rsp, rbp);
 213   pop(rbp);
 214 }
 215 
 216 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 217   // Multiplication of two Java long values stored on the stack
 218   // as illustrated below. Result is in rdx:rax.
 219   //
 220   // rsp ---> [  ??  ] \               \
 221   //            ....    | y_rsp_offset  |
 222   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 223   //          [ y_hi ]                  | (in bytes)
 224   //            ....                    |
 225   //          [ x_lo ]                 /
 226   //          [ x_hi ]
 227   //            ....
 228   //
 229   // Basic idea: lo(result) = lo(x_lo * y_lo)
 230   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 231   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 232   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 233   Label quick;
 234   // load x_hi, y_hi and check if quick
 235   // multiplication is possible
 236   movl(rbx, x_hi);
 237   movl(rcx, y_hi);
 238   movl(rax, rbx);
 239   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 240   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 241   // do full multiplication
 242   // 1st step
 243   mull(y_lo);                                    // x_hi * y_lo
 244   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 245   // 2nd step
 246   movl(rax, x_lo);
 247   mull(rcx);                                     // x_lo * y_hi
 248   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 249   // 3rd step
 250   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 251   movl(rax, x_lo);
 252   mull(y_lo);                                    // x_lo * y_lo
 253   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 254 }
 255 
 256 void MacroAssembler::lneg(Register hi, Register lo) {
 257   negl(lo);
 258   adcl(hi, 0);
 259   negl(hi);
 260 }
 261 
 262 void MacroAssembler::lshl(Register hi, Register lo) {
 263   // Java shift left long support (semantics as described in JVM spec., p.305)
 264   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 265   // shift value is in rcx !
 266   assert(hi != rcx, "must not use rcx");
 267   assert(lo != rcx, "must not use rcx");
 268   const Register s = rcx;                        // shift count
 269   const int      n = BitsPerWord;
 270   Label L;
 271   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 272   cmpl(s, n);                                    // if (s < n)
 273   jcc(Assembler::less, L);                       // else (s >= n)
 274   movl(hi, lo);                                  // x := x << n
 275   xorl(lo, lo);
 276   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 277   bind(L);                                       // s (mod n) < n
 278   shldl(hi, lo);                                 // x := x << s
 279   shll(lo);
 280 }
 281 
 282 
 283 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 284   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 285   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 286   assert(hi != rcx, "must not use rcx");
 287   assert(lo != rcx, "must not use rcx");
 288   const Register s = rcx;                        // shift count
 289   const int      n = BitsPerWord;
 290   Label L;
 291   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 292   cmpl(s, n);                                    // if (s < n)
 293   jcc(Assembler::less, L);                       // else (s >= n)
 294   movl(lo, hi);                                  // x := x >> n
 295   if (sign_extension) sarl(hi, 31);
 296   else                xorl(hi, hi);
 297   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 298   bind(L);                                       // s (mod n) < n
 299   shrdl(lo, hi);                                 // x := x >> s
 300   if (sign_extension) sarl(hi);
 301   else                shrl(hi);
 302 }
 303 
 304 void MacroAssembler::movoop(Register dst, jobject obj) {
 305   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 306 }
 307 
 308 void MacroAssembler::movoop(Address dst, jobject obj) {
 309   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 310 }
 311 
 312 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 313   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 314 }
 315 
 316 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 317   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 318 }
 319 
 320 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 321   // scratch register is not used,
 322   // it is defined to match parameters of 64-bit version of this method.
 323   if (src.is_lval()) {
 324     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 325   } else {
 326     movl(dst, as_Address(src));
 327   }
 328 }
 329 
 330 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 331   movl(as_Address(dst), src);
 332 }
 333 
 334 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 335   movl(dst, as_Address(src));
 336 }
 337 
 338 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 339 void MacroAssembler::movptr(Address dst, intptr_t src) {
 340   movl(dst, src);
 341 }
 342 
 343 
 344 void MacroAssembler::pop_callee_saved_registers() {
 345   pop(rcx);
 346   pop(rdx);
 347   pop(rdi);
 348   pop(rsi);
 349 }
 350 
 351 void MacroAssembler::pop_fTOS() {
 352   fld_d(Address(rsp, 0));
 353   addl(rsp, 2 * wordSize);
 354 }
 355 
 356 void MacroAssembler::push_callee_saved_registers() {
 357   push(rsi);
 358   push(rdi);
 359   push(rdx);
 360   push(rcx);
 361 }
 362 
 363 void MacroAssembler::push_fTOS() {
 364   subl(rsp, 2 * wordSize);
 365   fstp_d(Address(rsp, 0));
 366 }
 367 
 368 
 369 void MacroAssembler::pushoop(jobject obj) {
 370   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 371 }
 372 
 373 void MacroAssembler::pushklass(Metadata* obj) {
 374   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 375 }
 376 
 377 void MacroAssembler::pushptr(AddressLiteral src) {
 378   if (src.is_lval()) {
 379     push_literal32((int32_t)src.target(), src.rspec());
 380   } else {
 381     pushl(as_Address(src));
 382   }
 383 }
 384 
 385 void MacroAssembler::set_word_if_not_zero(Register dst) {
 386   xorl(dst, dst);
 387   set_byte_if_not_zero(dst);
 388 }
 389 
 390 static void pass_arg0(MacroAssembler* masm, Register arg) {
 391   masm->push(arg);
 392 }
 393 
 394 static void pass_arg1(MacroAssembler* masm, Register arg) {
 395   masm->push(arg);
 396 }
 397 
 398 static void pass_arg2(MacroAssembler* masm, Register arg) {
 399   masm->push(arg);
 400 }
 401 
 402 static void pass_arg3(MacroAssembler* masm, Register arg) {
 403   masm->push(arg);
 404 }
 405 
 406 #ifndef PRODUCT
 407 extern "C" void findpc(intptr_t x);
 408 #endif
 409 
 410 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 411   // In order to get locks to work, we need to fake a in_VM state
 412   JavaThread* thread = JavaThread::current();
 413   JavaThreadState saved_state = thread->thread_state();
 414   thread->set_thread_state(_thread_in_vm);
 415   if (ShowMessageBoxOnError) {
 416     JavaThread* thread = JavaThread::current();
 417     JavaThreadState saved_state = thread->thread_state();
 418     thread->set_thread_state(_thread_in_vm);
 419     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 420       ttyLocker ttyl;
 421       BytecodeCounter::print();
 422     }
 423     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 424     // This is the value of eip which points to where verify_oop will return.
 425     if (os::message_box(msg, "Execution stopped, print registers?")) {
 426       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 427       BREAKPOINT;
 428     }
 429   } else {
 430     ttyLocker ttyl;
 431     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 432   }
 433   // Don't assert holding the ttyLock
 434     assert(false, "DEBUG MESSAGE: %s", msg);
 435   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 436 }
 437 
 438 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 439   ttyLocker ttyl;
 440   FlagSetting fs(Debugging, true);
 441   tty->print_cr("eip = 0x%08x", eip);
 442 #ifndef PRODUCT
 443   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 444     tty->cr();
 445     findpc(eip);
 446     tty->cr();
 447   }
 448 #endif
 449 #define PRINT_REG(rax) \
 450   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 451   PRINT_REG(rax);
 452   PRINT_REG(rbx);
 453   PRINT_REG(rcx);
 454   PRINT_REG(rdx);
 455   PRINT_REG(rdi);
 456   PRINT_REG(rsi);
 457   PRINT_REG(rbp);
 458   PRINT_REG(rsp);
 459 #undef PRINT_REG
 460   // Print some words near top of staack.
 461   int* dump_sp = (int*) rsp;
 462   for (int col1 = 0; col1 < 8; col1++) {
 463     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 464     os::print_location(tty, *dump_sp++);
 465   }
 466   for (int row = 0; row < 16; row++) {
 467     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 468     for (int col = 0; col < 8; col++) {
 469       tty->print(" 0x%08x", *dump_sp++);
 470     }
 471     tty->cr();
 472   }
 473   // Print some instructions around pc:
 474   Disassembler::decode((address)eip-64, (address)eip);
 475   tty->print_cr("--------");
 476   Disassembler::decode((address)eip, (address)eip+32);
 477 }
 478 
 479 void MacroAssembler::stop(const char* msg) {
 480   ExternalAddress message((address)msg);
 481   // push address of message
 482   pushptr(message.addr());
 483   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 484   pusha();                                            // push registers
 485   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 486   hlt();
 487 }
 488 
 489 void MacroAssembler::warn(const char* msg) {
 490   push_CPU_state();
 491 
 492   ExternalAddress message((address) msg);
 493   // push address of message
 494   pushptr(message.addr());
 495 
 496   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 497   addl(rsp, wordSize);       // discard argument
 498   pop_CPU_state();
 499 }
 500 
 501 void MacroAssembler::print_state() {
 502   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 503   pusha();                                            // push registers
 504 
 505   push_CPU_state();
 506   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 507   pop_CPU_state();
 508 
 509   popa();
 510   addl(rsp, wordSize);
 511 }
 512 
 513 #else // _LP64
 514 
 515 // 64 bit versions
 516 
 517 Address MacroAssembler::as_Address(AddressLiteral adr) {
 518   // amd64 always does this as a pc-rel
 519   // we can be absolute or disp based on the instruction type
 520   // jmp/call are displacements others are absolute
 521   assert(!adr.is_lval(), "must be rval");
 522   assert(reachable(adr), "must be");
 523   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 524 
 525 }
 526 
 527 Address MacroAssembler::as_Address(ArrayAddress adr) {
 528   AddressLiteral base = adr.base();
 529   lea(rscratch1, base);
 530   Address index = adr.index();
 531   assert(index._disp == 0, "must not have disp"); // maybe it can?
 532   Address array(rscratch1, index._index, index._scale, index._disp);
 533   return array;
 534 }
 535 
 536 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 537   Label L, E;
 538 
 539 #ifdef _WIN64
 540   // Windows always allocates space for it's register args
 541   assert(num_args <= 4, "only register arguments supported");
 542   subq(rsp,  frame::arg_reg_save_area_bytes);
 543 #endif
 544 
 545   // Align stack if necessary
 546   testl(rsp, 15);
 547   jcc(Assembler::zero, L);
 548 
 549   subq(rsp, 8);
 550   {
 551     call(RuntimeAddress(entry_point));
 552   }
 553   addq(rsp, 8);
 554   jmp(E);
 555 
 556   bind(L);
 557   {
 558     call(RuntimeAddress(entry_point));
 559   }
 560 
 561   bind(E);
 562 
 563 #ifdef _WIN64
 564   // restore stack pointer
 565   addq(rsp, frame::arg_reg_save_area_bytes);
 566 #endif
 567 
 568 }
 569 
 570 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 571   assert(!src2.is_lval(), "should use cmpptr");
 572 
 573   if (reachable(src2)) {
 574     cmpq(src1, as_Address(src2));
 575   } else {
 576     lea(rscratch1, src2);
 577     Assembler::cmpq(src1, Address(rscratch1, 0));
 578   }
 579 }
 580 
 581 int MacroAssembler::corrected_idivq(Register reg) {
 582   // Full implementation of Java ldiv and lrem; checks for special
 583   // case as described in JVM spec., p.243 & p.271.  The function
 584   // returns the (pc) offset of the idivl instruction - may be needed
 585   // for implicit exceptions.
 586   //
 587   //         normal case                           special case
 588   //
 589   // input : rax: dividend                         min_long
 590   //         reg: divisor   (may not be eax/edx)   -1
 591   //
 592   // output: rax: quotient  (= rax idiv reg)       min_long
 593   //         rdx: remainder (= rax irem reg)       0
 594   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 595   static const int64_t min_long = 0x8000000000000000;
 596   Label normal_case, special_case;
 597 
 598   // check for special case
 599   cmp64(rax, ExternalAddress((address) &min_long));
 600   jcc(Assembler::notEqual, normal_case);
 601   xorl(rdx, rdx); // prepare rdx for possible special case (where
 602                   // remainder = 0)
 603   cmpq(reg, -1);
 604   jcc(Assembler::equal, special_case);
 605 
 606   // handle normal case
 607   bind(normal_case);
 608   cdqq();
 609   int idivq_offset = offset();
 610   idivq(reg);
 611 
 612   // normal and special case exit
 613   bind(special_case);
 614 
 615   return idivq_offset;
 616 }
 617 
 618 void MacroAssembler::decrementq(Register reg, int value) {
 619   if (value == min_jint) { subq(reg, value); return; }
 620   if (value <  0) { incrementq(reg, -value); return; }
 621   if (value == 0) {                        ; return; }
 622   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 623   /* else */      { subq(reg, value)       ; return; }
 624 }
 625 
 626 void MacroAssembler::decrementq(Address dst, int value) {
 627   if (value == min_jint) { subq(dst, value); return; }
 628   if (value <  0) { incrementq(dst, -value); return; }
 629   if (value == 0) {                        ; return; }
 630   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 631   /* else */      { subq(dst, value)       ; return; }
 632 }
 633 
 634 void MacroAssembler::incrementq(AddressLiteral dst) {
 635   if (reachable(dst)) {
 636     incrementq(as_Address(dst));
 637   } else {
 638     lea(rscratch1, dst);
 639     incrementq(Address(rscratch1, 0));
 640   }
 641 }
 642 
 643 void MacroAssembler::incrementq(Register reg, int value) {
 644   if (value == min_jint) { addq(reg, value); return; }
 645   if (value <  0) { decrementq(reg, -value); return; }
 646   if (value == 0) {                        ; return; }
 647   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 648   /* else */      { addq(reg, value)       ; return; }
 649 }
 650 
 651 void MacroAssembler::incrementq(Address dst, int value) {
 652   if (value == min_jint) { addq(dst, value); return; }
 653   if (value <  0) { decrementq(dst, -value); return; }
 654   if (value == 0) {                        ; return; }
 655   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 656   /* else */      { addq(dst, value)       ; return; }
 657 }
 658 
 659 // 32bit can do a case table jump in one instruction but we no longer allow the base
 660 // to be installed in the Address class
 661 void MacroAssembler::jump(ArrayAddress entry) {
 662   lea(rscratch1, entry.base());
 663   Address dispatch = entry.index();
 664   assert(dispatch._base == noreg, "must be");
 665   dispatch._base = rscratch1;
 666   jmp(dispatch);
 667 }
 668 
 669 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 670   ShouldNotReachHere(); // 64bit doesn't use two regs
 671   cmpq(x_lo, y_lo);
 672 }
 673 
 674 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 675     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 676 }
 677 
 678 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 679   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 680   movptr(dst, rscratch1);
 681 }
 682 
 683 void MacroAssembler::leave() {
 684   // %%% is this really better? Why not on 32bit too?
 685   emit_int8((unsigned char)0xC9); // LEAVE
 686 }
 687 
 688 void MacroAssembler::lneg(Register hi, Register lo) {
 689   ShouldNotReachHere(); // 64bit doesn't use two regs
 690   negq(lo);
 691 }
 692 
 693 void MacroAssembler::movoop(Register dst, jobject obj) {
 694   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 695 }
 696 
 697 void MacroAssembler::movoop(Address dst, jobject obj) {
 698   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 699   movq(dst, rscratch1);
 700 }
 701 
 702 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 703   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 704 }
 705 
 706 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 707   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 708   movq(dst, rscratch1);
 709 }
 710 
 711 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 712   if (src.is_lval()) {
 713     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 714   } else {
 715     if (reachable(src)) {
 716       movq(dst, as_Address(src));
 717     } else {
 718       lea(scratch, src);
 719       movq(dst, Address(scratch, 0));
 720     }
 721   }
 722 }
 723 
 724 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 725   movq(as_Address(dst), src);
 726 }
 727 
 728 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 729   movq(dst, as_Address(src));
 730 }
 731 
 732 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 733 void MacroAssembler::movptr(Address dst, intptr_t src) {
 734   mov64(rscratch1, src);
 735   movq(dst, rscratch1);
 736 }
 737 
 738 // These are mostly for initializing NULL
 739 void MacroAssembler::movptr(Address dst, int32_t src) {
 740   movslq(dst, src);
 741 }
 742 
 743 void MacroAssembler::movptr(Register dst, int32_t src) {
 744   mov64(dst, (intptr_t)src);
 745 }
 746 
 747 void MacroAssembler::pushoop(jobject obj) {
 748   movoop(rscratch1, obj);
 749   push(rscratch1);
 750 }
 751 
 752 void MacroAssembler::pushklass(Metadata* obj) {
 753   mov_metadata(rscratch1, obj);
 754   push(rscratch1);
 755 }
 756 
 757 void MacroAssembler::pushptr(AddressLiteral src) {
 758   lea(rscratch1, src);
 759   if (src.is_lval()) {
 760     push(rscratch1);
 761   } else {
 762     pushq(Address(rscratch1, 0));
 763   }
 764 }
 765 
 766 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 767   // we must set sp to zero to clear frame
 768   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 769   // must clear fp, so that compiled frames are not confused; it is
 770   // possible that we need it only for debugging
 771   if (clear_fp) {
 772     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 773   }
 774 
 775   // Always clear the pc because it could have been set by make_walkable()
 776   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 777   vzeroupper();
 778 }
 779 
 780 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 781                                          Register last_java_fp,
 782                                          address  last_java_pc) {
 783   vzeroupper();
 784   // determine last_java_sp register
 785   if (!last_java_sp->is_valid()) {
 786     last_java_sp = rsp;
 787   }
 788 
 789   // last_java_fp is optional
 790   if (last_java_fp->is_valid()) {
 791     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 792            last_java_fp);
 793   }
 794 
 795   // last_java_pc is optional
 796   if (last_java_pc != NULL) {
 797     Address java_pc(r15_thread,
 798                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 799     lea(rscratch1, InternalAddress(last_java_pc));
 800     movptr(java_pc, rscratch1);
 801   }
 802 
 803   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 804 }
 805 
 806 static void pass_arg0(MacroAssembler* masm, Register arg) {
 807   if (c_rarg0 != arg ) {
 808     masm->mov(c_rarg0, arg);
 809   }
 810 }
 811 
 812 static void pass_arg1(MacroAssembler* masm, Register arg) {
 813   if (c_rarg1 != arg ) {
 814     masm->mov(c_rarg1, arg);
 815   }
 816 }
 817 
 818 static void pass_arg2(MacroAssembler* masm, Register arg) {
 819   if (c_rarg2 != arg ) {
 820     masm->mov(c_rarg2, arg);
 821   }
 822 }
 823 
 824 static void pass_arg3(MacroAssembler* masm, Register arg) {
 825   if (c_rarg3 != arg ) {
 826     masm->mov(c_rarg3, arg);
 827   }
 828 }
 829 
 830 void MacroAssembler::stop(const char* msg) {
 831   address rip = pc();
 832   pusha(); // get regs on stack
 833   lea(c_rarg0, ExternalAddress((address) msg));
 834   lea(c_rarg1, InternalAddress(rip));
 835   movq(c_rarg2, rsp); // pass pointer to regs array
 836   andq(rsp, -16); // align stack as required by ABI
 837   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 838   hlt();
 839 }
 840 
 841 void MacroAssembler::warn(const char* msg) {
 842   push(rbp);
 843   movq(rbp, rsp);
 844   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 845   push_CPU_state();   // keeps alignment at 16 bytes
 846   lea(c_rarg0, ExternalAddress((address) msg));
 847   lea(rax, ExternalAddress(CAST_FROM_FN_PTR(address, warning)));
 848   call(rax);
 849   pop_CPU_state();
 850   mov(rsp, rbp);
 851   pop(rbp);
 852 }
 853 
 854 void MacroAssembler::print_state() {
 855   address rip = pc();
 856   pusha();            // get regs on stack
 857   push(rbp);
 858   movq(rbp, rsp);
 859   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 860   push_CPU_state();   // keeps alignment at 16 bytes
 861 
 862   lea(c_rarg0, InternalAddress(rip));
 863   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 864   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 865 
 866   pop_CPU_state();
 867   mov(rsp, rbp);
 868   pop(rbp);
 869   popa();
 870 }
 871 
 872 #ifndef PRODUCT
 873 extern "C" void findpc(intptr_t x);
 874 #endif
 875 
 876 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 877   // In order to get locks to work, we need to fake a in_VM state
 878   if (ShowMessageBoxOnError) {
 879     JavaThread* thread = JavaThread::current();
 880     JavaThreadState saved_state = thread->thread_state();
 881     thread->set_thread_state(_thread_in_vm);
 882 #ifndef PRODUCT
 883     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 884       ttyLocker ttyl;
 885       BytecodeCounter::print();
 886     }
 887 #endif
 888     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 889     // XXX correct this offset for amd64
 890     // This is the value of eip which points to where verify_oop will return.
 891     if (os::message_box(msg, "Execution stopped, print registers?")) {
 892       print_state64(pc, regs);
 893       BREAKPOINT;
 894       assert(false, "start up GDB");
 895     }
 896     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 897   } else {
 898     ttyLocker ttyl;
 899     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 900                     msg);
 901     assert(false, "DEBUG MESSAGE: %s", msg);
 902   }
 903 }
 904 
 905 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 906   ttyLocker ttyl;
 907   FlagSetting fs(Debugging, true);
 908   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 909 #ifndef PRODUCT
 910   tty->cr();
 911   findpc(pc);
 912   tty->cr();
 913 #endif
 914 #define PRINT_REG(rax, value) \
 915   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 916   PRINT_REG(rax, regs[15]);
 917   PRINT_REG(rbx, regs[12]);
 918   PRINT_REG(rcx, regs[14]);
 919   PRINT_REG(rdx, regs[13]);
 920   PRINT_REG(rdi, regs[8]);
 921   PRINT_REG(rsi, regs[9]);
 922   PRINT_REG(rbp, regs[10]);
 923   PRINT_REG(rsp, regs[11]);
 924   PRINT_REG(r8 , regs[7]);
 925   PRINT_REG(r9 , regs[6]);
 926   PRINT_REG(r10, regs[5]);
 927   PRINT_REG(r11, regs[4]);
 928   PRINT_REG(r12, regs[3]);
 929   PRINT_REG(r13, regs[2]);
 930   PRINT_REG(r14, regs[1]);
 931   PRINT_REG(r15, regs[0]);
 932 #undef PRINT_REG
 933   // Print some words near top of staack.
 934   int64_t* rsp = (int64_t*) regs[11];
 935   int64_t* dump_sp = rsp;
 936   for (int col1 = 0; col1 < 8; col1++) {
 937     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 938     os::print_location(tty, *dump_sp++);
 939   }
 940   for (int row = 0; row < 25; row++) {
 941     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 942     for (int col = 0; col < 4; col++) {
 943       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 944     }
 945     tty->cr();
 946   }
 947   // Print some instructions around pc:
 948   Disassembler::decode((address)pc-64, (address)pc);
 949   tty->print_cr("--------");
 950   Disassembler::decode((address)pc, (address)pc+32);
 951 }
 952 
 953 #endif // _LP64
 954 
 955 // Now versions that are common to 32/64 bit
 956 
 957 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 958   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 959 }
 960 
 961 void MacroAssembler::addptr(Register dst, Register src) {
 962   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 963 }
 964 
 965 void MacroAssembler::addptr(Address dst, Register src) {
 966   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 967 }
 968 
 969 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 970   if (reachable(src)) {
 971     Assembler::addsd(dst, as_Address(src));
 972   } else {
 973     lea(rscratch1, src);
 974     Assembler::addsd(dst, Address(rscratch1, 0));
 975   }
 976 }
 977 
 978 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 979   if (reachable(src)) {
 980     addss(dst, as_Address(src));
 981   } else {
 982     lea(rscratch1, src);
 983     addss(dst, Address(rscratch1, 0));
 984   }
 985 }
 986 
 987 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 988   if (reachable(src)) {
 989     Assembler::addpd(dst, as_Address(src));
 990   } else {
 991     lea(rscratch1, src);
 992     Assembler::addpd(dst, Address(rscratch1, 0));
 993   }
 994 }
 995 
 996 void MacroAssembler::align(int modulus) {
 997   align(modulus, offset());
 998 }
 999 
1000 void MacroAssembler::align(int modulus, int target) {
1001   if (target % modulus != 0) {
1002     nop(modulus - (target % modulus));
1003   }
1004 }
1005 
1006 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
1007   // Used in sign-masking with aligned address.
1008   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1009   if (reachable(src)) {
1010     Assembler::andpd(dst, as_Address(src));
1011   } else {
1012     lea(rscratch1, src);
1013     Assembler::andpd(dst, Address(rscratch1, 0));
1014   }
1015 }
1016 
1017 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1018   // Used in sign-masking with aligned address.
1019   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1020   if (reachable(src)) {
1021     Assembler::andps(dst, as_Address(src));
1022   } else {
1023     lea(rscratch1, src);
1024     Assembler::andps(dst, Address(rscratch1, 0));
1025   }
1026 }
1027 
1028 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1029   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1030 }
1031 
1032 void MacroAssembler::atomic_incl(Address counter_addr) {
1033   if (os::is_MP())
1034     lock();
1035   incrementl(counter_addr);
1036 }
1037 
1038 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1039   if (reachable(counter_addr)) {
1040     atomic_incl(as_Address(counter_addr));
1041   } else {
1042     lea(scr, counter_addr);
1043     atomic_incl(Address(scr, 0));
1044   }
1045 }
1046 
1047 #ifdef _LP64
1048 void MacroAssembler::atomic_incq(Address counter_addr) {
1049   if (os::is_MP())
1050     lock();
1051   incrementq(counter_addr);
1052 }
1053 
1054 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1055   if (reachable(counter_addr)) {
1056     atomic_incq(as_Address(counter_addr));
1057   } else {
1058     lea(scr, counter_addr);
1059     atomic_incq(Address(scr, 0));
1060   }
1061 }
1062 #endif
1063 
1064 // Writes to stack successive pages until offset reached to check for
1065 // stack overflow + shadow pages.  This clobbers tmp.
1066 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1067   movptr(tmp, rsp);
1068   // Bang stack for total size given plus shadow page size.
1069   // Bang one page at a time because large size can bang beyond yellow and
1070   // red zones.
1071   Label loop;
1072   bind(loop);
1073   movl(Address(tmp, (-os::vm_page_size())), size );
1074   subptr(tmp, os::vm_page_size());
1075   subl(size, os::vm_page_size());
1076   jcc(Assembler::greater, loop);
1077 
1078   // Bang down shadow pages too.
1079   // At this point, (tmp-0) is the last address touched, so don't
1080   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1081   // was post-decremented.)  Skip this address by starting at i=1, and
1082   // touch a few more pages below.  N.B.  It is important to touch all
1083   // the way down including all pages in the shadow zone.
1084   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1085     // this could be any sized move but this is can be a debugging crumb
1086     // so the bigger the better.
1087     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1088   }
1089 }
1090 
1091 void MacroAssembler::reserved_stack_check() {
1092     // testing if reserved zone needs to be enabled
1093     Label no_reserved_zone_enabling;
1094     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1095     NOT_LP64(get_thread(rsi);)
1096 
1097     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1098     jcc(Assembler::below, no_reserved_zone_enabling);
1099 
1100     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1101     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1102     should_not_reach_here();
1103 
1104     bind(no_reserved_zone_enabling);
1105 }
1106 
1107 int MacroAssembler::biased_locking_enter(Register lock_reg,
1108                                          Register obj_reg,
1109                                          Register swap_reg,
1110                                          Register tmp_reg,
1111                                          bool swap_reg_contains_mark,
1112                                          Label& done,
1113                                          Label* slow_case,
1114                                          BiasedLockingCounters* counters) {
1115   assert(UseBiasedLocking, "why call this otherwise?");
1116   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1117   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1118   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1119   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1120   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1121   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1122 
1123   if (PrintBiasedLockingStatistics && counters == NULL) {
1124     counters = BiasedLocking::counters();
1125   }
1126   // Biased locking
1127   // See whether the lock is currently biased toward our thread and
1128   // whether the epoch is still valid
1129   // Note that the runtime guarantees sufficient alignment of JavaThread
1130   // pointers to allow age to be placed into low bits
1131   // First check to see whether biasing is even enabled for this object
1132   Label cas_label;
1133   int null_check_offset = -1;
1134   if (!swap_reg_contains_mark) {
1135     null_check_offset = offset();
1136     movptr(swap_reg, mark_addr);
1137   }
1138   movptr(tmp_reg, swap_reg);
1139   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1140   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1141   jcc(Assembler::notEqual, cas_label);
1142   // The bias pattern is present in the object's header. Need to check
1143   // whether the bias owner and the epoch are both still current.
1144 #ifndef _LP64
1145   // Note that because there is no current thread register on x86_32 we
1146   // need to store off the mark word we read out of the object to
1147   // avoid reloading it and needing to recheck invariants below. This
1148   // store is unfortunate but it makes the overall code shorter and
1149   // simpler.
1150   movptr(saved_mark_addr, swap_reg);
1151 #endif
1152   if (swap_reg_contains_mark) {
1153     null_check_offset = offset();
1154   }
1155   load_prototype_header(tmp_reg, obj_reg);
1156 #ifdef _LP64
1157   orptr(tmp_reg, r15_thread);
1158   xorptr(tmp_reg, swap_reg);
1159   Register header_reg = tmp_reg;
1160 #else
1161   xorptr(tmp_reg, swap_reg);
1162   get_thread(swap_reg);
1163   xorptr(swap_reg, tmp_reg);
1164   Register header_reg = swap_reg;
1165 #endif
1166   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1167   if (counters != NULL) {
1168     cond_inc32(Assembler::zero,
1169                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1170   }
1171   jcc(Assembler::equal, done);
1172 
1173   Label try_revoke_bias;
1174   Label try_rebias;
1175 
1176   // At this point we know that the header has the bias pattern and
1177   // that we are not the bias owner in the current epoch. We need to
1178   // figure out more details about the state of the header in order to
1179   // know what operations can be legally performed on the object's
1180   // header.
1181 
1182   // If the low three bits in the xor result aren't clear, that means
1183   // the prototype header is no longer biased and we have to revoke
1184   // the bias on this object.
1185   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1186   jccb(Assembler::notZero, try_revoke_bias);
1187 
1188   // Biasing is still enabled for this data type. See whether the
1189   // epoch of the current bias is still valid, meaning that the epoch
1190   // bits of the mark word are equal to the epoch bits of the
1191   // prototype header. (Note that the prototype header's epoch bits
1192   // only change at a safepoint.) If not, attempt to rebias the object
1193   // toward the current thread. Note that we must be absolutely sure
1194   // that the current epoch is invalid in order to do this because
1195   // otherwise the manipulations it performs on the mark word are
1196   // illegal.
1197   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1198   jccb(Assembler::notZero, try_rebias);
1199 
1200   // The epoch of the current bias is still valid but we know nothing
1201   // about the owner; it might be set or it might be clear. Try to
1202   // acquire the bias of the object using an atomic operation. If this
1203   // fails we will go in to the runtime to revoke the object's bias.
1204   // Note that we first construct the presumed unbiased header so we
1205   // don't accidentally blow away another thread's valid bias.
1206   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1207   andptr(swap_reg,
1208          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1209 #ifdef _LP64
1210   movptr(tmp_reg, swap_reg);
1211   orptr(tmp_reg, r15_thread);
1212 #else
1213   get_thread(tmp_reg);
1214   orptr(tmp_reg, swap_reg);
1215 #endif
1216   if (os::is_MP()) {
1217     lock();
1218   }
1219   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1220   // If the biasing toward our thread failed, this means that
1221   // another thread succeeded in biasing it toward itself and we
1222   // need to revoke that bias. The revocation will occur in the
1223   // interpreter runtime in the slow case.
1224   if (counters != NULL) {
1225     cond_inc32(Assembler::zero,
1226                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1227   }
1228   if (slow_case != NULL) {
1229     jcc(Assembler::notZero, *slow_case);
1230   }
1231   jmp(done);
1232 
1233   bind(try_rebias);
1234   // At this point we know the epoch has expired, meaning that the
1235   // current "bias owner", if any, is actually invalid. Under these
1236   // circumstances _only_, we are allowed to use the current header's
1237   // value as the comparison value when doing the cas to acquire the
1238   // bias in the current epoch. In other words, we allow transfer of
1239   // the bias from one thread to another directly in this situation.
1240   //
1241   // FIXME: due to a lack of registers we currently blow away the age
1242   // bits in this situation. Should attempt to preserve them.
1243   load_prototype_header(tmp_reg, obj_reg);
1244 #ifdef _LP64
1245   orptr(tmp_reg, r15_thread);
1246 #else
1247   get_thread(swap_reg);
1248   orptr(tmp_reg, swap_reg);
1249   movptr(swap_reg, saved_mark_addr);
1250 #endif
1251   if (os::is_MP()) {
1252     lock();
1253   }
1254   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1255   // If the biasing toward our thread failed, then another thread
1256   // succeeded in biasing it toward itself and we need to revoke that
1257   // bias. The revocation will occur in the runtime in the slow case.
1258   if (counters != NULL) {
1259     cond_inc32(Assembler::zero,
1260                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1261   }
1262   if (slow_case != NULL) {
1263     jcc(Assembler::notZero, *slow_case);
1264   }
1265   jmp(done);
1266 
1267   bind(try_revoke_bias);
1268   // The prototype mark in the klass doesn't have the bias bit set any
1269   // more, indicating that objects of this data type are not supposed
1270   // to be biased any more. We are going to try to reset the mark of
1271   // this object to the prototype value and fall through to the
1272   // CAS-based locking scheme. Note that if our CAS fails, it means
1273   // that another thread raced us for the privilege of revoking the
1274   // bias of this particular object, so it's okay to continue in the
1275   // normal locking code.
1276   //
1277   // FIXME: due to a lack of registers we currently blow away the age
1278   // bits in this situation. Should attempt to preserve them.
1279   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1280   load_prototype_header(tmp_reg, obj_reg);
1281   if (os::is_MP()) {
1282     lock();
1283   }
1284   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1285   // Fall through to the normal CAS-based lock, because no matter what
1286   // the result of the above CAS, some thread must have succeeded in
1287   // removing the bias bit from the object's header.
1288   if (counters != NULL) {
1289     cond_inc32(Assembler::zero,
1290                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1291   }
1292 
1293   bind(cas_label);
1294 
1295   return null_check_offset;
1296 }
1297 
1298 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1299   assert(UseBiasedLocking, "why call this otherwise?");
1300 
1301   // Check for biased locking unlock case, which is a no-op
1302   // Note: we do not have to check the thread ID for two reasons.
1303   // First, the interpreter checks for IllegalMonitorStateException at
1304   // a higher level. Second, if the bias was revoked while we held the
1305   // lock, the object could not be rebiased toward another thread, so
1306   // the bias bit would be clear.
1307   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1308   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1309   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1310   jcc(Assembler::equal, done);
1311 }
1312 
1313 #ifdef COMPILER2
1314 
1315 #if INCLUDE_RTM_OPT
1316 
1317 // Update rtm_counters based on abort status
1318 // input: abort_status
1319 //        rtm_counters (RTMLockingCounters*)
1320 // flags are killed
1321 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1322 
1323   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1324   if (PrintPreciseRTMLockingStatistics) {
1325     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1326       Label check_abort;
1327       testl(abort_status, (1<<i));
1328       jccb(Assembler::equal, check_abort);
1329       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1330       bind(check_abort);
1331     }
1332   }
1333 }
1334 
1335 // Branch if (random & (count-1) != 0), count is 2^n
1336 // tmp, scr and flags are killed
1337 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1338   assert(tmp == rax, "");
1339   assert(scr == rdx, "");
1340   rdtsc(); // modifies EDX:EAX
1341   andptr(tmp, count-1);
1342   jccb(Assembler::notZero, brLabel);
1343 }
1344 
1345 // Perform abort ratio calculation, set no_rtm bit if high ratio
1346 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1347 // tmpReg, rtm_counters_Reg and flags are killed
1348 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1349                                                  Register rtm_counters_Reg,
1350                                                  RTMLockingCounters* rtm_counters,
1351                                                  Metadata* method_data) {
1352   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1353 
1354   if (RTMLockingCalculationDelay > 0) {
1355     // Delay calculation
1356     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1357     testptr(tmpReg, tmpReg);
1358     jccb(Assembler::equal, L_done);
1359   }
1360   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1361   //   Aborted transactions = abort_count * 100
1362   //   All transactions = total_count *  RTMTotalCountIncrRate
1363   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1364 
1365   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1366   cmpptr(tmpReg, RTMAbortThreshold);
1367   jccb(Assembler::below, L_check_always_rtm2);
1368   imulptr(tmpReg, tmpReg, 100);
1369 
1370   Register scrReg = rtm_counters_Reg;
1371   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1372   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1373   imulptr(scrReg, scrReg, RTMAbortRatio);
1374   cmpptr(tmpReg, scrReg);
1375   jccb(Assembler::below, L_check_always_rtm1);
1376   if (method_data != NULL) {
1377     // set rtm_state to "no rtm" in MDO
1378     mov_metadata(tmpReg, method_data);
1379     if (os::is_MP()) {
1380       lock();
1381     }
1382     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1383   }
1384   jmpb(L_done);
1385   bind(L_check_always_rtm1);
1386   // Reload RTMLockingCounters* address
1387   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1388   bind(L_check_always_rtm2);
1389   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1390   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1391   jccb(Assembler::below, L_done);
1392   if (method_data != NULL) {
1393     // set rtm_state to "always rtm" in MDO
1394     mov_metadata(tmpReg, method_data);
1395     if (os::is_MP()) {
1396       lock();
1397     }
1398     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1399   }
1400   bind(L_done);
1401 }
1402 
1403 // Update counters and perform abort ratio calculation
1404 // input:  abort_status_Reg
1405 // rtm_counters_Reg, flags are killed
1406 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1407                                    Register rtm_counters_Reg,
1408                                    RTMLockingCounters* rtm_counters,
1409                                    Metadata* method_data,
1410                                    bool profile_rtm) {
1411 
1412   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1413   // update rtm counters based on rax value at abort
1414   // reads abort_status_Reg, updates flags
1415   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1416   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1417   if (profile_rtm) {
1418     // Save abort status because abort_status_Reg is used by following code.
1419     if (RTMRetryCount > 0) {
1420       push(abort_status_Reg);
1421     }
1422     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1423     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1424     // restore abort status
1425     if (RTMRetryCount > 0) {
1426       pop(abort_status_Reg);
1427     }
1428   }
1429 }
1430 
1431 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1432 // inputs: retry_count_Reg
1433 //       : abort_status_Reg
1434 // output: retry_count_Reg decremented by 1
1435 // flags are killed
1436 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1437   Label doneRetry;
1438   assert(abort_status_Reg == rax, "");
1439   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1440   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1441   // if reason is in 0x6 and retry count != 0 then retry
1442   andptr(abort_status_Reg, 0x6);
1443   jccb(Assembler::zero, doneRetry);
1444   testl(retry_count_Reg, retry_count_Reg);
1445   jccb(Assembler::zero, doneRetry);
1446   pause();
1447   decrementl(retry_count_Reg);
1448   jmp(retryLabel);
1449   bind(doneRetry);
1450 }
1451 
1452 // Spin and retry if lock is busy,
1453 // inputs: box_Reg (monitor address)
1454 //       : retry_count_Reg
1455 // output: retry_count_Reg decremented by 1
1456 //       : clear z flag if retry count exceeded
1457 // tmp_Reg, scr_Reg, flags are killed
1458 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1459                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1460   Label SpinLoop, SpinExit, doneRetry;
1461   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1462 
1463   testl(retry_count_Reg, retry_count_Reg);
1464   jccb(Assembler::zero, doneRetry);
1465   decrementl(retry_count_Reg);
1466   movptr(scr_Reg, RTMSpinLoopCount);
1467 
1468   bind(SpinLoop);
1469   pause();
1470   decrementl(scr_Reg);
1471   jccb(Assembler::lessEqual, SpinExit);
1472   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1473   testptr(tmp_Reg, tmp_Reg);
1474   jccb(Assembler::notZero, SpinLoop);
1475 
1476   bind(SpinExit);
1477   jmp(retryLabel);
1478   bind(doneRetry);
1479   incrementl(retry_count_Reg); // clear z flag
1480 }
1481 
1482 // Use RTM for normal stack locks
1483 // Input: objReg (object to lock)
1484 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1485                                        Register retry_on_abort_count_Reg,
1486                                        RTMLockingCounters* stack_rtm_counters,
1487                                        Metadata* method_data, bool profile_rtm,
1488                                        Label& DONE_LABEL, Label& IsInflated) {
1489   assert(UseRTMForStackLocks, "why call this otherwise?");
1490   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1491   assert(tmpReg == rax, "");
1492   assert(scrReg == rdx, "");
1493   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1494 
1495   if (RTMRetryCount > 0) {
1496     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1497     bind(L_rtm_retry);
1498   }
1499   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1500   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1501   jcc(Assembler::notZero, IsInflated);
1502 
1503   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1504     Label L_noincrement;
1505     if (RTMTotalCountIncrRate > 1) {
1506       // tmpReg, scrReg and flags are killed
1507       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1508     }
1509     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1510     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1511     bind(L_noincrement);
1512   }
1513   xbegin(L_on_abort);
1514   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1515   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1516   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1517   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1518 
1519   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1520   if (UseRTMXendForLockBusy) {
1521     xend();
1522     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1523     jmp(L_decrement_retry);
1524   }
1525   else {
1526     xabort(0);
1527   }
1528   bind(L_on_abort);
1529   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1530     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1531   }
1532   bind(L_decrement_retry);
1533   if (RTMRetryCount > 0) {
1534     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1535     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1536   }
1537 }
1538 
1539 // Use RTM for inflating locks
1540 // inputs: objReg (object to lock)
1541 //         boxReg (on-stack box address (displaced header location) - KILLED)
1542 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1543 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1544                                           Register scrReg, Register retry_on_busy_count_Reg,
1545                                           Register retry_on_abort_count_Reg,
1546                                           RTMLockingCounters* rtm_counters,
1547                                           Metadata* method_data, bool profile_rtm,
1548                                           Label& DONE_LABEL) {
1549   assert(UseRTMLocking, "why call this otherwise?");
1550   assert(tmpReg == rax, "");
1551   assert(scrReg == rdx, "");
1552   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1553   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1554 
1555   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1556   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1557   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1558 
1559   if (RTMRetryCount > 0) {
1560     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1561     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1562     bind(L_rtm_retry);
1563   }
1564   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1565     Label L_noincrement;
1566     if (RTMTotalCountIncrRate > 1) {
1567       // tmpReg, scrReg and flags are killed
1568       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1569     }
1570     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1571     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1572     bind(L_noincrement);
1573   }
1574   xbegin(L_on_abort);
1575   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1576   movptr(tmpReg, Address(tmpReg, owner_offset));
1577   testptr(tmpReg, tmpReg);
1578   jcc(Assembler::zero, DONE_LABEL);
1579   if (UseRTMXendForLockBusy) {
1580     xend();
1581     jmp(L_decrement_retry);
1582   }
1583   else {
1584     xabort(0);
1585   }
1586   bind(L_on_abort);
1587   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1588   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1589     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1590   }
1591   if (RTMRetryCount > 0) {
1592     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1593     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1594   }
1595 
1596   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1597   testptr(tmpReg, tmpReg) ;
1598   jccb(Assembler::notZero, L_decrement_retry) ;
1599 
1600   // Appears unlocked - try to swing _owner from null to non-null.
1601   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1602 #ifdef _LP64
1603   Register threadReg = r15_thread;
1604 #else
1605   get_thread(scrReg);
1606   Register threadReg = scrReg;
1607 #endif
1608   if (os::is_MP()) {
1609     lock();
1610   }
1611   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1612 
1613   if (RTMRetryCount > 0) {
1614     // success done else retry
1615     jccb(Assembler::equal, DONE_LABEL) ;
1616     bind(L_decrement_retry);
1617     // Spin and retry if lock is busy.
1618     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1619   }
1620   else {
1621     bind(L_decrement_retry);
1622   }
1623 }
1624 
1625 #endif //  INCLUDE_RTM_OPT
1626 
1627 // Fast_Lock and Fast_Unlock used by C2
1628 
1629 // Because the transitions from emitted code to the runtime
1630 // monitorenter/exit helper stubs are so slow it's critical that
1631 // we inline both the stack-locking fast-path and the inflated fast path.
1632 //
1633 // See also: cmpFastLock and cmpFastUnlock.
1634 //
1635 // What follows is a specialized inline transliteration of the code
1636 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1637 // another option would be to emit TrySlowEnter and TrySlowExit methods
1638 // at startup-time.  These methods would accept arguments as
1639 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1640 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1641 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1642 // In practice, however, the # of lock sites is bounded and is usually small.
1643 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1644 // if the processor uses simple bimodal branch predictors keyed by EIP
1645 // Since the helper routines would be called from multiple synchronization
1646 // sites.
1647 //
1648 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1649 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1650 // to those specialized methods.  That'd give us a mostly platform-independent
1651 // implementation that the JITs could optimize and inline at their pleasure.
1652 // Done correctly, the only time we'd need to cross to native could would be
1653 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1654 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1655 // (b) explicit barriers or fence operations.
1656 //
1657 // TODO:
1658 //
1659 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1660 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1661 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1662 //    the lock operators would typically be faster than reifying Self.
1663 //
1664 // *  Ideally I'd define the primitives as:
1665 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1666 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1667 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1668 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1669 //    Furthermore the register assignments are overconstrained, possibly resulting in
1670 //    sub-optimal code near the synchronization site.
1671 //
1672 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1673 //    Alternately, use a better sp-proximity test.
1674 //
1675 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1676 //    Either one is sufficient to uniquely identify a thread.
1677 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1678 //
1679 // *  Intrinsify notify() and notifyAll() for the common cases where the
1680 //    object is locked by the calling thread but the waitlist is empty.
1681 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1682 //
1683 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1684 //    But beware of excessive branch density on AMD Opterons.
1685 //
1686 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1687 //    or failure of the fast-path.  If the fast-path fails then we pass
1688 //    control to the slow-path, typically in C.  In Fast_Lock and
1689 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1690 //    will emit a conditional branch immediately after the node.
1691 //    So we have branches to branches and lots of ICC.ZF games.
1692 //    Instead, it might be better to have C2 pass a "FailureLabel"
1693 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1694 //    will drop through the node.  ICC.ZF is undefined at exit.
1695 //    In the case of failure, the node will branch directly to the
1696 //    FailureLabel
1697 
1698 
1699 // obj: object to lock
1700 // box: on-stack box address (displaced header location) - KILLED
1701 // rax,: tmp -- KILLED
1702 // scr: tmp -- KILLED
1703 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1704                                Register scrReg, Register cx1Reg, Register cx2Reg,
1705                                BiasedLockingCounters* counters,
1706                                RTMLockingCounters* rtm_counters,
1707                                RTMLockingCounters* stack_rtm_counters,
1708                                Metadata* method_data,
1709                                bool use_rtm, bool profile_rtm) {
1710   // Ensure the register assignments are disjoint
1711   assert(tmpReg == rax, "");
1712 
1713   if (use_rtm) {
1714     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1715   } else {
1716     assert(cx1Reg == noreg, "");
1717     assert(cx2Reg == noreg, "");
1718     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1719   }
1720 
1721   if (counters != NULL) {
1722     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1723   }
1724   if (EmitSync & 1) {
1725       // set box->dhw = markOopDesc::unused_mark()
1726       // Force all sync thru slow-path: slow_enter() and slow_exit()
1727       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1728       cmpptr (rsp, (int32_t)NULL_WORD);
1729   } else {
1730     // Possible cases that we'll encounter in fast_lock
1731     // ------------------------------------------------
1732     // * Inflated
1733     //    -- unlocked
1734     //    -- Locked
1735     //       = by self
1736     //       = by other
1737     // * biased
1738     //    -- by Self
1739     //    -- by other
1740     // * neutral
1741     // * stack-locked
1742     //    -- by self
1743     //       = sp-proximity test hits
1744     //       = sp-proximity test generates false-negative
1745     //    -- by other
1746     //
1747 
1748     Label IsInflated, DONE_LABEL;
1749 
1750     // it's stack-locked, biased or neutral
1751     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1752     // order to reduce the number of conditional branches in the most common cases.
1753     // Beware -- there's a subtle invariant that fetch of the markword
1754     // at [FETCH], below, will never observe a biased encoding (*101b).
1755     // If this invariant is not held we risk exclusion (safety) failure.
1756     if (UseBiasedLocking && !UseOptoBiasInlining) {
1757       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1758     }
1759 
1760 #if INCLUDE_RTM_OPT
1761     if (UseRTMForStackLocks && use_rtm) {
1762       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1763                         stack_rtm_counters, method_data, profile_rtm,
1764                         DONE_LABEL, IsInflated);
1765     }
1766 #endif // INCLUDE_RTM_OPT
1767 
1768     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1769     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1770     jccb(Assembler::notZero, IsInflated);
1771 
1772     // Attempt stack-locking ...
1773     orptr (tmpReg, markOopDesc::unlocked_value);
1774     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1775     if (os::is_MP()) {
1776       lock();
1777     }
1778     cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1779     if (counters != NULL) {
1780       cond_inc32(Assembler::equal,
1781                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1782     }
1783     jcc(Assembler::equal, DONE_LABEL);           // Success
1784 
1785     // Recursive locking.
1786     // The object is stack-locked: markword contains stack pointer to BasicLock.
1787     // Locked by current thread if difference with current SP is less than one page.
1788     subptr(tmpReg, rsp);
1789     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1790     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1791     movptr(Address(boxReg, 0), tmpReg);
1792     if (counters != NULL) {
1793       cond_inc32(Assembler::equal,
1794                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1795     }
1796     jmp(DONE_LABEL);
1797 
1798     bind(IsInflated);
1799     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1800 
1801 #if INCLUDE_RTM_OPT
1802     // Use the same RTM locking code in 32- and 64-bit VM.
1803     if (use_rtm) {
1804       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1805                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1806     } else {
1807 #endif // INCLUDE_RTM_OPT
1808 
1809 #ifndef _LP64
1810     // The object is inflated.
1811 
1812     // boxReg refers to the on-stack BasicLock in the current frame.
1813     // We'd like to write:
1814     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1815     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1816     // additional latency as we have another ST in the store buffer that must drain.
1817 
1818     if (EmitSync & 8192) {
1819        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1820        get_thread (scrReg);
1821        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1822        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1823        if (os::is_MP()) {
1824          lock();
1825        }
1826        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1827     } else
1828     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1829        // register juggle because we need tmpReg for cmpxchgptr below
1830        movptr(scrReg, boxReg);
1831        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1832 
1833        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1834        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1835           // prefetchw [eax + Offset(_owner)-2]
1836           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1837        }
1838 
1839        if ((EmitSync & 64) == 0) {
1840          // Optimistic form: consider XORL tmpReg,tmpReg
1841          movptr(tmpReg, NULL_WORD);
1842        } else {
1843          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1844          // Test-And-CAS instead of CAS
1845          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1846          testptr(tmpReg, tmpReg);                   // Locked ?
1847          jccb  (Assembler::notZero, DONE_LABEL);
1848        }
1849 
1850        // Appears unlocked - try to swing _owner from null to non-null.
1851        // Ideally, I'd manifest "Self" with get_thread and then attempt
1852        // to CAS the register containing Self into m->Owner.
1853        // But we don't have enough registers, so instead we can either try to CAS
1854        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1855        // we later store "Self" into m->Owner.  Transiently storing a stack address
1856        // (rsp or the address of the box) into  m->owner is harmless.
1857        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1858        if (os::is_MP()) {
1859          lock();
1860        }
1861        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1862        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1863        // If we weren't able to swing _owner from NULL to the BasicLock
1864        // then take the slow path.
1865        jccb  (Assembler::notZero, DONE_LABEL);
1866        // update _owner from BasicLock to thread
1867        get_thread (scrReg);                    // beware: clobbers ICCs
1868        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1869        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1870 
1871        // If the CAS fails we can either retry or pass control to the slow-path.
1872        // We use the latter tactic.
1873        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1874        // If the CAS was successful ...
1875        //   Self has acquired the lock
1876        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1877        // Intentional fall-through into DONE_LABEL ...
1878     } else {
1879        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1880        movptr(boxReg, tmpReg);
1881 
1882        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1883        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1884           // prefetchw [eax + Offset(_owner)-2]
1885           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1886        }
1887 
1888        if ((EmitSync & 64) == 0) {
1889          // Optimistic form
1890          xorptr  (tmpReg, tmpReg);
1891        } else {
1892          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1893          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1894          testptr(tmpReg, tmpReg);                   // Locked ?
1895          jccb  (Assembler::notZero, DONE_LABEL);
1896        }
1897 
1898        // Appears unlocked - try to swing _owner from null to non-null.
1899        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1900        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1901        get_thread (scrReg);
1902        if (os::is_MP()) {
1903          lock();
1904        }
1905        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1906 
1907        // If the CAS fails we can either retry or pass control to the slow-path.
1908        // We use the latter tactic.
1909        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1910        // If the CAS was successful ...
1911        //   Self has acquired the lock
1912        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1913        // Intentional fall-through into DONE_LABEL ...
1914     }
1915 #else // _LP64
1916     // It's inflated
1917     movq(scrReg, tmpReg);
1918     xorq(tmpReg, tmpReg);
1919 
1920     if (os::is_MP()) {
1921       lock();
1922     }
1923     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1924     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1925     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1926     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1927     // Intentional fall-through into DONE_LABEL ...
1928     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1929 #endif // _LP64
1930 #if INCLUDE_RTM_OPT
1931     } // use_rtm()
1932 #endif
1933     // DONE_LABEL is a hot target - we'd really like to place it at the
1934     // start of cache line by padding with NOPs.
1935     // See the AMD and Intel software optimization manuals for the
1936     // most efficient "long" NOP encodings.
1937     // Unfortunately none of our alignment mechanisms suffice.
1938     bind(DONE_LABEL);
1939 
1940     // At DONE_LABEL the icc ZFlag is set as follows ...
1941     // Fast_Unlock uses the same protocol.
1942     // ZFlag == 1 -> Success
1943     // ZFlag == 0 -> Failure - force control through the slow-path
1944   }
1945 }
1946 
1947 // obj: object to unlock
1948 // box: box address (displaced header location), killed.  Must be EAX.
1949 // tmp: killed, cannot be obj nor box.
1950 //
1951 // Some commentary on balanced locking:
1952 //
1953 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1954 // Methods that don't have provably balanced locking are forced to run in the
1955 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1956 // The interpreter provides two properties:
1957 // I1:  At return-time the interpreter automatically and quietly unlocks any
1958 //      objects acquired the current activation (frame).  Recall that the
1959 //      interpreter maintains an on-stack list of locks currently held by
1960 //      a frame.
1961 // I2:  If a method attempts to unlock an object that is not held by the
1962 //      the frame the interpreter throws IMSX.
1963 //
1964 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1965 // B() doesn't have provably balanced locking so it runs in the interpreter.
1966 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1967 // is still locked by A().
1968 //
1969 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1970 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1971 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1972 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1973 // Arguably given that the spec legislates the JNI case as undefined our implementation
1974 // could reasonably *avoid* checking owner in Fast_Unlock().
1975 // In the interest of performance we elide m->Owner==Self check in unlock.
1976 // A perfectly viable alternative is to elide the owner check except when
1977 // Xcheck:jni is enabled.
1978 
1979 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1980   assert(boxReg == rax, "");
1981   assert_different_registers(objReg, boxReg, tmpReg);
1982 
1983   if (EmitSync & 4) {
1984     // Disable - inhibit all inlining.  Force control through the slow-path
1985     cmpptr (rsp, 0);
1986   } else {
1987     Label DONE_LABEL, Stacked, CheckSucc;
1988 
1989     // Critically, the biased locking test must have precedence over
1990     // and appear before the (box->dhw == 0) recursive stack-lock test.
1991     if (UseBiasedLocking && !UseOptoBiasInlining) {
1992        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1993     }
1994 
1995 #if INCLUDE_RTM_OPT
1996     if (UseRTMForStackLocks && use_rtm) {
1997       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1998       Label L_regular_unlock;
1999       movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
2000       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
2001       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
2002       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
2003       xend();                                       // otherwise end...
2004       jmp(DONE_LABEL);                              // ... and we're done
2005       bind(L_regular_unlock);
2006     }
2007 #endif
2008 
2009     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
2010     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2011     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
2012     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2013     jccb  (Assembler::zero, Stacked);
2014 
2015     // It's inflated.
2016 #if INCLUDE_RTM_OPT
2017     if (use_rtm) {
2018       Label L_regular_inflated_unlock;
2019       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2020       movptr(boxReg, Address(tmpReg, owner_offset));
2021       testptr(boxReg, boxReg);
2022       jccb(Assembler::notZero, L_regular_inflated_unlock);
2023       xend();
2024       jmpb(DONE_LABEL);
2025       bind(L_regular_inflated_unlock);
2026     }
2027 #endif
2028 
2029     // Despite our balanced locking property we still check that m->_owner == Self
2030     // as java routines or native JNI code called by this thread might
2031     // have released the lock.
2032     // Refer to the comments in synchronizer.cpp for how we might encode extra
2033     // state in _succ so we can avoid fetching EntryList|cxq.
2034     //
2035     // I'd like to add more cases in fast_lock() and fast_unlock() --
2036     // such as recursive enter and exit -- but we have to be wary of
2037     // I$ bloat, T$ effects and BP$ effects.
2038     //
2039     // If there's no contention try a 1-0 exit.  That is, exit without
2040     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2041     // we detect and recover from the race that the 1-0 exit admits.
2042     //
2043     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2044     // before it STs null into _owner, releasing the lock.  Updates
2045     // to data protected by the critical section must be visible before
2046     // we drop the lock (and thus before any other thread could acquire
2047     // the lock and observe the fields protected by the lock).
2048     // IA32's memory-model is SPO, so STs are ordered with respect to
2049     // each other and there's no need for an explicit barrier (fence).
2050     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2051 #ifndef _LP64
2052     get_thread (boxReg);
2053     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2054       // prefetchw [ebx + Offset(_owner)-2]
2055       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2056     }
2057 
2058     // Note that we could employ various encoding schemes to reduce
2059     // the number of loads below (currently 4) to just 2 or 3.
2060     // Refer to the comments in synchronizer.cpp.
2061     // In practice the chain of fetches doesn't seem to impact performance, however.
2062     xorptr(boxReg, boxReg);
2063     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2064        // Attempt to reduce branch density - AMD's branch predictor.
2065        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2066        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2067        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2068        jccb  (Assembler::notZero, DONE_LABEL);
2069        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2070        jmpb  (DONE_LABEL);
2071     } else {
2072        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2073        jccb  (Assembler::notZero, DONE_LABEL);
2074        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2075        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2076        jccb  (Assembler::notZero, CheckSucc);
2077        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2078        jmpb  (DONE_LABEL);
2079     }
2080 
2081     // The Following code fragment (EmitSync & 65536) improves the performance of
2082     // contended applications and contended synchronization microbenchmarks.
2083     // Unfortunately the emission of the code - even though not executed - causes regressions
2084     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2085     // with an equal number of never-executed NOPs results in the same regression.
2086     // We leave it off by default.
2087 
2088     if ((EmitSync & 65536) != 0) {
2089        Label LSuccess, LGoSlowPath ;
2090 
2091        bind  (CheckSucc);
2092 
2093        // Optional pre-test ... it's safe to elide this
2094        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2095        jccb(Assembler::zero, LGoSlowPath);
2096 
2097        // We have a classic Dekker-style idiom:
2098        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2099        // There are a number of ways to implement the barrier:
2100        // (1) lock:andl &m->_owner, 0
2101        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2102        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2103        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2104        // (2) If supported, an explicit MFENCE is appealing.
2105        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2106        //     particularly if the write-buffer is full as might be the case if
2107        //     if stores closely precede the fence or fence-equivalent instruction.
2108        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2109        //     as the situation has changed with Nehalem and Shanghai.
2110        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2111        //     The $lines underlying the top-of-stack should be in M-state.
2112        //     The locked add instruction is serializing, of course.
2113        // (4) Use xchg, which is serializing
2114        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2115        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2116        //     The integer condition codes will tell us if succ was 0.
2117        //     Since _succ and _owner should reside in the same $line and
2118        //     we just stored into _owner, it's likely that the $line
2119        //     remains in M-state for the lock:orl.
2120        //
2121        // We currently use (3), although it's likely that switching to (2)
2122        // is correct for the future.
2123 
2124        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2125        if (os::is_MP()) {
2126          lock(); addptr(Address(rsp, 0), 0);
2127        }
2128        // Ratify _succ remains non-null
2129        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2130        jccb  (Assembler::notZero, LSuccess);
2131 
2132        xorptr(boxReg, boxReg);                  // box is really EAX
2133        if (os::is_MP()) { lock(); }
2134        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2135        // There's no successor so we tried to regrab the lock with the
2136        // placeholder value. If that didn't work, then another thread
2137        // grabbed the lock so we're done (and exit was a success).
2138        jccb  (Assembler::notEqual, LSuccess);
2139        // Since we're low on registers we installed rsp as a placeholding in _owner.
2140        // Now install Self over rsp.  This is safe as we're transitioning from
2141        // non-null to non=null
2142        get_thread (boxReg);
2143        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2144        // Intentional fall-through into LGoSlowPath ...
2145 
2146        bind  (LGoSlowPath);
2147        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2148        jmpb  (DONE_LABEL);
2149 
2150        bind  (LSuccess);
2151        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2152        jmpb  (DONE_LABEL);
2153     }
2154 
2155     bind (Stacked);
2156     // It's not inflated and it's not recursively stack-locked and it's not biased.
2157     // It must be stack-locked.
2158     // Try to reset the header to displaced header.
2159     // The "box" value on the stack is stable, so we can reload
2160     // and be assured we observe the same value as above.
2161     movptr(tmpReg, Address(boxReg, 0));
2162     if (os::is_MP()) {
2163       lock();
2164     }
2165     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2166     // Intention fall-thru into DONE_LABEL
2167 
2168     // DONE_LABEL is a hot target - we'd really like to place it at the
2169     // start of cache line by padding with NOPs.
2170     // See the AMD and Intel software optimization manuals for the
2171     // most efficient "long" NOP encodings.
2172     // Unfortunately none of our alignment mechanisms suffice.
2173     if ((EmitSync & 65536) == 0) {
2174        bind (CheckSucc);
2175     }
2176 #else // _LP64
2177     // It's inflated
2178     if (EmitSync & 1024) {
2179       // Emit code to check that _owner == Self
2180       // We could fold the _owner test into subsequent code more efficiently
2181       // than using a stand-alone check, but since _owner checking is off by
2182       // default we don't bother. We also might consider predicating the
2183       // _owner==Self check on Xcheck:jni or running on a debug build.
2184       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2185       xorptr(boxReg, r15_thread);
2186     } else {
2187       xorptr(boxReg, boxReg);
2188     }
2189     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2190     jccb  (Assembler::notZero, DONE_LABEL);
2191     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2192     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2193     jccb  (Assembler::notZero, CheckSucc);
2194     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2195     jmpb  (DONE_LABEL);
2196 
2197     if ((EmitSync & 65536) == 0) {
2198       // Try to avoid passing control into the slow_path ...
2199       Label LSuccess, LGoSlowPath ;
2200       bind  (CheckSucc);
2201 
2202       // The following optional optimization can be elided if necessary
2203       // Effectively: if (succ == null) goto SlowPath
2204       // The code reduces the window for a race, however,
2205       // and thus benefits performance.
2206       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2207       jccb  (Assembler::zero, LGoSlowPath);
2208 
2209       xorptr(boxReg, boxReg);
2210       if ((EmitSync & 16) && os::is_MP()) {
2211         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2212       } else {
2213         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2214         if (os::is_MP()) {
2215           // Memory barrier/fence
2216           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2217           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2218           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2219           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2220           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2221           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2222           lock(); addl(Address(rsp, 0), 0);
2223         }
2224       }
2225       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2226       jccb  (Assembler::notZero, LSuccess);
2227 
2228       // Rare inopportune interleaving - race.
2229       // The successor vanished in the small window above.
2230       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2231       // We need to ensure progress and succession.
2232       // Try to reacquire the lock.
2233       // If that fails then the new owner is responsible for succession and this
2234       // thread needs to take no further action and can exit via the fast path (success).
2235       // If the re-acquire succeeds then pass control into the slow path.
2236       // As implemented, this latter mode is horrible because we generated more
2237       // coherence traffic on the lock *and* artifically extended the critical section
2238       // length while by virtue of passing control into the slow path.
2239 
2240       // box is really RAX -- the following CMPXCHG depends on that binding
2241       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2242       if (os::is_MP()) { lock(); }
2243       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2244       // There's no successor so we tried to regrab the lock.
2245       // If that didn't work, then another thread grabbed the
2246       // lock so we're done (and exit was a success).
2247       jccb  (Assembler::notEqual, LSuccess);
2248       // Intentional fall-through into slow-path
2249 
2250       bind  (LGoSlowPath);
2251       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2252       jmpb  (DONE_LABEL);
2253 
2254       bind  (LSuccess);
2255       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2256       jmpb  (DONE_LABEL);
2257     }
2258 
2259     bind  (Stacked);
2260     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2261     if (os::is_MP()) { lock(); }
2262     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2263 
2264     if (EmitSync & 65536) {
2265        bind (CheckSucc);
2266     }
2267 #endif
2268     bind(DONE_LABEL);
2269   }
2270 }
2271 #endif // COMPILER2
2272 
2273 void MacroAssembler::c2bool(Register x) {
2274   // implements x == 0 ? 0 : 1
2275   // note: must only look at least-significant byte of x
2276   //       since C-style booleans are stored in one byte
2277   //       only! (was bug)
2278   andl(x, 0xFF);
2279   setb(Assembler::notZero, x);
2280 }
2281 
2282 // Wouldn't need if AddressLiteral version had new name
2283 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2284   Assembler::call(L, rtype);
2285 }
2286 
2287 void MacroAssembler::call(Register entry) {
2288   Assembler::call(entry);
2289 }
2290 
2291 void MacroAssembler::call(AddressLiteral entry) {
2292   if (reachable(entry)) {
2293     Assembler::call_literal(entry.target(), entry.rspec());
2294   } else {
2295     lea(rscratch1, entry);
2296     Assembler::call(rscratch1);
2297   }
2298 }
2299 
2300 void MacroAssembler::ic_call(address entry, jint method_index) {
2301   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2302   movptr(rax, (intptr_t)Universe::non_oop_word());
2303   call(AddressLiteral(entry, rh));
2304 }
2305 
2306 // Implementation of call_VM versions
2307 
2308 void MacroAssembler::call_VM(Register oop_result,
2309                              address entry_point,
2310                              bool check_exceptions) {
2311   Label C, E;
2312   call(C, relocInfo::none);
2313   jmp(E);
2314 
2315   bind(C);
2316   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2317   ret(0);
2318 
2319   bind(E);
2320 }
2321 
2322 void MacroAssembler::call_VM(Register oop_result,
2323                              address entry_point,
2324                              Register arg_1,
2325                              bool check_exceptions) {
2326   Label C, E;
2327   call(C, relocInfo::none);
2328   jmp(E);
2329 
2330   bind(C);
2331   pass_arg1(this, arg_1);
2332   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2333   ret(0);
2334 
2335   bind(E);
2336 }
2337 
2338 void MacroAssembler::call_VM(Register oop_result,
2339                              address entry_point,
2340                              Register arg_1,
2341                              Register arg_2,
2342                              bool check_exceptions) {
2343   Label C, E;
2344   call(C, relocInfo::none);
2345   jmp(E);
2346 
2347   bind(C);
2348 
2349   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2350 
2351   pass_arg2(this, arg_2);
2352   pass_arg1(this, arg_1);
2353   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2354   ret(0);
2355 
2356   bind(E);
2357 }
2358 
2359 void MacroAssembler::call_VM(Register oop_result,
2360                              address entry_point,
2361                              Register arg_1,
2362                              Register arg_2,
2363                              Register arg_3,
2364                              bool check_exceptions) {
2365   Label C, E;
2366   call(C, relocInfo::none);
2367   jmp(E);
2368 
2369   bind(C);
2370 
2371   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2372   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2373   pass_arg3(this, arg_3);
2374 
2375   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2376   pass_arg2(this, arg_2);
2377 
2378   pass_arg1(this, arg_1);
2379   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2380   ret(0);
2381 
2382   bind(E);
2383 }
2384 
2385 void MacroAssembler::call_VM(Register oop_result,
2386                              Register last_java_sp,
2387                              address entry_point,
2388                              int number_of_arguments,
2389                              bool check_exceptions) {
2390   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2391   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2392 }
2393 
2394 void MacroAssembler::call_VM(Register oop_result,
2395                              Register last_java_sp,
2396                              address entry_point,
2397                              Register arg_1,
2398                              bool check_exceptions) {
2399   pass_arg1(this, arg_1);
2400   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2401 }
2402 
2403 void MacroAssembler::call_VM(Register oop_result,
2404                              Register last_java_sp,
2405                              address entry_point,
2406                              Register arg_1,
2407                              Register arg_2,
2408                              bool check_exceptions) {
2409 
2410   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2411   pass_arg2(this, arg_2);
2412   pass_arg1(this, arg_1);
2413   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2414 }
2415 
2416 void MacroAssembler::call_VM(Register oop_result,
2417                              Register last_java_sp,
2418                              address entry_point,
2419                              Register arg_1,
2420                              Register arg_2,
2421                              Register arg_3,
2422                              bool check_exceptions) {
2423   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2424   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2425   pass_arg3(this, arg_3);
2426   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2427   pass_arg2(this, arg_2);
2428   pass_arg1(this, arg_1);
2429   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2430 }
2431 
2432 void MacroAssembler::super_call_VM(Register oop_result,
2433                                    Register last_java_sp,
2434                                    address entry_point,
2435                                    int number_of_arguments,
2436                                    bool check_exceptions) {
2437   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2438   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2439 }
2440 
2441 void MacroAssembler::super_call_VM(Register oop_result,
2442                                    Register last_java_sp,
2443                                    address entry_point,
2444                                    Register arg_1,
2445                                    bool check_exceptions) {
2446   pass_arg1(this, arg_1);
2447   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2448 }
2449 
2450 void MacroAssembler::super_call_VM(Register oop_result,
2451                                    Register last_java_sp,
2452                                    address entry_point,
2453                                    Register arg_1,
2454                                    Register arg_2,
2455                                    bool check_exceptions) {
2456 
2457   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2458   pass_arg2(this, arg_2);
2459   pass_arg1(this, arg_1);
2460   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2461 }
2462 
2463 void MacroAssembler::super_call_VM(Register oop_result,
2464                                    Register last_java_sp,
2465                                    address entry_point,
2466                                    Register arg_1,
2467                                    Register arg_2,
2468                                    Register arg_3,
2469                                    bool check_exceptions) {
2470   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2471   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2472   pass_arg3(this, arg_3);
2473   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2474   pass_arg2(this, arg_2);
2475   pass_arg1(this, arg_1);
2476   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2477 }
2478 
2479 void MacroAssembler::call_VM_base(Register oop_result,
2480                                   Register java_thread,
2481                                   Register last_java_sp,
2482                                   address  entry_point,
2483                                   int      number_of_arguments,
2484                                   bool     check_exceptions) {
2485   // determine java_thread register
2486   if (!java_thread->is_valid()) {
2487 #ifdef _LP64
2488     java_thread = r15_thread;
2489 #else
2490     java_thread = rdi;
2491     get_thread(java_thread);
2492 #endif // LP64
2493   }
2494   // determine last_java_sp register
2495   if (!last_java_sp->is_valid()) {
2496     last_java_sp = rsp;
2497   }
2498   // debugging support
2499   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2500   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2501 #ifdef ASSERT
2502   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2503   // r12 is the heapbase.
2504   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2505 #endif // ASSERT
2506 
2507   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2508   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2509 
2510   // push java thread (becomes first argument of C function)
2511 
2512   NOT_LP64(push(java_thread); number_of_arguments++);
2513   LP64_ONLY(mov(c_rarg0, r15_thread));
2514 
2515   // set last Java frame before call
2516   assert(last_java_sp != rbp, "can't use ebp/rbp");
2517 
2518   // Only interpreter should have to set fp
2519   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2520 
2521   // do the call, remove parameters
2522   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2523 
2524   // restore the thread (cannot use the pushed argument since arguments
2525   // may be overwritten by C code generated by an optimizing compiler);
2526   // however can use the register value directly if it is callee saved.
2527   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2528     // rdi & rsi (also r15) are callee saved -> nothing to do
2529 #ifdef ASSERT
2530     guarantee(java_thread != rax, "change this code");
2531     push(rax);
2532     { Label L;
2533       get_thread(rax);
2534       cmpptr(java_thread, rax);
2535       jcc(Assembler::equal, L);
2536       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2537       bind(L);
2538     }
2539     pop(rax);
2540 #endif
2541   } else {
2542     get_thread(java_thread);
2543   }
2544   // reset last Java frame
2545   // Only interpreter should have to clear fp
2546   reset_last_Java_frame(java_thread, true);
2547 
2548    // C++ interp handles this in the interpreter
2549   check_and_handle_popframe(java_thread);
2550   check_and_handle_earlyret(java_thread);
2551 
2552   if (check_exceptions) {
2553     // check for pending exceptions (java_thread is set upon return)
2554     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2555 #ifndef _LP64
2556     jump_cc(Assembler::notEqual,
2557             RuntimeAddress(StubRoutines::forward_exception_entry()));
2558 #else
2559     // This used to conditionally jump to forward_exception however it is
2560     // possible if we relocate that the branch will not reach. So we must jump
2561     // around so we can always reach
2562 
2563     Label ok;
2564     jcc(Assembler::equal, ok);
2565     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2566     bind(ok);
2567 #endif // LP64
2568   }
2569 
2570   // get oop result if there is one and reset the value in the thread
2571   if (oop_result->is_valid()) {
2572     get_vm_result(oop_result, java_thread);
2573   }
2574 }
2575 
2576 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2577 
2578   // Calculate the value for last_Java_sp
2579   // somewhat subtle. call_VM does an intermediate call
2580   // which places a return address on the stack just under the
2581   // stack pointer as the user finsihed with it. This allows
2582   // use to retrieve last_Java_pc from last_Java_sp[-1].
2583   // On 32bit we then have to push additional args on the stack to accomplish
2584   // the actual requested call. On 64bit call_VM only can use register args
2585   // so the only extra space is the return address that call_VM created.
2586   // This hopefully explains the calculations here.
2587 
2588 #ifdef _LP64
2589   // We've pushed one address, correct last_Java_sp
2590   lea(rax, Address(rsp, wordSize));
2591 #else
2592   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2593 #endif // LP64
2594 
2595   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2596 
2597 }
2598 
2599 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2600 void MacroAssembler::call_VM_leaf0(address entry_point) {
2601   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2602 }
2603 
2604 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2605   call_VM_leaf_base(entry_point, number_of_arguments);
2606 }
2607 
2608 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2609   pass_arg0(this, arg_0);
2610   call_VM_leaf(entry_point, 1);
2611 }
2612 
2613 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2614 
2615   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2616   pass_arg1(this, arg_1);
2617   pass_arg0(this, arg_0);
2618   call_VM_leaf(entry_point, 2);
2619 }
2620 
2621 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2622   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2623   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2624   pass_arg2(this, arg_2);
2625   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2626   pass_arg1(this, arg_1);
2627   pass_arg0(this, arg_0);
2628   call_VM_leaf(entry_point, 3);
2629 }
2630 
2631 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2632   pass_arg0(this, arg_0);
2633   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2634 }
2635 
2636 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2637 
2638   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2639   pass_arg1(this, arg_1);
2640   pass_arg0(this, arg_0);
2641   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2642 }
2643 
2644 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2645   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2646   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2647   pass_arg2(this, arg_2);
2648   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2649   pass_arg1(this, arg_1);
2650   pass_arg0(this, arg_0);
2651   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2652 }
2653 
2654 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2655   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2656   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2657   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2658   pass_arg3(this, arg_3);
2659   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2660   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2661   pass_arg2(this, arg_2);
2662   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2663   pass_arg1(this, arg_1);
2664   pass_arg0(this, arg_0);
2665   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2666 }
2667 
2668 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2669   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2670   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2671   verify_oop(oop_result, "broken oop in call_VM_base");
2672 }
2673 
2674 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2675   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2676   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2677 }
2678 
2679 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2680 }
2681 
2682 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2683 }
2684 
2685 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2686   if (reachable(src1)) {
2687     cmpl(as_Address(src1), imm);
2688   } else {
2689     lea(rscratch1, src1);
2690     cmpl(Address(rscratch1, 0), imm);
2691   }
2692 }
2693 
2694 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2695   assert(!src2.is_lval(), "use cmpptr");
2696   if (reachable(src2)) {
2697     cmpl(src1, as_Address(src2));
2698   } else {
2699     lea(rscratch1, src2);
2700     cmpl(src1, Address(rscratch1, 0));
2701   }
2702 }
2703 
2704 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2705   Assembler::cmpl(src1, imm);
2706 }
2707 
2708 void MacroAssembler::cmp32(Register src1, Address src2) {
2709   Assembler::cmpl(src1, src2);
2710 }
2711 
2712 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2713   ucomisd(opr1, opr2);
2714 
2715   Label L;
2716   if (unordered_is_less) {
2717     movl(dst, -1);
2718     jcc(Assembler::parity, L);
2719     jcc(Assembler::below , L);
2720     movl(dst, 0);
2721     jcc(Assembler::equal , L);
2722     increment(dst);
2723   } else { // unordered is greater
2724     movl(dst, 1);
2725     jcc(Assembler::parity, L);
2726     jcc(Assembler::above , L);
2727     movl(dst, 0);
2728     jcc(Assembler::equal , L);
2729     decrementl(dst);
2730   }
2731   bind(L);
2732 }
2733 
2734 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2735   ucomiss(opr1, opr2);
2736 
2737   Label L;
2738   if (unordered_is_less) {
2739     movl(dst, -1);
2740     jcc(Assembler::parity, L);
2741     jcc(Assembler::below , L);
2742     movl(dst, 0);
2743     jcc(Assembler::equal , L);
2744     increment(dst);
2745   } else { // unordered is greater
2746     movl(dst, 1);
2747     jcc(Assembler::parity, L);
2748     jcc(Assembler::above , L);
2749     movl(dst, 0);
2750     jcc(Assembler::equal , L);
2751     decrementl(dst);
2752   }
2753   bind(L);
2754 }
2755 
2756 
2757 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2758   if (reachable(src1)) {
2759     cmpb(as_Address(src1), imm);
2760   } else {
2761     lea(rscratch1, src1);
2762     cmpb(Address(rscratch1, 0), imm);
2763   }
2764 }
2765 
2766 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2767 #ifdef _LP64
2768   if (src2.is_lval()) {
2769     movptr(rscratch1, src2);
2770     Assembler::cmpq(src1, rscratch1);
2771   } else if (reachable(src2)) {
2772     cmpq(src1, as_Address(src2));
2773   } else {
2774     lea(rscratch1, src2);
2775     Assembler::cmpq(src1, Address(rscratch1, 0));
2776   }
2777 #else
2778   if (src2.is_lval()) {
2779     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2780   } else {
2781     cmpl(src1, as_Address(src2));
2782   }
2783 #endif // _LP64
2784 }
2785 
2786 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2787   assert(src2.is_lval(), "not a mem-mem compare");
2788 #ifdef _LP64
2789   // moves src2's literal address
2790   movptr(rscratch1, src2);
2791   Assembler::cmpq(src1, rscratch1);
2792 #else
2793   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2794 #endif // _LP64
2795 }
2796 
2797 void MacroAssembler::cmpoop(Register src1, Register src2) {
2798   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
2799   bs->obj_equals(this, src1, src2);
2800 }
2801 
2802 void MacroAssembler::cmpoop(Register src1, Address src2) {
2803   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
2804   bs->obj_equals(this, src1, src2);
2805 }
2806 
2807 #ifdef _LP64
2808 void MacroAssembler::cmpoop(Register src1, jobject src2) {
2809   movoop(rscratch1, src2);
2810   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
2811   bs->obj_equals(this, src1, rscratch1);
2812 }
2813 #endif
2814 
2815 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2816   if (reachable(adr)) {
2817     if (os::is_MP())
2818       lock();
2819     cmpxchgptr(reg, as_Address(adr));
2820   } else {
2821     lea(rscratch1, adr);
2822     if (os::is_MP())
2823       lock();
2824     cmpxchgptr(reg, Address(rscratch1, 0));
2825   }
2826 }
2827 
2828 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2829   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2830 }
2831 
2832 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2833   if (reachable(src)) {
2834     Assembler::comisd(dst, as_Address(src));
2835   } else {
2836     lea(rscratch1, src);
2837     Assembler::comisd(dst, Address(rscratch1, 0));
2838   }
2839 }
2840 
2841 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2842   if (reachable(src)) {
2843     Assembler::comiss(dst, as_Address(src));
2844   } else {
2845     lea(rscratch1, src);
2846     Assembler::comiss(dst, Address(rscratch1, 0));
2847   }
2848 }
2849 
2850 
2851 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2852   Condition negated_cond = negate_condition(cond);
2853   Label L;
2854   jcc(negated_cond, L);
2855   pushf(); // Preserve flags
2856   atomic_incl(counter_addr);
2857   popf();
2858   bind(L);
2859 }
2860 
2861 int MacroAssembler::corrected_idivl(Register reg) {
2862   // Full implementation of Java idiv and irem; checks for
2863   // special case as described in JVM spec., p.243 & p.271.
2864   // The function returns the (pc) offset of the idivl
2865   // instruction - may be needed for implicit exceptions.
2866   //
2867   //         normal case                           special case
2868   //
2869   // input : rax,: dividend                         min_int
2870   //         reg: divisor   (may not be rax,/rdx)   -1
2871   //
2872   // output: rax,: quotient  (= rax, idiv reg)       min_int
2873   //         rdx: remainder (= rax, irem reg)       0
2874   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2875   const int min_int = 0x80000000;
2876   Label normal_case, special_case;
2877 
2878   // check for special case
2879   cmpl(rax, min_int);
2880   jcc(Assembler::notEqual, normal_case);
2881   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2882   cmpl(reg, -1);
2883   jcc(Assembler::equal, special_case);
2884 
2885   // handle normal case
2886   bind(normal_case);
2887   cdql();
2888   int idivl_offset = offset();
2889   idivl(reg);
2890 
2891   // normal and special case exit
2892   bind(special_case);
2893 
2894   return idivl_offset;
2895 }
2896 
2897 
2898 
2899 void MacroAssembler::decrementl(Register reg, int value) {
2900   if (value == min_jint) {subl(reg, value) ; return; }
2901   if (value <  0) { incrementl(reg, -value); return; }
2902   if (value == 0) {                        ; return; }
2903   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2904   /* else */      { subl(reg, value)       ; return; }
2905 }
2906 
2907 void MacroAssembler::decrementl(Address dst, int value) {
2908   if (value == min_jint) {subl(dst, value) ; return; }
2909   if (value <  0) { incrementl(dst, -value); return; }
2910   if (value == 0) {                        ; return; }
2911   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2912   /* else */      { subl(dst, value)       ; return; }
2913 }
2914 
2915 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2916   assert (shift_value > 0, "illegal shift value");
2917   Label _is_positive;
2918   testl (reg, reg);
2919   jcc (Assembler::positive, _is_positive);
2920   int offset = (1 << shift_value) - 1 ;
2921 
2922   if (offset == 1) {
2923     incrementl(reg);
2924   } else {
2925     addl(reg, offset);
2926   }
2927 
2928   bind (_is_positive);
2929   sarl(reg, shift_value);
2930 }
2931 
2932 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2933   if (reachable(src)) {
2934     Assembler::divsd(dst, as_Address(src));
2935   } else {
2936     lea(rscratch1, src);
2937     Assembler::divsd(dst, Address(rscratch1, 0));
2938   }
2939 }
2940 
2941 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2942   if (reachable(src)) {
2943     Assembler::divss(dst, as_Address(src));
2944   } else {
2945     lea(rscratch1, src);
2946     Assembler::divss(dst, Address(rscratch1, 0));
2947   }
2948 }
2949 
2950 // !defined(COMPILER2) is because of stupid core builds
2951 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2952 void MacroAssembler::empty_FPU_stack() {
2953   if (VM_Version::supports_mmx()) {
2954     emms();
2955   } else {
2956     for (int i = 8; i-- > 0; ) ffree(i);
2957   }
2958 }
2959 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2960 
2961 
2962 void MacroAssembler::enter() {
2963   push(rbp);
2964   mov(rbp, rsp);
2965 }
2966 
2967 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2968 void MacroAssembler::fat_nop() {
2969   if (UseAddressNop) {
2970     addr_nop_5();
2971   } else {
2972     emit_int8(0x26); // es:
2973     emit_int8(0x2e); // cs:
2974     emit_int8(0x64); // fs:
2975     emit_int8(0x65); // gs:
2976     emit_int8((unsigned char)0x90);
2977   }
2978 }
2979 
2980 void MacroAssembler::fcmp(Register tmp) {
2981   fcmp(tmp, 1, true, true);
2982 }
2983 
2984 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2985   assert(!pop_right || pop_left, "usage error");
2986   if (VM_Version::supports_cmov()) {
2987     assert(tmp == noreg, "unneeded temp");
2988     if (pop_left) {
2989       fucomip(index);
2990     } else {
2991       fucomi(index);
2992     }
2993     if (pop_right) {
2994       fpop();
2995     }
2996   } else {
2997     assert(tmp != noreg, "need temp");
2998     if (pop_left) {
2999       if (pop_right) {
3000         fcompp();
3001       } else {
3002         fcomp(index);
3003       }
3004     } else {
3005       fcom(index);
3006     }
3007     // convert FPU condition into eflags condition via rax,
3008     save_rax(tmp);
3009     fwait(); fnstsw_ax();
3010     sahf();
3011     restore_rax(tmp);
3012   }
3013   // condition codes set as follows:
3014   //
3015   // CF (corresponds to C0) if x < y
3016   // PF (corresponds to C2) if unordered
3017   // ZF (corresponds to C3) if x = y
3018 }
3019 
3020 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3021   fcmp2int(dst, unordered_is_less, 1, true, true);
3022 }
3023 
3024 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3025   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3026   Label L;
3027   if (unordered_is_less) {
3028     movl(dst, -1);
3029     jcc(Assembler::parity, L);
3030     jcc(Assembler::below , L);
3031     movl(dst, 0);
3032     jcc(Assembler::equal , L);
3033     increment(dst);
3034   } else { // unordered is greater
3035     movl(dst, 1);
3036     jcc(Assembler::parity, L);
3037     jcc(Assembler::above , L);
3038     movl(dst, 0);
3039     jcc(Assembler::equal , L);
3040     decrementl(dst);
3041   }
3042   bind(L);
3043 }
3044 
3045 void MacroAssembler::fld_d(AddressLiteral src) {
3046   fld_d(as_Address(src));
3047 }
3048 
3049 void MacroAssembler::fld_s(AddressLiteral src) {
3050   fld_s(as_Address(src));
3051 }
3052 
3053 void MacroAssembler::fld_x(AddressLiteral src) {
3054   Assembler::fld_x(as_Address(src));
3055 }
3056 
3057 void MacroAssembler::fldcw(AddressLiteral src) {
3058   Assembler::fldcw(as_Address(src));
3059 }
3060 
3061 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3062   if (reachable(src)) {
3063     Assembler::mulpd(dst, as_Address(src));
3064   } else {
3065     lea(rscratch1, src);
3066     Assembler::mulpd(dst, Address(rscratch1, 0));
3067   }
3068 }
3069 
3070 void MacroAssembler::increase_precision() {
3071   subptr(rsp, BytesPerWord);
3072   fnstcw(Address(rsp, 0));
3073   movl(rax, Address(rsp, 0));
3074   orl(rax, 0x300);
3075   push(rax);
3076   fldcw(Address(rsp, 0));
3077   pop(rax);
3078 }
3079 
3080 void MacroAssembler::restore_precision() {
3081   fldcw(Address(rsp, 0));
3082   addptr(rsp, BytesPerWord);
3083 }
3084 
3085 void MacroAssembler::fpop() {
3086   ffree();
3087   fincstp();
3088 }
3089 
3090 void MacroAssembler::load_float(Address src) {
3091   if (UseSSE >= 1) {
3092     movflt(xmm0, src);
3093   } else {
3094     LP64_ONLY(ShouldNotReachHere());
3095     NOT_LP64(fld_s(src));
3096   }
3097 }
3098 
3099 void MacroAssembler::store_float(Address dst) {
3100   if (UseSSE >= 1) {
3101     movflt(dst, xmm0);
3102   } else {
3103     LP64_ONLY(ShouldNotReachHere());
3104     NOT_LP64(fstp_s(dst));
3105   }
3106 }
3107 
3108 void MacroAssembler::load_double(Address src) {
3109   if (UseSSE >= 2) {
3110     movdbl(xmm0, src);
3111   } else {
3112     LP64_ONLY(ShouldNotReachHere());
3113     NOT_LP64(fld_d(src));
3114   }
3115 }
3116 
3117 void MacroAssembler::store_double(Address dst) {
3118   if (UseSSE >= 2) {
3119     movdbl(dst, xmm0);
3120   } else {
3121     LP64_ONLY(ShouldNotReachHere());
3122     NOT_LP64(fstp_d(dst));
3123   }
3124 }
3125 
3126 void MacroAssembler::fremr(Register tmp) {
3127   save_rax(tmp);
3128   { Label L;
3129     bind(L);
3130     fprem();
3131     fwait(); fnstsw_ax();
3132 #ifdef _LP64
3133     testl(rax, 0x400);
3134     jcc(Assembler::notEqual, L);
3135 #else
3136     sahf();
3137     jcc(Assembler::parity, L);
3138 #endif // _LP64
3139   }
3140   restore_rax(tmp);
3141   // Result is in ST0.
3142   // Note: fxch & fpop to get rid of ST1
3143   // (otherwise FPU stack could overflow eventually)
3144   fxch(1);
3145   fpop();
3146 }
3147 
3148 // dst = c = a * b + c
3149 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3150   Assembler::vfmadd231sd(c, a, b);
3151   if (dst != c) {
3152     movdbl(dst, c);
3153   }
3154 }
3155 
3156 // dst = c = a * b + c
3157 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3158   Assembler::vfmadd231ss(c, a, b);
3159   if (dst != c) {
3160     movflt(dst, c);
3161   }
3162 }
3163 
3164 // dst = c = a * b + c
3165 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3166   Assembler::vfmadd231pd(c, a, b, vector_len);
3167   if (dst != c) {
3168     vmovdqu(dst, c);
3169   }
3170 }
3171 
3172 // dst = c = a * b + c
3173 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3174   Assembler::vfmadd231ps(c, a, b, vector_len);
3175   if (dst != c) {
3176     vmovdqu(dst, c);
3177   }
3178 }
3179 
3180 // dst = c = a * b + c
3181 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3182   Assembler::vfmadd231pd(c, a, b, vector_len);
3183   if (dst != c) {
3184     vmovdqu(dst, c);
3185   }
3186 }
3187 
3188 // dst = c = a * b + c
3189 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3190   Assembler::vfmadd231ps(c, a, b, vector_len);
3191   if (dst != c) {
3192     vmovdqu(dst, c);
3193   }
3194 }
3195 
3196 void MacroAssembler::incrementl(AddressLiteral dst) {
3197   if (reachable(dst)) {
3198     incrementl(as_Address(dst));
3199   } else {
3200     lea(rscratch1, dst);
3201     incrementl(Address(rscratch1, 0));
3202   }
3203 }
3204 
3205 void MacroAssembler::incrementl(ArrayAddress dst) {
3206   incrementl(as_Address(dst));
3207 }
3208 
3209 void MacroAssembler::incrementl(Register reg, int value) {
3210   if (value == min_jint) {addl(reg, value) ; return; }
3211   if (value <  0) { decrementl(reg, -value); return; }
3212   if (value == 0) {                        ; return; }
3213   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3214   /* else */      { addl(reg, value)       ; return; }
3215 }
3216 
3217 void MacroAssembler::incrementl(Address dst, int value) {
3218   if (value == min_jint) {addl(dst, value) ; return; }
3219   if (value <  0) { decrementl(dst, -value); return; }
3220   if (value == 0) {                        ; return; }
3221   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3222   /* else */      { addl(dst, value)       ; return; }
3223 }
3224 
3225 void MacroAssembler::jump(AddressLiteral dst) {
3226   if (reachable(dst)) {
3227     jmp_literal(dst.target(), dst.rspec());
3228   } else {
3229     lea(rscratch1, dst);
3230     jmp(rscratch1);
3231   }
3232 }
3233 
3234 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3235   if (reachable(dst)) {
3236     InstructionMark im(this);
3237     relocate(dst.reloc());
3238     const int short_size = 2;
3239     const int long_size = 6;
3240     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3241     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3242       // 0111 tttn #8-bit disp
3243       emit_int8(0x70 | cc);
3244       emit_int8((offs - short_size) & 0xFF);
3245     } else {
3246       // 0000 1111 1000 tttn #32-bit disp
3247       emit_int8(0x0F);
3248       emit_int8((unsigned char)(0x80 | cc));
3249       emit_int32(offs - long_size);
3250     }
3251   } else {
3252 #ifdef ASSERT
3253     warning("reversing conditional branch");
3254 #endif /* ASSERT */
3255     Label skip;
3256     jccb(reverse[cc], skip);
3257     lea(rscratch1, dst);
3258     Assembler::jmp(rscratch1);
3259     bind(skip);
3260   }
3261 }
3262 
3263 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3264   if (reachable(src)) {
3265     Assembler::ldmxcsr(as_Address(src));
3266   } else {
3267     lea(rscratch1, src);
3268     Assembler::ldmxcsr(Address(rscratch1, 0));
3269   }
3270 }
3271 
3272 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3273   int off;
3274   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3275     off = offset();
3276     movsbl(dst, src); // movsxb
3277   } else {
3278     off = load_unsigned_byte(dst, src);
3279     shll(dst, 24);
3280     sarl(dst, 24);
3281   }
3282   return off;
3283 }
3284 
3285 // Note: load_signed_short used to be called load_signed_word.
3286 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3287 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3288 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3289 int MacroAssembler::load_signed_short(Register dst, Address src) {
3290   int off;
3291   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3292     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3293     // version but this is what 64bit has always done. This seems to imply
3294     // that users are only using 32bits worth.
3295     off = offset();
3296     movswl(dst, src); // movsxw
3297   } else {
3298     off = load_unsigned_short(dst, src);
3299     shll(dst, 16);
3300     sarl(dst, 16);
3301   }
3302   return off;
3303 }
3304 
3305 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3306   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3307   // and "3.9 Partial Register Penalties", p. 22).
3308   int off;
3309   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3310     off = offset();
3311     movzbl(dst, src); // movzxb
3312   } else {
3313     xorl(dst, dst);
3314     off = offset();
3315     movb(dst, src);
3316   }
3317   return off;
3318 }
3319 
3320 // Note: load_unsigned_short used to be called load_unsigned_word.
3321 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3322   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3323   // and "3.9 Partial Register Penalties", p. 22).
3324   int off;
3325   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3326     off = offset();
3327     movzwl(dst, src); // movzxw
3328   } else {
3329     xorl(dst, dst);
3330     off = offset();
3331     movw(dst, src);
3332   }
3333   return off;
3334 }
3335 
3336 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3337   switch (size_in_bytes) {
3338 #ifndef _LP64
3339   case  8:
3340     assert(dst2 != noreg, "second dest register required");
3341     movl(dst,  src);
3342     movl(dst2, src.plus_disp(BytesPerInt));
3343     break;
3344 #else
3345   case  8:  movq(dst, src); break;
3346 #endif
3347   case  4:  movl(dst, src); break;
3348   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3349   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3350   default:  ShouldNotReachHere();
3351   }
3352 }
3353 
3354 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3355   switch (size_in_bytes) {
3356 #ifndef _LP64
3357   case  8:
3358     assert(src2 != noreg, "second source register required");
3359     movl(dst,                        src);
3360     movl(dst.plus_disp(BytesPerInt), src2);
3361     break;
3362 #else
3363   case  8:  movq(dst, src); break;
3364 #endif
3365   case  4:  movl(dst, src); break;
3366   case  2:  movw(dst, src); break;
3367   case  1:  movb(dst, src); break;
3368   default:  ShouldNotReachHere();
3369   }
3370 }
3371 
3372 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3373   if (reachable(dst)) {
3374     movl(as_Address(dst), src);
3375   } else {
3376     lea(rscratch1, dst);
3377     movl(Address(rscratch1, 0), src);
3378   }
3379 }
3380 
3381 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3382   if (reachable(src)) {
3383     movl(dst, as_Address(src));
3384   } else {
3385     lea(rscratch1, src);
3386     movl(dst, Address(rscratch1, 0));
3387   }
3388 }
3389 
3390 // C++ bool manipulation
3391 
3392 void MacroAssembler::movbool(Register dst, Address src) {
3393   if(sizeof(bool) == 1)
3394     movb(dst, src);
3395   else if(sizeof(bool) == 2)
3396     movw(dst, src);
3397   else if(sizeof(bool) == 4)
3398     movl(dst, src);
3399   else
3400     // unsupported
3401     ShouldNotReachHere();
3402 }
3403 
3404 void MacroAssembler::movbool(Address dst, bool boolconst) {
3405   if(sizeof(bool) == 1)
3406     movb(dst, (int) boolconst);
3407   else if(sizeof(bool) == 2)
3408     movw(dst, (int) boolconst);
3409   else if(sizeof(bool) == 4)
3410     movl(dst, (int) boolconst);
3411   else
3412     // unsupported
3413     ShouldNotReachHere();
3414 }
3415 
3416 void MacroAssembler::movbool(Address dst, Register src) {
3417   if(sizeof(bool) == 1)
3418     movb(dst, src);
3419   else if(sizeof(bool) == 2)
3420     movw(dst, src);
3421   else if(sizeof(bool) == 4)
3422     movl(dst, src);
3423   else
3424     // unsupported
3425     ShouldNotReachHere();
3426 }
3427 
3428 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3429   movb(as_Address(dst), src);
3430 }
3431 
3432 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3433   if (reachable(src)) {
3434     movdl(dst, as_Address(src));
3435   } else {
3436     lea(rscratch1, src);
3437     movdl(dst, Address(rscratch1, 0));
3438   }
3439 }
3440 
3441 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3442   if (reachable(src)) {
3443     movq(dst, as_Address(src));
3444   } else {
3445     lea(rscratch1, src);
3446     movq(dst, Address(rscratch1, 0));
3447   }
3448 }
3449 
3450 void MacroAssembler::setvectmask(Register dst, Register src) {
3451   Assembler::movl(dst, 1);
3452   Assembler::shlxl(dst, dst, src);
3453   Assembler::decl(dst);
3454   Assembler::kmovdl(k1, dst);
3455   Assembler::movl(dst, src);
3456 }
3457 
3458 void MacroAssembler::restorevectmask() {
3459   Assembler::knotwl(k1, k0);
3460 }
3461 
3462 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3463   if (reachable(src)) {
3464     if (UseXmmLoadAndClearUpper) {
3465       movsd (dst, as_Address(src));
3466     } else {
3467       movlpd(dst, as_Address(src));
3468     }
3469   } else {
3470     lea(rscratch1, src);
3471     if (UseXmmLoadAndClearUpper) {
3472       movsd (dst, Address(rscratch1, 0));
3473     } else {
3474       movlpd(dst, Address(rscratch1, 0));
3475     }
3476   }
3477 }
3478 
3479 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3480   if (reachable(src)) {
3481     movss(dst, as_Address(src));
3482   } else {
3483     lea(rscratch1, src);
3484     movss(dst, Address(rscratch1, 0));
3485   }
3486 }
3487 
3488 void MacroAssembler::movptr(Register dst, Register src) {
3489   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3490 }
3491 
3492 void MacroAssembler::movptr(Register dst, Address src) {
3493   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3494 }
3495 
3496 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3497 void MacroAssembler::movptr(Register dst, intptr_t src) {
3498   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3499 }
3500 
3501 void MacroAssembler::movptr(Address dst, Register src) {
3502   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3503 }
3504 
3505 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3506   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3507     Assembler::vextractf32x4(dst, src, 0);
3508   } else {
3509     Assembler::movdqu(dst, src);
3510   }
3511 }
3512 
3513 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3514   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3515     Assembler::vinsertf32x4(dst, dst, src, 0);
3516   } else {
3517     Assembler::movdqu(dst, src);
3518   }
3519 }
3520 
3521 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3522   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3523     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3524   } else {
3525     Assembler::movdqu(dst, src);
3526   }
3527 }
3528 
3529 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3530   if (reachable(src)) {
3531     movdqu(dst, as_Address(src));
3532   } else {
3533     lea(scratchReg, src);
3534     movdqu(dst, Address(scratchReg, 0));
3535   }
3536 }
3537 
3538 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3539   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3540     vextractf64x4_low(dst, src);
3541   } else {
3542     Assembler::vmovdqu(dst, src);
3543   }
3544 }
3545 
3546 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3547   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3548     vinsertf64x4_low(dst, src);
3549   } else {
3550     Assembler::vmovdqu(dst, src);
3551   }
3552 }
3553 
3554 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3555   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3556     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3557   }
3558   else {
3559     Assembler::vmovdqu(dst, src);
3560   }
3561 }
3562 
3563 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3564   if (reachable(src)) {
3565     vmovdqu(dst, as_Address(src));
3566   }
3567   else {
3568     lea(rscratch1, src);
3569     vmovdqu(dst, Address(rscratch1, 0));
3570   }
3571 }
3572 
3573 void MacroAssembler::evmovdquq(XMMRegister dst, AddressLiteral src, int vector_len, Register rscratch) {
3574   if (reachable(src)) {
3575     Assembler::evmovdquq(dst, as_Address(src), vector_len);
3576   } else {
3577     lea(rscratch, src);
3578     Assembler::evmovdquq(dst, Address(rscratch, 0), vector_len);
3579   }
3580 }
3581 
3582 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3583   if (reachable(src)) {
3584     Assembler::movdqa(dst, as_Address(src));
3585   } else {
3586     lea(rscratch1, src);
3587     Assembler::movdqa(dst, Address(rscratch1, 0));
3588   }
3589 }
3590 
3591 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3592   if (reachable(src)) {
3593     Assembler::movsd(dst, as_Address(src));
3594   } else {
3595     lea(rscratch1, src);
3596     Assembler::movsd(dst, Address(rscratch1, 0));
3597   }
3598 }
3599 
3600 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3601   if (reachable(src)) {
3602     Assembler::movss(dst, as_Address(src));
3603   } else {
3604     lea(rscratch1, src);
3605     Assembler::movss(dst, Address(rscratch1, 0));
3606   }
3607 }
3608 
3609 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3610   if (reachable(src)) {
3611     Assembler::mulsd(dst, as_Address(src));
3612   } else {
3613     lea(rscratch1, src);
3614     Assembler::mulsd(dst, Address(rscratch1, 0));
3615   }
3616 }
3617 
3618 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3619   if (reachable(src)) {
3620     Assembler::mulss(dst, as_Address(src));
3621   } else {
3622     lea(rscratch1, src);
3623     Assembler::mulss(dst, Address(rscratch1, 0));
3624   }
3625 }
3626 
3627 void MacroAssembler::null_check(Register reg, int offset) {
3628   if (needs_explicit_null_check(offset)) {
3629     // provoke OS NULL exception if reg = NULL by
3630     // accessing M[reg] w/o changing any (non-CC) registers
3631     // NOTE: cmpl is plenty here to provoke a segv
3632     cmpptr(rax, Address(reg, 0));
3633     // Note: should probably use testl(rax, Address(reg, 0));
3634     //       may be shorter code (however, this version of
3635     //       testl needs to be implemented first)
3636   } else {
3637     // nothing to do, (later) access of M[reg + offset]
3638     // will provoke OS NULL exception if reg = NULL
3639   }
3640 }
3641 
3642 void MacroAssembler::os_breakpoint() {
3643   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3644   // (e.g., MSVC can't call ps() otherwise)
3645   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3646 }
3647 
3648 void MacroAssembler::unimplemented(const char* what) {
3649   const char* buf = NULL;
3650   {
3651     ResourceMark rm;
3652     stringStream ss;
3653     ss.print("unimplemented: %s", what);
3654     buf = code_string(ss.as_string());
3655   }
3656   stop(buf);
3657 }
3658 
3659 #ifdef _LP64
3660 #define XSTATE_BV 0x200
3661 #endif
3662 
3663 void MacroAssembler::pop_CPU_state() {
3664   pop_FPU_state();
3665   pop_IU_state();
3666 }
3667 
3668 void MacroAssembler::pop_FPU_state() {
3669 #ifndef _LP64
3670   frstor(Address(rsp, 0));
3671 #else
3672   fxrstor(Address(rsp, 0));
3673 #endif
3674   addptr(rsp, FPUStateSizeInWords * wordSize);
3675 }
3676 
3677 void MacroAssembler::pop_IU_state() {
3678   popa();
3679   LP64_ONLY(addq(rsp, 8));
3680   popf();
3681 }
3682 
3683 // Save Integer and Float state
3684 // Warning: Stack must be 16 byte aligned (64bit)
3685 void MacroAssembler::push_CPU_state() {
3686   push_IU_state();
3687   push_FPU_state();
3688 }
3689 
3690 void MacroAssembler::push_FPU_state() {
3691   subptr(rsp, FPUStateSizeInWords * wordSize);
3692 #ifndef _LP64
3693   fnsave(Address(rsp, 0));
3694   fwait();
3695 #else
3696   fxsave(Address(rsp, 0));
3697 #endif // LP64
3698 }
3699 
3700 void MacroAssembler::push_IU_state() {
3701   // Push flags first because pusha kills them
3702   pushf();
3703   // Make sure rsp stays 16-byte aligned
3704   LP64_ONLY(subq(rsp, 8));
3705   pusha();
3706 }
3707 
3708 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3709   if (!java_thread->is_valid()) {
3710     java_thread = rdi;
3711     get_thread(java_thread);
3712   }
3713   // we must set sp to zero to clear frame
3714   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3715   if (clear_fp) {
3716     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3717   }
3718 
3719   // Always clear the pc because it could have been set by make_walkable()
3720   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3721 
3722   vzeroupper();
3723 }
3724 
3725 void MacroAssembler::restore_rax(Register tmp) {
3726   if (tmp == noreg) pop(rax);
3727   else if (tmp != rax) mov(rax, tmp);
3728 }
3729 
3730 void MacroAssembler::round_to(Register reg, int modulus) {
3731   addptr(reg, modulus - 1);
3732   andptr(reg, -modulus);
3733 }
3734 
3735 void MacroAssembler::save_rax(Register tmp) {
3736   if (tmp == noreg) push(rax);
3737   else if (tmp != rax) mov(tmp, rax);
3738 }
3739 
3740 // Write serialization page so VM thread can do a pseudo remote membar.
3741 // We use the current thread pointer to calculate a thread specific
3742 // offset to write to within the page. This minimizes bus traffic
3743 // due to cache line collision.
3744 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3745   movl(tmp, thread);
3746   shrl(tmp, os::get_serialize_page_shift_count());
3747   andl(tmp, (os::vm_page_size() - sizeof(int)));
3748 
3749   Address index(noreg, tmp, Address::times_1);
3750   ExternalAddress page(os::get_memory_serialize_page());
3751 
3752   // Size of store must match masking code above
3753   movl(as_Address(ArrayAddress(page, index)), tmp);
3754 }
3755 
3756 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, Register temp_reg) {
3757   if (SafepointMechanism::uses_thread_local_poll()) {
3758 #ifdef _LP64
3759     assert(thread_reg == r15_thread, "should be");
3760 #else
3761     if (thread_reg == noreg) {
3762       thread_reg = temp_reg;
3763       get_thread(thread_reg);
3764     }
3765 #endif
3766     testb(Address(thread_reg, Thread::polling_page_offset()), SafepointMechanism::poll_bit());
3767     jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
3768   } else {
3769     cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3770         SafepointSynchronize::_not_synchronized);
3771     jcc(Assembler::notEqual, slow_path);
3772   }
3773 }
3774 
3775 // Calls to C land
3776 //
3777 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3778 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3779 // has to be reset to 0. This is required to allow proper stack traversal.
3780 void MacroAssembler::set_last_Java_frame(Register java_thread,
3781                                          Register last_java_sp,
3782                                          Register last_java_fp,
3783                                          address  last_java_pc) {
3784   vzeroupper();
3785   // determine java_thread register
3786   if (!java_thread->is_valid()) {
3787     java_thread = rdi;
3788     get_thread(java_thread);
3789   }
3790   // determine last_java_sp register
3791   if (!last_java_sp->is_valid()) {
3792     last_java_sp = rsp;
3793   }
3794 
3795   // last_java_fp is optional
3796 
3797   if (last_java_fp->is_valid()) {
3798     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3799   }
3800 
3801   // last_java_pc is optional
3802 
3803   if (last_java_pc != NULL) {
3804     lea(Address(java_thread,
3805                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3806         InternalAddress(last_java_pc));
3807 
3808   }
3809   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3810 }
3811 
3812 void MacroAssembler::shlptr(Register dst, int imm8) {
3813   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3814 }
3815 
3816 void MacroAssembler::shrptr(Register dst, int imm8) {
3817   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3818 }
3819 
3820 void MacroAssembler::sign_extend_byte(Register reg) {
3821   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3822     movsbl(reg, reg); // movsxb
3823   } else {
3824     shll(reg, 24);
3825     sarl(reg, 24);
3826   }
3827 }
3828 
3829 void MacroAssembler::sign_extend_short(Register reg) {
3830   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3831     movswl(reg, reg); // movsxw
3832   } else {
3833     shll(reg, 16);
3834     sarl(reg, 16);
3835   }
3836 }
3837 
3838 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3839   assert(reachable(src), "Address should be reachable");
3840   testl(dst, as_Address(src));
3841 }
3842 
3843 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3844   int dst_enc = dst->encoding();
3845   int src_enc = src->encoding();
3846   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3847     Assembler::pcmpeqb(dst, src);
3848   } else if ((dst_enc < 16) && (src_enc < 16)) {
3849     Assembler::pcmpeqb(dst, src);
3850   } else if (src_enc < 16) {
3851     subptr(rsp, 64);
3852     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3853     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3854     Assembler::pcmpeqb(xmm0, src);
3855     movdqu(dst, xmm0);
3856     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3857     addptr(rsp, 64);
3858   } else if (dst_enc < 16) {
3859     subptr(rsp, 64);
3860     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3861     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3862     Assembler::pcmpeqb(dst, xmm0);
3863     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3864     addptr(rsp, 64);
3865   } else {
3866     subptr(rsp, 64);
3867     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3868     subptr(rsp, 64);
3869     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3870     movdqu(xmm0, src);
3871     movdqu(xmm1, dst);
3872     Assembler::pcmpeqb(xmm1, xmm0);
3873     movdqu(dst, xmm1);
3874     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3875     addptr(rsp, 64);
3876     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3877     addptr(rsp, 64);
3878   }
3879 }
3880 
3881 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3882   int dst_enc = dst->encoding();
3883   int src_enc = src->encoding();
3884   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3885     Assembler::pcmpeqw(dst, src);
3886   } else if ((dst_enc < 16) && (src_enc < 16)) {
3887     Assembler::pcmpeqw(dst, src);
3888   } else if (src_enc < 16) {
3889     subptr(rsp, 64);
3890     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3891     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3892     Assembler::pcmpeqw(xmm0, src);
3893     movdqu(dst, xmm0);
3894     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3895     addptr(rsp, 64);
3896   } else if (dst_enc < 16) {
3897     subptr(rsp, 64);
3898     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3899     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3900     Assembler::pcmpeqw(dst, xmm0);
3901     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3902     addptr(rsp, 64);
3903   } else {
3904     subptr(rsp, 64);
3905     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3906     subptr(rsp, 64);
3907     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3908     movdqu(xmm0, src);
3909     movdqu(xmm1, dst);
3910     Assembler::pcmpeqw(xmm1, xmm0);
3911     movdqu(dst, xmm1);
3912     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3913     addptr(rsp, 64);
3914     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3915     addptr(rsp, 64);
3916   }
3917 }
3918 
3919 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3920   int dst_enc = dst->encoding();
3921   if (dst_enc < 16) {
3922     Assembler::pcmpestri(dst, src, imm8);
3923   } else {
3924     subptr(rsp, 64);
3925     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3926     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3927     Assembler::pcmpestri(xmm0, src, imm8);
3928     movdqu(dst, xmm0);
3929     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3930     addptr(rsp, 64);
3931   }
3932 }
3933 
3934 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3935   int dst_enc = dst->encoding();
3936   int src_enc = src->encoding();
3937   if ((dst_enc < 16) && (src_enc < 16)) {
3938     Assembler::pcmpestri(dst, src, imm8);
3939   } else if (src_enc < 16) {
3940     subptr(rsp, 64);
3941     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3942     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3943     Assembler::pcmpestri(xmm0, src, imm8);
3944     movdqu(dst, xmm0);
3945     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3946     addptr(rsp, 64);
3947   } else if (dst_enc < 16) {
3948     subptr(rsp, 64);
3949     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3950     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3951     Assembler::pcmpestri(dst, xmm0, imm8);
3952     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3953     addptr(rsp, 64);
3954   } else {
3955     subptr(rsp, 64);
3956     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3957     subptr(rsp, 64);
3958     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3959     movdqu(xmm0, src);
3960     movdqu(xmm1, dst);
3961     Assembler::pcmpestri(xmm1, xmm0, imm8);
3962     movdqu(dst, xmm1);
3963     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3964     addptr(rsp, 64);
3965     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3966     addptr(rsp, 64);
3967   }
3968 }
3969 
3970 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3971   int dst_enc = dst->encoding();
3972   int src_enc = src->encoding();
3973   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3974     Assembler::pmovzxbw(dst, src);
3975   } else if ((dst_enc < 16) && (src_enc < 16)) {
3976     Assembler::pmovzxbw(dst, src);
3977   } else if (src_enc < 16) {
3978     subptr(rsp, 64);
3979     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3980     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3981     Assembler::pmovzxbw(xmm0, src);
3982     movdqu(dst, xmm0);
3983     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3984     addptr(rsp, 64);
3985   } else if (dst_enc < 16) {
3986     subptr(rsp, 64);
3987     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3988     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3989     Assembler::pmovzxbw(dst, xmm0);
3990     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3991     addptr(rsp, 64);
3992   } else {
3993     subptr(rsp, 64);
3994     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3995     subptr(rsp, 64);
3996     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3997     movdqu(xmm0, src);
3998     movdqu(xmm1, dst);
3999     Assembler::pmovzxbw(xmm1, xmm0);
4000     movdqu(dst, xmm1);
4001     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4002     addptr(rsp, 64);
4003     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4004     addptr(rsp, 64);
4005   }
4006 }
4007 
4008 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4009   int dst_enc = dst->encoding();
4010   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4011     Assembler::pmovzxbw(dst, src);
4012   } else if (dst_enc < 16) {
4013     Assembler::pmovzxbw(dst, src);
4014   } else {
4015     subptr(rsp, 64);
4016     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4017     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4018     Assembler::pmovzxbw(xmm0, src);
4019     movdqu(dst, xmm0);
4020     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4021     addptr(rsp, 64);
4022   }
4023 }
4024 
4025 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4026   int src_enc = src->encoding();
4027   if (src_enc < 16) {
4028     Assembler::pmovmskb(dst, src);
4029   } else {
4030     subptr(rsp, 64);
4031     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4032     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4033     Assembler::pmovmskb(dst, xmm0);
4034     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4035     addptr(rsp, 64);
4036   }
4037 }
4038 
4039 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4040   int dst_enc = dst->encoding();
4041   int src_enc = src->encoding();
4042   if ((dst_enc < 16) && (src_enc < 16)) {
4043     Assembler::ptest(dst, src);
4044   } else if (src_enc < 16) {
4045     subptr(rsp, 64);
4046     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4047     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4048     Assembler::ptest(xmm0, src);
4049     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4050     addptr(rsp, 64);
4051   } else if (dst_enc < 16) {
4052     subptr(rsp, 64);
4053     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4054     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4055     Assembler::ptest(dst, xmm0);
4056     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4057     addptr(rsp, 64);
4058   } else {
4059     subptr(rsp, 64);
4060     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4061     subptr(rsp, 64);
4062     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4063     movdqu(xmm0, src);
4064     movdqu(xmm1, dst);
4065     Assembler::ptest(xmm1, xmm0);
4066     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4067     addptr(rsp, 64);
4068     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4069     addptr(rsp, 64);
4070   }
4071 }
4072 
4073 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4074   if (reachable(src)) {
4075     Assembler::sqrtsd(dst, as_Address(src));
4076   } else {
4077     lea(rscratch1, src);
4078     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4079   }
4080 }
4081 
4082 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4083   if (reachable(src)) {
4084     Assembler::sqrtss(dst, as_Address(src));
4085   } else {
4086     lea(rscratch1, src);
4087     Assembler::sqrtss(dst, Address(rscratch1, 0));
4088   }
4089 }
4090 
4091 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4092   if (reachable(src)) {
4093     Assembler::subsd(dst, as_Address(src));
4094   } else {
4095     lea(rscratch1, src);
4096     Assembler::subsd(dst, Address(rscratch1, 0));
4097   }
4098 }
4099 
4100 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4101   if (reachable(src)) {
4102     Assembler::subss(dst, as_Address(src));
4103   } else {
4104     lea(rscratch1, src);
4105     Assembler::subss(dst, Address(rscratch1, 0));
4106   }
4107 }
4108 
4109 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4110   if (reachable(src)) {
4111     Assembler::ucomisd(dst, as_Address(src));
4112   } else {
4113     lea(rscratch1, src);
4114     Assembler::ucomisd(dst, Address(rscratch1, 0));
4115   }
4116 }
4117 
4118 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4119   if (reachable(src)) {
4120     Assembler::ucomiss(dst, as_Address(src));
4121   } else {
4122     lea(rscratch1, src);
4123     Assembler::ucomiss(dst, Address(rscratch1, 0));
4124   }
4125 }
4126 
4127 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4128   // Used in sign-bit flipping with aligned address.
4129   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4130   if (reachable(src)) {
4131     Assembler::xorpd(dst, as_Address(src));
4132   } else {
4133     lea(rscratch1, src);
4134     Assembler::xorpd(dst, Address(rscratch1, 0));
4135   }
4136 }
4137 
4138 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4139   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4140     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4141   }
4142   else {
4143     Assembler::xorpd(dst, src);
4144   }
4145 }
4146 
4147 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4148   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4149     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4150   } else {
4151     Assembler::xorps(dst, src);
4152   }
4153 }
4154 
4155 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4156   // Used in sign-bit flipping with aligned address.
4157   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4158   if (reachable(src)) {
4159     Assembler::xorps(dst, as_Address(src));
4160   } else {
4161     lea(rscratch1, src);
4162     Assembler::xorps(dst, Address(rscratch1, 0));
4163   }
4164 }
4165 
4166 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4167   // Used in sign-bit flipping with aligned address.
4168   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4169   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4170   if (reachable(src)) {
4171     Assembler::pshufb(dst, as_Address(src));
4172   } else {
4173     lea(rscratch1, src);
4174     Assembler::pshufb(dst, Address(rscratch1, 0));
4175   }
4176 }
4177 
4178 // AVX 3-operands instructions
4179 
4180 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4181   if (reachable(src)) {
4182     vaddsd(dst, nds, as_Address(src));
4183   } else {
4184     lea(rscratch1, src);
4185     vaddsd(dst, nds, Address(rscratch1, 0));
4186   }
4187 }
4188 
4189 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4190   if (reachable(src)) {
4191     vaddss(dst, nds, as_Address(src));
4192   } else {
4193     lea(rscratch1, src);
4194     vaddss(dst, nds, Address(rscratch1, 0));
4195   }
4196 }
4197 
4198 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4199   int dst_enc = dst->encoding();
4200   int nds_enc = nds->encoding();
4201   int src_enc = src->encoding();
4202   if ((dst_enc < 16) && (nds_enc < 16)) {
4203     vandps(dst, nds, negate_field, vector_len);
4204   } else if ((src_enc < 16) && (dst_enc < 16)) {
4205     evmovdqul(src, nds, Assembler::AVX_512bit);
4206     vandps(dst, src, negate_field, vector_len);
4207   } else if (src_enc < 16) {
4208     evmovdqul(src, nds, Assembler::AVX_512bit);
4209     vandps(src, src, negate_field, vector_len);
4210     evmovdqul(dst, src, Assembler::AVX_512bit);
4211   } else if (dst_enc < 16) {
4212     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4213     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4214     vandps(dst, xmm0, negate_field, vector_len);
4215     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4216   } else {
4217     if (src_enc != dst_enc) {
4218       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4219       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4220       vandps(xmm0, xmm0, negate_field, vector_len);
4221       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4222       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4223     } else {
4224       subptr(rsp, 64);
4225       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4226       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4227       vandps(xmm0, xmm0, negate_field, vector_len);
4228       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4229       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4230       addptr(rsp, 64);
4231     }
4232   }
4233 }
4234 
4235 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4236   int dst_enc = dst->encoding();
4237   int nds_enc = nds->encoding();
4238   int src_enc = src->encoding();
4239   if ((dst_enc < 16) && (nds_enc < 16)) {
4240     vandpd(dst, nds, negate_field, vector_len);
4241   } else if ((src_enc < 16) && (dst_enc < 16)) {
4242     evmovdqul(src, nds, Assembler::AVX_512bit);
4243     vandpd(dst, src, negate_field, vector_len);
4244   } else if (src_enc < 16) {
4245     evmovdqul(src, nds, Assembler::AVX_512bit);
4246     vandpd(src, src, negate_field, vector_len);
4247     evmovdqul(dst, src, Assembler::AVX_512bit);
4248   } else if (dst_enc < 16) {
4249     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4250     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4251     vandpd(dst, xmm0, negate_field, vector_len);
4252     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4253   } else {
4254     if (src_enc != dst_enc) {
4255       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4256       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4257       vandpd(xmm0, xmm0, negate_field, vector_len);
4258       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4259       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4260     } else {
4261       subptr(rsp, 64);
4262       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4263       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4264       vandpd(xmm0, xmm0, negate_field, vector_len);
4265       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4266       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4267       addptr(rsp, 64);
4268     }
4269   }
4270 }
4271 
4272 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4273   int dst_enc = dst->encoding();
4274   int nds_enc = nds->encoding();
4275   int src_enc = src->encoding();
4276   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4277     Assembler::vpaddb(dst, nds, src, vector_len);
4278   } else if ((dst_enc < 16) && (src_enc < 16)) {
4279     Assembler::vpaddb(dst, dst, src, vector_len);
4280   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4281     // use nds as scratch for src
4282     evmovdqul(nds, src, Assembler::AVX_512bit);
4283     Assembler::vpaddb(dst, dst, nds, vector_len);
4284   } else if ((src_enc < 16) && (nds_enc < 16)) {
4285     // use nds as scratch for dst
4286     evmovdqul(nds, dst, Assembler::AVX_512bit);
4287     Assembler::vpaddb(nds, nds, src, vector_len);
4288     evmovdqul(dst, nds, Assembler::AVX_512bit);
4289   } else if (dst_enc < 16) {
4290     // use nds as scatch for xmm0 to hold src
4291     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4292     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4293     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4294     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4295   } else {
4296     // worse case scenario, all regs are in the upper bank
4297     subptr(rsp, 64);
4298     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4299     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4300     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4301     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4302     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4303     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4304     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4305     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4306     addptr(rsp, 64);
4307   }
4308 }
4309 
4310 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4311   int dst_enc = dst->encoding();
4312   int nds_enc = nds->encoding();
4313   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4314     Assembler::vpaddb(dst, nds, src, vector_len);
4315   } else if (dst_enc < 16) {
4316     Assembler::vpaddb(dst, dst, src, vector_len);
4317   } else if (nds_enc < 16) {
4318     // implies dst_enc in upper bank with src as scratch
4319     evmovdqul(nds, dst, Assembler::AVX_512bit);
4320     Assembler::vpaddb(nds, nds, src, vector_len);
4321     evmovdqul(dst, nds, Assembler::AVX_512bit);
4322   } else {
4323     // worse case scenario, all regs in upper bank
4324     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4325     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4326     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4327     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4328   }
4329 }
4330 
4331 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4332   int dst_enc = dst->encoding();
4333   int nds_enc = nds->encoding();
4334   int src_enc = src->encoding();
4335   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4336     Assembler::vpaddw(dst, nds, src, vector_len);
4337   } else if ((dst_enc < 16) && (src_enc < 16)) {
4338     Assembler::vpaddw(dst, dst, src, vector_len);
4339   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4340     // use nds as scratch for src
4341     evmovdqul(nds, src, Assembler::AVX_512bit);
4342     Assembler::vpaddw(dst, dst, nds, vector_len);
4343   } else if ((src_enc < 16) && (nds_enc < 16)) {
4344     // use nds as scratch for dst
4345     evmovdqul(nds, dst, Assembler::AVX_512bit);
4346     Assembler::vpaddw(nds, nds, src, vector_len);
4347     evmovdqul(dst, nds, Assembler::AVX_512bit);
4348   } else if (dst_enc < 16) {
4349     // use nds as scatch for xmm0 to hold src
4350     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4351     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4352     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4353     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4354   } else {
4355     // worse case scenario, all regs are in the upper bank
4356     subptr(rsp, 64);
4357     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4358     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4359     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4360     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4361     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4362     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4363     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4364     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4365     addptr(rsp, 64);
4366   }
4367 }
4368 
4369 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4370   int dst_enc = dst->encoding();
4371   int nds_enc = nds->encoding();
4372   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4373     Assembler::vpaddw(dst, nds, src, vector_len);
4374   } else if (dst_enc < 16) {
4375     Assembler::vpaddw(dst, dst, src, vector_len);
4376   } else if (nds_enc < 16) {
4377     // implies dst_enc in upper bank with src as scratch
4378     evmovdqul(nds, dst, Assembler::AVX_512bit);
4379     Assembler::vpaddw(nds, nds, src, vector_len);
4380     evmovdqul(dst, nds, Assembler::AVX_512bit);
4381   } else {
4382     // worse case scenario, all regs in upper bank
4383     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4384     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4385     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4386     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4387   }
4388 }
4389 
4390 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4391   if (reachable(src)) {
4392     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4393   } else {
4394     lea(rscratch1, src);
4395     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4396   }
4397 }
4398 
4399 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4400   int dst_enc = dst->encoding();
4401   int src_enc = src->encoding();
4402   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4403     Assembler::vpbroadcastw(dst, src);
4404   } else if ((dst_enc < 16) && (src_enc < 16)) {
4405     Assembler::vpbroadcastw(dst, src);
4406   } else if (src_enc < 16) {
4407     subptr(rsp, 64);
4408     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4409     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4410     Assembler::vpbroadcastw(xmm0, src);
4411     movdqu(dst, xmm0);
4412     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4413     addptr(rsp, 64);
4414   } else if (dst_enc < 16) {
4415     subptr(rsp, 64);
4416     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4417     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4418     Assembler::vpbroadcastw(dst, xmm0);
4419     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4420     addptr(rsp, 64);
4421   } else {
4422     subptr(rsp, 64);
4423     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4424     subptr(rsp, 64);
4425     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4426     movdqu(xmm0, src);
4427     movdqu(xmm1, dst);
4428     Assembler::vpbroadcastw(xmm1, xmm0);
4429     movdqu(dst, xmm1);
4430     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4431     addptr(rsp, 64);
4432     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4433     addptr(rsp, 64);
4434   }
4435 }
4436 
4437 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4438   int dst_enc = dst->encoding();
4439   int nds_enc = nds->encoding();
4440   int src_enc = src->encoding();
4441   assert(dst_enc == nds_enc, "");
4442   if ((dst_enc < 16) && (src_enc < 16)) {
4443     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4444   } else if (src_enc < 16) {
4445     subptr(rsp, 64);
4446     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4447     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4448     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4449     movdqu(dst, xmm0);
4450     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4451     addptr(rsp, 64);
4452   } else if (dst_enc < 16) {
4453     subptr(rsp, 64);
4454     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4455     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4456     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4457     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4458     addptr(rsp, 64);
4459   } else {
4460     subptr(rsp, 64);
4461     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4462     subptr(rsp, 64);
4463     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4464     movdqu(xmm0, src);
4465     movdqu(xmm1, dst);
4466     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4467     movdqu(dst, xmm1);
4468     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4469     addptr(rsp, 64);
4470     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4471     addptr(rsp, 64);
4472   }
4473 }
4474 
4475 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4476   int dst_enc = dst->encoding();
4477   int nds_enc = nds->encoding();
4478   int src_enc = src->encoding();
4479   assert(dst_enc == nds_enc, "");
4480   if ((dst_enc < 16) && (src_enc < 16)) {
4481     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4482   } else if (src_enc < 16) {
4483     subptr(rsp, 64);
4484     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4485     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4486     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4487     movdqu(dst, xmm0);
4488     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4489     addptr(rsp, 64);
4490   } else if (dst_enc < 16) {
4491     subptr(rsp, 64);
4492     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4493     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4494     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4495     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4496     addptr(rsp, 64);
4497   } else {
4498     subptr(rsp, 64);
4499     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4500     subptr(rsp, 64);
4501     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4502     movdqu(xmm0, src);
4503     movdqu(xmm1, dst);
4504     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4505     movdqu(dst, xmm1);
4506     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4507     addptr(rsp, 64);
4508     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4509     addptr(rsp, 64);
4510   }
4511 }
4512 
4513 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4514   int dst_enc = dst->encoding();
4515   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4516     Assembler::vpmovzxbw(dst, src, vector_len);
4517   } else if (dst_enc < 16) {
4518     Assembler::vpmovzxbw(dst, src, vector_len);
4519   } else {
4520     subptr(rsp, 64);
4521     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4522     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4523     Assembler::vpmovzxbw(xmm0, src, vector_len);
4524     movdqu(dst, xmm0);
4525     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4526     addptr(rsp, 64);
4527   }
4528 }
4529 
4530 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4531   int src_enc = src->encoding();
4532   if (src_enc < 16) {
4533     Assembler::vpmovmskb(dst, src);
4534   } else {
4535     subptr(rsp, 64);
4536     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4537     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4538     Assembler::vpmovmskb(dst, xmm0);
4539     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4540     addptr(rsp, 64);
4541   }
4542 }
4543 
4544 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4545   int dst_enc = dst->encoding();
4546   int nds_enc = nds->encoding();
4547   int src_enc = src->encoding();
4548   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4549     Assembler::vpmullw(dst, nds, src, vector_len);
4550   } else if ((dst_enc < 16) && (src_enc < 16)) {
4551     Assembler::vpmullw(dst, dst, src, vector_len);
4552   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4553     // use nds as scratch for src
4554     evmovdqul(nds, src, Assembler::AVX_512bit);
4555     Assembler::vpmullw(dst, dst, nds, vector_len);
4556   } else if ((src_enc < 16) && (nds_enc < 16)) {
4557     // use nds as scratch for dst
4558     evmovdqul(nds, dst, Assembler::AVX_512bit);
4559     Assembler::vpmullw(nds, nds, src, vector_len);
4560     evmovdqul(dst, nds, Assembler::AVX_512bit);
4561   } else if (dst_enc < 16) {
4562     // use nds as scatch for xmm0 to hold src
4563     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4564     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4565     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4566     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4567   } else {
4568     // worse case scenario, all regs are in the upper bank
4569     subptr(rsp, 64);
4570     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4571     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4572     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4573     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4574     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4575     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4576     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4577     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4578     addptr(rsp, 64);
4579   }
4580 }
4581 
4582 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4583   int dst_enc = dst->encoding();
4584   int nds_enc = nds->encoding();
4585   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4586     Assembler::vpmullw(dst, nds, src, vector_len);
4587   } else if (dst_enc < 16) {
4588     Assembler::vpmullw(dst, dst, src, vector_len);
4589   } else if (nds_enc < 16) {
4590     // implies dst_enc in upper bank with src as scratch
4591     evmovdqul(nds, dst, Assembler::AVX_512bit);
4592     Assembler::vpmullw(nds, nds, src, vector_len);
4593     evmovdqul(dst, nds, Assembler::AVX_512bit);
4594   } else {
4595     // worse case scenario, all regs in upper bank
4596     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4597     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4598     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4599     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4600   }
4601 }
4602 
4603 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4604   int dst_enc = dst->encoding();
4605   int nds_enc = nds->encoding();
4606   int src_enc = src->encoding();
4607   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4608     Assembler::vpsubb(dst, nds, src, vector_len);
4609   } else if ((dst_enc < 16) && (src_enc < 16)) {
4610     Assembler::vpsubb(dst, dst, src, vector_len);
4611   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4612     // use nds as scratch for src
4613     evmovdqul(nds, src, Assembler::AVX_512bit);
4614     Assembler::vpsubb(dst, dst, nds, vector_len);
4615   } else if ((src_enc < 16) && (nds_enc < 16)) {
4616     // use nds as scratch for dst
4617     evmovdqul(nds, dst, Assembler::AVX_512bit);
4618     Assembler::vpsubb(nds, nds, src, vector_len);
4619     evmovdqul(dst, nds, Assembler::AVX_512bit);
4620   } else if (dst_enc < 16) {
4621     // use nds as scatch for xmm0 to hold src
4622     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4623     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4624     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4625     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4626   } else {
4627     // worse case scenario, all regs are in the upper bank
4628     subptr(rsp, 64);
4629     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4630     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4631     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4632     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4633     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4634     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4635     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4636     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4637     addptr(rsp, 64);
4638   }
4639 }
4640 
4641 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4642   int dst_enc = dst->encoding();
4643   int nds_enc = nds->encoding();
4644   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4645     Assembler::vpsubb(dst, nds, src, vector_len);
4646   } else if (dst_enc < 16) {
4647     Assembler::vpsubb(dst, dst, src, vector_len);
4648   } else if (nds_enc < 16) {
4649     // implies dst_enc in upper bank with src as scratch
4650     evmovdqul(nds, dst, Assembler::AVX_512bit);
4651     Assembler::vpsubb(nds, nds, src, vector_len);
4652     evmovdqul(dst, nds, Assembler::AVX_512bit);
4653   } else {
4654     // worse case scenario, all regs in upper bank
4655     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4656     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4657     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4658     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4659   }
4660 }
4661 
4662 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4663   int dst_enc = dst->encoding();
4664   int nds_enc = nds->encoding();
4665   int src_enc = src->encoding();
4666   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4667     Assembler::vpsubw(dst, nds, src, vector_len);
4668   } else if ((dst_enc < 16) && (src_enc < 16)) {
4669     Assembler::vpsubw(dst, dst, src, vector_len);
4670   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4671     // use nds as scratch for src
4672     evmovdqul(nds, src, Assembler::AVX_512bit);
4673     Assembler::vpsubw(dst, dst, nds, vector_len);
4674   } else if ((src_enc < 16) && (nds_enc < 16)) {
4675     // use nds as scratch for dst
4676     evmovdqul(nds, dst, Assembler::AVX_512bit);
4677     Assembler::vpsubw(nds, nds, src, vector_len);
4678     evmovdqul(dst, nds, Assembler::AVX_512bit);
4679   } else if (dst_enc < 16) {
4680     // use nds as scatch for xmm0 to hold src
4681     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4682     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4683     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4684     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4685   } else {
4686     // worse case scenario, all regs are in the upper bank
4687     subptr(rsp, 64);
4688     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4689     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4690     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4691     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4692     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4693     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4694     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4695     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4696     addptr(rsp, 64);
4697   }
4698 }
4699 
4700 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4701   int dst_enc = dst->encoding();
4702   int nds_enc = nds->encoding();
4703   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4704     Assembler::vpsubw(dst, nds, src, vector_len);
4705   } else if (dst_enc < 16) {
4706     Assembler::vpsubw(dst, dst, src, vector_len);
4707   } else if (nds_enc < 16) {
4708     // implies dst_enc in upper bank with src as scratch
4709     evmovdqul(nds, dst, Assembler::AVX_512bit);
4710     Assembler::vpsubw(nds, nds, src, vector_len);
4711     evmovdqul(dst, nds, Assembler::AVX_512bit);
4712   } else {
4713     // worse case scenario, all regs in upper bank
4714     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4715     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4716     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4717     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4718   }
4719 }
4720 
4721 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4722   int dst_enc = dst->encoding();
4723   int nds_enc = nds->encoding();
4724   int shift_enc = shift->encoding();
4725   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4726     Assembler::vpsraw(dst, nds, shift, vector_len);
4727   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4728     Assembler::vpsraw(dst, dst, shift, vector_len);
4729   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4730     // use nds_enc as scratch with shift
4731     evmovdqul(nds, shift, Assembler::AVX_512bit);
4732     Assembler::vpsraw(dst, dst, nds, vector_len);
4733   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4734     // use nds as scratch with dst
4735     evmovdqul(nds, dst, Assembler::AVX_512bit);
4736     Assembler::vpsraw(nds, nds, shift, vector_len);
4737     evmovdqul(dst, nds, Assembler::AVX_512bit);
4738   } else if (dst_enc < 16) {
4739     // use nds to save a copy of xmm0 and hold shift
4740     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4741     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4742     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4743     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4744   } else if (nds_enc < 16) {
4745     // use nds as dest as temps
4746     evmovdqul(nds, dst, Assembler::AVX_512bit);
4747     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4748     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4749     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4750     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4751     evmovdqul(dst, nds, Assembler::AVX_512bit);
4752   } else {
4753     // worse case scenario, all regs are in the upper bank
4754     subptr(rsp, 64);
4755     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4756     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4757     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4758     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4759     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4760     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4761     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4762     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4763     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4764     addptr(rsp, 64);
4765   }
4766 }
4767 
4768 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4769   int dst_enc = dst->encoding();
4770   int nds_enc = nds->encoding();
4771   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4772     Assembler::vpsraw(dst, nds, shift, vector_len);
4773   } else if (dst_enc < 16) {
4774     Assembler::vpsraw(dst, dst, shift, vector_len);
4775   } else if (nds_enc < 16) {
4776     // use nds as scratch
4777     evmovdqul(nds, dst, Assembler::AVX_512bit);
4778     Assembler::vpsraw(nds, nds, shift, vector_len);
4779     evmovdqul(dst, nds, Assembler::AVX_512bit);
4780   } else {
4781     // use nds as scratch for xmm0
4782     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4783     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4784     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4785     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4786   }
4787 }
4788 
4789 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4790   int dst_enc = dst->encoding();
4791   int nds_enc = nds->encoding();
4792   int shift_enc = shift->encoding();
4793   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4794     Assembler::vpsrlw(dst, nds, shift, vector_len);
4795   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4796     Assembler::vpsrlw(dst, dst, shift, vector_len);
4797   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4798     // use nds_enc as scratch with shift
4799     evmovdqul(nds, shift, Assembler::AVX_512bit);
4800     Assembler::vpsrlw(dst, dst, nds, vector_len);
4801   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4802     // use nds as scratch with dst
4803     evmovdqul(nds, dst, Assembler::AVX_512bit);
4804     Assembler::vpsrlw(nds, nds, shift, vector_len);
4805     evmovdqul(dst, nds, Assembler::AVX_512bit);
4806   } else if (dst_enc < 16) {
4807     // use nds to save a copy of xmm0 and hold shift
4808     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4809     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4810     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4811     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4812   } else if (nds_enc < 16) {
4813     // use nds as dest as temps
4814     evmovdqul(nds, dst, Assembler::AVX_512bit);
4815     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4816     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4817     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4818     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4819     evmovdqul(dst, nds, Assembler::AVX_512bit);
4820   } else {
4821     // worse case scenario, all regs are in the upper bank
4822     subptr(rsp, 64);
4823     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4824     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4825     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4826     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4827     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4828     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4829     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4830     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4831     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4832     addptr(rsp, 64);
4833   }
4834 }
4835 
4836 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4837   int dst_enc = dst->encoding();
4838   int nds_enc = nds->encoding();
4839   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4840     Assembler::vpsrlw(dst, nds, shift, vector_len);
4841   } else if (dst_enc < 16) {
4842     Assembler::vpsrlw(dst, dst, shift, vector_len);
4843   } else if (nds_enc < 16) {
4844     // use nds as scratch
4845     evmovdqul(nds, dst, Assembler::AVX_512bit);
4846     Assembler::vpsrlw(nds, nds, shift, vector_len);
4847     evmovdqul(dst, nds, Assembler::AVX_512bit);
4848   } else {
4849     // use nds as scratch for xmm0
4850     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4851     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4852     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4853     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4854   }
4855 }
4856 
4857 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4858   int dst_enc = dst->encoding();
4859   int nds_enc = nds->encoding();
4860   int shift_enc = shift->encoding();
4861   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4862     Assembler::vpsllw(dst, nds, shift, vector_len);
4863   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4864     Assembler::vpsllw(dst, dst, shift, vector_len);
4865   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4866     // use nds_enc as scratch with shift
4867     evmovdqul(nds, shift, Assembler::AVX_512bit);
4868     Assembler::vpsllw(dst, dst, nds, vector_len);
4869   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4870     // use nds as scratch with dst
4871     evmovdqul(nds, dst, Assembler::AVX_512bit);
4872     Assembler::vpsllw(nds, nds, shift, vector_len);
4873     evmovdqul(dst, nds, Assembler::AVX_512bit);
4874   } else if (dst_enc < 16) {
4875     // use nds to save a copy of xmm0 and hold shift
4876     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4877     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4878     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4879     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4880   } else if (nds_enc < 16) {
4881     // use nds as dest as temps
4882     evmovdqul(nds, dst, Assembler::AVX_512bit);
4883     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4884     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4885     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4886     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4887     evmovdqul(dst, nds, Assembler::AVX_512bit);
4888   } else {
4889     // worse case scenario, all regs are in the upper bank
4890     subptr(rsp, 64);
4891     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4892     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4893     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4894     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4895     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4896     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4897     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4898     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4899     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4900     addptr(rsp, 64);
4901   }
4902 }
4903 
4904 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4905   int dst_enc = dst->encoding();
4906   int nds_enc = nds->encoding();
4907   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4908     Assembler::vpsllw(dst, nds, shift, vector_len);
4909   } else if (dst_enc < 16) {
4910     Assembler::vpsllw(dst, dst, shift, vector_len);
4911   } else if (nds_enc < 16) {
4912     // use nds as scratch
4913     evmovdqul(nds, dst, Assembler::AVX_512bit);
4914     Assembler::vpsllw(nds, nds, shift, vector_len);
4915     evmovdqul(dst, nds, Assembler::AVX_512bit);
4916   } else {
4917     // use nds as scratch for xmm0
4918     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4919     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4920     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4921     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4922   }
4923 }
4924 
4925 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4926   int dst_enc = dst->encoding();
4927   int src_enc = src->encoding();
4928   if ((dst_enc < 16) && (src_enc < 16)) {
4929     Assembler::vptest(dst, src);
4930   } else if (src_enc < 16) {
4931     subptr(rsp, 64);
4932     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4933     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4934     Assembler::vptest(xmm0, src);
4935     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4936     addptr(rsp, 64);
4937   } else if (dst_enc < 16) {
4938     subptr(rsp, 64);
4939     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4940     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4941     Assembler::vptest(dst, xmm0);
4942     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4943     addptr(rsp, 64);
4944   } else {
4945     subptr(rsp, 64);
4946     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4947     subptr(rsp, 64);
4948     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4949     movdqu(xmm0, src);
4950     movdqu(xmm1, dst);
4951     Assembler::vptest(xmm1, xmm0);
4952     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4953     addptr(rsp, 64);
4954     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4955     addptr(rsp, 64);
4956   }
4957 }
4958 
4959 // This instruction exists within macros, ergo we cannot control its input
4960 // when emitted through those patterns.
4961 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4962   if (VM_Version::supports_avx512nobw()) {
4963     int dst_enc = dst->encoding();
4964     int src_enc = src->encoding();
4965     if (dst_enc == src_enc) {
4966       if (dst_enc < 16) {
4967         Assembler::punpcklbw(dst, src);
4968       } else {
4969         subptr(rsp, 64);
4970         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4971         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4972         Assembler::punpcklbw(xmm0, xmm0);
4973         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4974         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4975         addptr(rsp, 64);
4976       }
4977     } else {
4978       if ((src_enc < 16) && (dst_enc < 16)) {
4979         Assembler::punpcklbw(dst, src);
4980       } else if (src_enc < 16) {
4981         subptr(rsp, 64);
4982         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4983         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4984         Assembler::punpcklbw(xmm0, src);
4985         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4986         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4987         addptr(rsp, 64);
4988       } else if (dst_enc < 16) {
4989         subptr(rsp, 64);
4990         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4991         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4992         Assembler::punpcklbw(dst, xmm0);
4993         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4994         addptr(rsp, 64);
4995       } else {
4996         subptr(rsp, 64);
4997         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4998         subptr(rsp, 64);
4999         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5000         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5001         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5002         Assembler::punpcklbw(xmm0, xmm1);
5003         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5004         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5005         addptr(rsp, 64);
5006         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5007         addptr(rsp, 64);
5008       }
5009     }
5010   } else {
5011     Assembler::punpcklbw(dst, src);
5012   }
5013 }
5014 
5015 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
5016   if (VM_Version::supports_avx512vl()) {
5017     Assembler::pshufd(dst, src, mode);
5018   } else {
5019     int dst_enc = dst->encoding();
5020     if (dst_enc < 16) {
5021       Assembler::pshufd(dst, src, mode);
5022     } else {
5023       subptr(rsp, 64);
5024       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5025       Assembler::pshufd(xmm0, src, mode);
5026       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5027       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5028       addptr(rsp, 64);
5029     }
5030   }
5031 }
5032 
5033 // This instruction exists within macros, ergo we cannot control its input
5034 // when emitted through those patterns.
5035 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5036   if (VM_Version::supports_avx512nobw()) {
5037     int dst_enc = dst->encoding();
5038     int src_enc = src->encoding();
5039     if (dst_enc == src_enc) {
5040       if (dst_enc < 16) {
5041         Assembler::pshuflw(dst, src, mode);
5042       } else {
5043         subptr(rsp, 64);
5044         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5045         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5046         Assembler::pshuflw(xmm0, xmm0, mode);
5047         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5048         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5049         addptr(rsp, 64);
5050       }
5051     } else {
5052       if ((src_enc < 16) && (dst_enc < 16)) {
5053         Assembler::pshuflw(dst, src, mode);
5054       } else if (src_enc < 16) {
5055         subptr(rsp, 64);
5056         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5057         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5058         Assembler::pshuflw(xmm0, src, mode);
5059         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5060         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5061         addptr(rsp, 64);
5062       } else if (dst_enc < 16) {
5063         subptr(rsp, 64);
5064         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5065         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5066         Assembler::pshuflw(dst, xmm0, mode);
5067         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5068         addptr(rsp, 64);
5069       } else {
5070         subptr(rsp, 64);
5071         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5072         subptr(rsp, 64);
5073         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5074         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5075         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5076         Assembler::pshuflw(xmm0, xmm1, mode);
5077         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5078         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5079         addptr(rsp, 64);
5080         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5081         addptr(rsp, 64);
5082       }
5083     }
5084   } else {
5085     Assembler::pshuflw(dst, src, mode);
5086   }
5087 }
5088 
5089 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5090   if (reachable(src)) {
5091     vandpd(dst, nds, as_Address(src), vector_len);
5092   } else {
5093     lea(rscratch1, src);
5094     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5095   }
5096 }
5097 
5098 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5099   if (reachable(src)) {
5100     vandps(dst, nds, as_Address(src), vector_len);
5101   } else {
5102     lea(rscratch1, src);
5103     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5104   }
5105 }
5106 
5107 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5108   if (reachable(src)) {
5109     vdivsd(dst, nds, as_Address(src));
5110   } else {
5111     lea(rscratch1, src);
5112     vdivsd(dst, nds, Address(rscratch1, 0));
5113   }
5114 }
5115 
5116 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5117   if (reachable(src)) {
5118     vdivss(dst, nds, as_Address(src));
5119   } else {
5120     lea(rscratch1, src);
5121     vdivss(dst, nds, Address(rscratch1, 0));
5122   }
5123 }
5124 
5125 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5126   if (reachable(src)) {
5127     vmulsd(dst, nds, as_Address(src));
5128   } else {
5129     lea(rscratch1, src);
5130     vmulsd(dst, nds, Address(rscratch1, 0));
5131   }
5132 }
5133 
5134 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5135   if (reachable(src)) {
5136     vmulss(dst, nds, as_Address(src));
5137   } else {
5138     lea(rscratch1, src);
5139     vmulss(dst, nds, Address(rscratch1, 0));
5140   }
5141 }
5142 
5143 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5144   if (reachable(src)) {
5145     vsubsd(dst, nds, as_Address(src));
5146   } else {
5147     lea(rscratch1, src);
5148     vsubsd(dst, nds, Address(rscratch1, 0));
5149   }
5150 }
5151 
5152 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5153   if (reachable(src)) {
5154     vsubss(dst, nds, as_Address(src));
5155   } else {
5156     lea(rscratch1, src);
5157     vsubss(dst, nds, Address(rscratch1, 0));
5158   }
5159 }
5160 
5161 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5162   int nds_enc = nds->encoding();
5163   int dst_enc = dst->encoding();
5164   bool dst_upper_bank = (dst_enc > 15);
5165   bool nds_upper_bank = (nds_enc > 15);
5166   if (VM_Version::supports_avx512novl() &&
5167       (nds_upper_bank || dst_upper_bank)) {
5168     if (dst_upper_bank) {
5169       subptr(rsp, 64);
5170       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5171       movflt(xmm0, nds);
5172       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5173       movflt(dst, xmm0);
5174       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5175       addptr(rsp, 64);
5176     } else {
5177       movflt(dst, nds);
5178       vxorps(dst, dst, src, Assembler::AVX_128bit);
5179     }
5180   } else {
5181     vxorps(dst, nds, src, Assembler::AVX_128bit);
5182   }
5183 }
5184 
5185 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5186   int nds_enc = nds->encoding();
5187   int dst_enc = dst->encoding();
5188   bool dst_upper_bank = (dst_enc > 15);
5189   bool nds_upper_bank = (nds_enc > 15);
5190   if (VM_Version::supports_avx512novl() &&
5191       (nds_upper_bank || dst_upper_bank)) {
5192     if (dst_upper_bank) {
5193       subptr(rsp, 64);
5194       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5195       movdbl(xmm0, nds);
5196       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5197       movdbl(dst, xmm0);
5198       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5199       addptr(rsp, 64);
5200     } else {
5201       movdbl(dst, nds);
5202       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5203     }
5204   } else {
5205     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5206   }
5207 }
5208 
5209 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5210   if (reachable(src)) {
5211     vxorpd(dst, nds, as_Address(src), vector_len);
5212   } else {
5213     lea(rscratch1, src);
5214     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5215   }
5216 }
5217 
5218 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5219   if (reachable(src)) {
5220     vxorps(dst, nds, as_Address(src), vector_len);
5221   } else {
5222     lea(rscratch1, src);
5223     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5224   }
5225 }
5226 
5227 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5228   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5229   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5230   // The inverted mask is sign-extended
5231   andptr(possibly_jweak, inverted_jweak_mask);
5232 }
5233 
5234 void MacroAssembler::resolve_jobject(Register value,
5235                                      Register thread,
5236                                      Register tmp) {
5237   assert_different_registers(value, thread, tmp);
5238   Label done, not_weak;
5239   testptr(value, value);
5240   jcc(Assembler::zero, done);                // Use NULL as-is.
5241   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5242   jcc(Assembler::zero, not_weak);
5243   // Resolve jweak.
5244   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
5245                  value, Address(value, -JNIHandles::weak_tag_value), tmp, thread);
5246   verify_oop(value);
5247   jmp(done);
5248   bind(not_weak);
5249   // Resolve (untagged) jobject.
5250   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, 0), tmp, thread);
5251   verify_oop(value);
5252   bind(done);
5253 }
5254 
5255 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5256   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5257 }
5258 
5259 // Force generation of a 4 byte immediate value even if it fits into 8bit
5260 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5261   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5262 }
5263 
5264 void MacroAssembler::subptr(Register dst, Register src) {
5265   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5266 }
5267 
5268 // C++ bool manipulation
5269 void MacroAssembler::testbool(Register dst) {
5270   if(sizeof(bool) == 1)
5271     testb(dst, 0xff);
5272   else if(sizeof(bool) == 2) {
5273     // testw implementation needed for two byte bools
5274     ShouldNotReachHere();
5275   } else if(sizeof(bool) == 4)
5276     testl(dst, dst);
5277   else
5278     // unsupported
5279     ShouldNotReachHere();
5280 }
5281 
5282 void MacroAssembler::testptr(Register dst, Register src) {
5283   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5284 }
5285 
5286 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5287 void MacroAssembler::tlab_allocate(Register thread, Register obj,
5288                                    Register var_size_in_bytes,
5289                                    int con_size_in_bytes,
5290                                    Register t1,
5291                                    Register t2,
5292                                    Label& slow_case) {
5293   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5294   bs->tlab_allocate(this, thread, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
5295 }
5296 
5297 // Defines obj, preserves var_size_in_bytes
5298 void MacroAssembler::eden_allocate(Register thread, Register obj,
5299                                    Register var_size_in_bytes,
5300                                    int con_size_in_bytes,
5301                                    Register t1,
5302                                    Label& slow_case) {
5303   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5304   bs->eden_allocate(this, thread, obj, var_size_in_bytes, con_size_in_bytes, t1, slow_case);
5305 }
5306 
5307 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5308 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5309   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5310   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5311   Label done;
5312 
5313   testptr(length_in_bytes, length_in_bytes);
5314   jcc(Assembler::zero, done);
5315 
5316   // initialize topmost word, divide index by 2, check if odd and test if zero
5317   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5318 #ifdef ASSERT
5319   {
5320     Label L;
5321     testptr(length_in_bytes, BytesPerWord - 1);
5322     jcc(Assembler::zero, L);
5323     stop("length must be a multiple of BytesPerWord");
5324     bind(L);
5325   }
5326 #endif
5327   Register index = length_in_bytes;
5328   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5329   if (UseIncDec) {
5330     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5331   } else {
5332     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5333     shrptr(index, 1);
5334   }
5335 #ifndef _LP64
5336   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5337   {
5338     Label even;
5339     // note: if index was a multiple of 8, then it cannot
5340     //       be 0 now otherwise it must have been 0 before
5341     //       => if it is even, we don't need to check for 0 again
5342     jcc(Assembler::carryClear, even);
5343     // clear topmost word (no jump would be needed if conditional assignment worked here)
5344     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5345     // index could be 0 now, must check again
5346     jcc(Assembler::zero, done);
5347     bind(even);
5348   }
5349 #endif // !_LP64
5350   // initialize remaining object fields: index is a multiple of 2 now
5351   {
5352     Label loop;
5353     bind(loop);
5354     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5355     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5356     decrement(index);
5357     jcc(Assembler::notZero, loop);
5358   }
5359 
5360   bind(done);
5361 }
5362 
5363 // Look up the method for a megamorphic invokeinterface call.
5364 // The target method is determined by <intf_klass, itable_index>.
5365 // The receiver klass is in recv_klass.
5366 // On success, the result will be in method_result, and execution falls through.
5367 // On failure, execution transfers to the given label.
5368 void MacroAssembler::lookup_interface_method(Register recv_klass,
5369                                              Register intf_klass,
5370                                              RegisterOrConstant itable_index,
5371                                              Register method_result,
5372                                              Register scan_temp,
5373                                              Label& L_no_such_interface,
5374                                              bool return_method) {
5375   assert_different_registers(recv_klass, intf_klass, scan_temp);
5376   assert_different_registers(method_result, intf_klass, scan_temp);
5377   assert(recv_klass != method_result || !return_method,
5378          "recv_klass can be destroyed when method isn't needed");
5379 
5380   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5381          "caller must use same register for non-constant itable index as for method");
5382 
5383   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5384   int vtable_base = in_bytes(Klass::vtable_start_offset());
5385   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5386   int scan_step   = itableOffsetEntry::size() * wordSize;
5387   int vte_size    = vtableEntry::size_in_bytes();
5388   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5389   assert(vte_size == wordSize, "else adjust times_vte_scale");
5390 
5391   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5392 
5393   // %%% Could store the aligned, prescaled offset in the klassoop.
5394   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5395 
5396   if (return_method) {
5397     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5398     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5399     lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5400   }
5401 
5402   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5403   //   if (scan->interface() == intf) {
5404   //     result = (klass + scan->offset() + itable_index);
5405   //   }
5406   // }
5407   Label search, found_method;
5408 
5409   for (int peel = 1; peel >= 0; peel--) {
5410     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5411     cmpptr(intf_klass, method_result);
5412 
5413     if (peel) {
5414       jccb(Assembler::equal, found_method);
5415     } else {
5416       jccb(Assembler::notEqual, search);
5417       // (invert the test to fall through to found_method...)
5418     }
5419 
5420     if (!peel)  break;
5421 
5422     bind(search);
5423 
5424     // Check that the previous entry is non-null.  A null entry means that
5425     // the receiver class doesn't implement the interface, and wasn't the
5426     // same as when the caller was compiled.
5427     testptr(method_result, method_result);
5428     jcc(Assembler::zero, L_no_such_interface);
5429     addptr(scan_temp, scan_step);
5430   }
5431 
5432   bind(found_method);
5433 
5434   if (return_method) {
5435     // Got a hit.
5436     movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5437     movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5438   }
5439 }
5440 
5441 
5442 // virtual method calling
5443 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5444                                            RegisterOrConstant vtable_index,
5445                                            Register method_result) {
5446   const int base = in_bytes(Klass::vtable_start_offset());
5447   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5448   Address vtable_entry_addr(recv_klass,
5449                             vtable_index, Address::times_ptr,
5450                             base + vtableEntry::method_offset_in_bytes());
5451   movptr(method_result, vtable_entry_addr);
5452 }
5453 
5454 
5455 void MacroAssembler::check_klass_subtype(Register sub_klass,
5456                            Register super_klass,
5457                            Register temp_reg,
5458                            Label& L_success) {
5459   Label L_failure;
5460   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5461   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5462   bind(L_failure);
5463 }
5464 
5465 
5466 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5467                                                    Register super_klass,
5468                                                    Register temp_reg,
5469                                                    Label* L_success,
5470                                                    Label* L_failure,
5471                                                    Label* L_slow_path,
5472                                         RegisterOrConstant super_check_offset) {
5473   assert_different_registers(sub_klass, super_klass, temp_reg);
5474   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5475   if (super_check_offset.is_register()) {
5476     assert_different_registers(sub_klass, super_klass,
5477                                super_check_offset.as_register());
5478   } else if (must_load_sco) {
5479     assert(temp_reg != noreg, "supply either a temp or a register offset");
5480   }
5481 
5482   Label L_fallthrough;
5483   int label_nulls = 0;
5484   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5485   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5486   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5487   assert(label_nulls <= 1, "at most one NULL in the batch");
5488 
5489   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5490   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5491   Address super_check_offset_addr(super_klass, sco_offset);
5492 
5493   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5494   // range of a jccb.  If this routine grows larger, reconsider at
5495   // least some of these.
5496 #define local_jcc(assembler_cond, label)                                \
5497   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5498   else                             jcc( assembler_cond, label) /*omit semi*/
5499 
5500   // Hacked jmp, which may only be used just before L_fallthrough.
5501 #define final_jmp(label)                                                \
5502   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5503   else                            jmp(label)                /*omit semi*/
5504 
5505   // If the pointers are equal, we are done (e.g., String[] elements).
5506   // This self-check enables sharing of secondary supertype arrays among
5507   // non-primary types such as array-of-interface.  Otherwise, each such
5508   // type would need its own customized SSA.
5509   // We move this check to the front of the fast path because many
5510   // type checks are in fact trivially successful in this manner,
5511   // so we get a nicely predicted branch right at the start of the check.
5512   cmpptr(sub_klass, super_klass);
5513   local_jcc(Assembler::equal, *L_success);
5514 
5515   // Check the supertype display:
5516   if (must_load_sco) {
5517     // Positive movl does right thing on LP64.
5518     movl(temp_reg, super_check_offset_addr);
5519     super_check_offset = RegisterOrConstant(temp_reg);
5520   }
5521   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5522   cmpptr(super_klass, super_check_addr); // load displayed supertype
5523 
5524   // This check has worked decisively for primary supers.
5525   // Secondary supers are sought in the super_cache ('super_cache_addr').
5526   // (Secondary supers are interfaces and very deeply nested subtypes.)
5527   // This works in the same check above because of a tricky aliasing
5528   // between the super_cache and the primary super display elements.
5529   // (The 'super_check_addr' can address either, as the case requires.)
5530   // Note that the cache is updated below if it does not help us find
5531   // what we need immediately.
5532   // So if it was a primary super, we can just fail immediately.
5533   // Otherwise, it's the slow path for us (no success at this point).
5534 
5535   if (super_check_offset.is_register()) {
5536     local_jcc(Assembler::equal, *L_success);
5537     cmpl(super_check_offset.as_register(), sc_offset);
5538     if (L_failure == &L_fallthrough) {
5539       local_jcc(Assembler::equal, *L_slow_path);
5540     } else {
5541       local_jcc(Assembler::notEqual, *L_failure);
5542       final_jmp(*L_slow_path);
5543     }
5544   } else if (super_check_offset.as_constant() == sc_offset) {
5545     // Need a slow path; fast failure is impossible.
5546     if (L_slow_path == &L_fallthrough) {
5547       local_jcc(Assembler::equal, *L_success);
5548     } else {
5549       local_jcc(Assembler::notEqual, *L_slow_path);
5550       final_jmp(*L_success);
5551     }
5552   } else {
5553     // No slow path; it's a fast decision.
5554     if (L_failure == &L_fallthrough) {
5555       local_jcc(Assembler::equal, *L_success);
5556     } else {
5557       local_jcc(Assembler::notEqual, *L_failure);
5558       final_jmp(*L_success);
5559     }
5560   }
5561 
5562   bind(L_fallthrough);
5563 
5564 #undef local_jcc
5565 #undef final_jmp
5566 }
5567 
5568 
5569 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5570                                                    Register super_klass,
5571                                                    Register temp_reg,
5572                                                    Register temp2_reg,
5573                                                    Label* L_success,
5574                                                    Label* L_failure,
5575                                                    bool set_cond_codes) {
5576   assert_different_registers(sub_klass, super_klass, temp_reg);
5577   if (temp2_reg != noreg)
5578     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5579 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5580 
5581   Label L_fallthrough;
5582   int label_nulls = 0;
5583   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5584   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5585   assert(label_nulls <= 1, "at most one NULL in the batch");
5586 
5587   // a couple of useful fields in sub_klass:
5588   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5589   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5590   Address secondary_supers_addr(sub_klass, ss_offset);
5591   Address super_cache_addr(     sub_klass, sc_offset);
5592 
5593   // Do a linear scan of the secondary super-klass chain.
5594   // This code is rarely used, so simplicity is a virtue here.
5595   // The repne_scan instruction uses fixed registers, which we must spill.
5596   // Don't worry too much about pre-existing connections with the input regs.
5597 
5598   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5599   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5600 
5601   // Get super_klass value into rax (even if it was in rdi or rcx).
5602   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5603   if (super_klass != rax || UseCompressedOops) {
5604     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5605     mov(rax, super_klass);
5606   }
5607   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5608   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5609 
5610 #ifndef PRODUCT
5611   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5612   ExternalAddress pst_counter_addr((address) pst_counter);
5613   NOT_LP64(  incrementl(pst_counter_addr) );
5614   LP64_ONLY( lea(rcx, pst_counter_addr) );
5615   LP64_ONLY( incrementl(Address(rcx, 0)) );
5616 #endif //PRODUCT
5617 
5618   // We will consult the secondary-super array.
5619   movptr(rdi, secondary_supers_addr);
5620   // Load the array length.  (Positive movl does right thing on LP64.)
5621   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
5622   // Skip to start of data.
5623   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
5624 
5625   // Scan RCX words at [RDI] for an occurrence of RAX.
5626   // Set NZ/Z based on last compare.
5627   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
5628   // not change flags (only scas instruction which is repeated sets flags).
5629   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
5630 
5631     testptr(rax,rax); // Set Z = 0
5632     repne_scan();
5633 
5634   // Unspill the temp. registers:
5635   if (pushed_rdi)  pop(rdi);
5636   if (pushed_rcx)  pop(rcx);
5637   if (pushed_rax)  pop(rax);
5638 
5639   if (set_cond_codes) {
5640     // Special hack for the AD files:  rdi is guaranteed non-zero.
5641     assert(!pushed_rdi, "rdi must be left non-NULL");
5642     // Also, the condition codes are properly set Z/NZ on succeed/failure.
5643   }
5644 
5645   if (L_failure == &L_fallthrough)
5646         jccb(Assembler::notEqual, *L_failure);
5647   else  jcc(Assembler::notEqual, *L_failure);
5648 
5649   // Success.  Cache the super we found and proceed in triumph.
5650   movptr(super_cache_addr, super_klass);
5651 
5652   if (L_success != &L_fallthrough) {
5653     jmp(*L_success);
5654   }
5655 
5656 #undef IS_A_TEMP
5657 
5658   bind(L_fallthrough);
5659 }
5660 
5661 
5662 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
5663   if (VM_Version::supports_cmov()) {
5664     cmovl(cc, dst, src);
5665   } else {
5666     Label L;
5667     jccb(negate_condition(cc), L);
5668     movl(dst, src);
5669     bind(L);
5670   }
5671 }
5672 
5673 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
5674   if (VM_Version::supports_cmov()) {
5675     cmovl(cc, dst, src);
5676   } else {
5677     Label L;
5678     jccb(negate_condition(cc), L);
5679     movl(dst, src);
5680     bind(L);
5681   }
5682 }
5683 
5684 void MacroAssembler::verify_oop(Register reg, const char* s) {
5685   if (!VerifyOops) return;
5686 
5687   // Pass register number to verify_oop_subroutine
5688   const char* b = NULL;
5689   {
5690     ResourceMark rm;
5691     stringStream ss;
5692     ss.print("verify_oop: %s: %s", reg->name(), s);
5693     b = code_string(ss.as_string());
5694   }
5695   BLOCK_COMMENT("verify_oop {");
5696 #ifdef _LP64
5697   push(rscratch1);                    // save r10, trashed by movptr()
5698 #endif
5699   push(rax);                          // save rax,
5700   push(reg);                          // pass register argument
5701   ExternalAddress buffer((address) b);
5702   // avoid using pushptr, as it modifies scratch registers
5703   // and our contract is not to modify anything
5704   movptr(rax, buffer.addr());
5705   push(rax);
5706   // call indirectly to solve generation ordering problem
5707   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5708   call(rax);
5709   // Caller pops the arguments (oop, message) and restores rax, r10
5710   BLOCK_COMMENT("} verify_oop");
5711 }
5712 
5713 
5714 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
5715                                                       Register tmp,
5716                                                       int offset) {
5717   intptr_t value = *delayed_value_addr;
5718   if (value != 0)
5719     return RegisterOrConstant(value + offset);
5720 
5721   // load indirectly to solve generation ordering problem
5722   movptr(tmp, ExternalAddress((address) delayed_value_addr));
5723 
5724 #ifdef ASSERT
5725   { Label L;
5726     testptr(tmp, tmp);
5727     if (WizardMode) {
5728       const char* buf = NULL;
5729       {
5730         ResourceMark rm;
5731         stringStream ss;
5732         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
5733         buf = code_string(ss.as_string());
5734       }
5735       jcc(Assembler::notZero, L);
5736       STOP(buf);
5737     } else {
5738       jccb(Assembler::notZero, L);
5739       hlt();
5740     }
5741     bind(L);
5742   }
5743 #endif
5744 
5745   if (offset != 0)
5746     addptr(tmp, offset);
5747 
5748   return RegisterOrConstant(tmp);
5749 }
5750 
5751 
5752 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
5753                                          int extra_slot_offset) {
5754   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
5755   int stackElementSize = Interpreter::stackElementSize;
5756   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
5757 #ifdef ASSERT
5758   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
5759   assert(offset1 - offset == stackElementSize, "correct arithmetic");
5760 #endif
5761   Register             scale_reg    = noreg;
5762   Address::ScaleFactor scale_factor = Address::no_scale;
5763   if (arg_slot.is_constant()) {
5764     offset += arg_slot.as_constant() * stackElementSize;
5765   } else {
5766     scale_reg    = arg_slot.as_register();
5767     scale_factor = Address::times(stackElementSize);
5768   }
5769   offset += wordSize;           // return PC is on stack
5770   return Address(rsp, scale_reg, scale_factor, offset);
5771 }
5772 
5773 
5774 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
5775   if (!VerifyOops) return;
5776 
5777   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
5778   // Pass register number to verify_oop_subroutine
5779   const char* b = NULL;
5780   {
5781     ResourceMark rm;
5782     stringStream ss;
5783     ss.print("verify_oop_addr: %s", s);
5784     b = code_string(ss.as_string());
5785   }
5786 #ifdef _LP64
5787   push(rscratch1);                    // save r10, trashed by movptr()
5788 #endif
5789   push(rax);                          // save rax,
5790   // addr may contain rsp so we will have to adjust it based on the push
5791   // we just did (and on 64 bit we do two pushes)
5792   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
5793   // stores rax into addr which is backwards of what was intended.
5794   if (addr.uses(rsp)) {
5795     lea(rax, addr);
5796     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
5797   } else {
5798     pushptr(addr);
5799   }
5800 
5801   ExternalAddress buffer((address) b);
5802   // pass msg argument
5803   // avoid using pushptr, as it modifies scratch registers
5804   // and our contract is not to modify anything
5805   movptr(rax, buffer.addr());
5806   push(rax);
5807 
5808   // call indirectly to solve generation ordering problem
5809   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5810   call(rax);
5811   // Caller pops the arguments (addr, message) and restores rax, r10.
5812 }
5813 
5814 void MacroAssembler::verify_tlab() {
5815 #ifdef ASSERT
5816   if (UseTLAB && VerifyOops) {
5817     Label next, ok;
5818     Register t1 = rsi;
5819     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
5820 
5821     push(t1);
5822     NOT_LP64(push(thread_reg));
5823     NOT_LP64(get_thread(thread_reg));
5824 
5825     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5826     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5827     jcc(Assembler::aboveEqual, next);
5828     STOP("assert(top >= start)");
5829     should_not_reach_here();
5830 
5831     bind(next);
5832     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5833     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5834     jcc(Assembler::aboveEqual, ok);
5835     STOP("assert(top <= end)");
5836     should_not_reach_here();
5837 
5838     bind(ok);
5839     NOT_LP64(pop(thread_reg));
5840     pop(t1);
5841   }
5842 #endif
5843 }
5844 
5845 class ControlWord {
5846  public:
5847   int32_t _value;
5848 
5849   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
5850   int  precision_control() const       { return  (_value >>  8) & 3      ; }
5851   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5852   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5853   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5854   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5855   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5856   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5857 
5858   void print() const {
5859     // rounding control
5860     const char* rc;
5861     switch (rounding_control()) {
5862       case 0: rc = "round near"; break;
5863       case 1: rc = "round down"; break;
5864       case 2: rc = "round up  "; break;
5865       case 3: rc = "chop      "; break;
5866     };
5867     // precision control
5868     const char* pc;
5869     switch (precision_control()) {
5870       case 0: pc = "24 bits "; break;
5871       case 1: pc = "reserved"; break;
5872       case 2: pc = "53 bits "; break;
5873       case 3: pc = "64 bits "; break;
5874     };
5875     // flags
5876     char f[9];
5877     f[0] = ' ';
5878     f[1] = ' ';
5879     f[2] = (precision   ()) ? 'P' : 'p';
5880     f[3] = (underflow   ()) ? 'U' : 'u';
5881     f[4] = (overflow    ()) ? 'O' : 'o';
5882     f[5] = (zero_divide ()) ? 'Z' : 'z';
5883     f[6] = (denormalized()) ? 'D' : 'd';
5884     f[7] = (invalid     ()) ? 'I' : 'i';
5885     f[8] = '\x0';
5886     // output
5887     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
5888   }
5889 
5890 };
5891 
5892 class StatusWord {
5893  public:
5894   int32_t _value;
5895 
5896   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
5897   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
5898   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
5899   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
5900   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
5901   int  top() const                     { return  (_value >> 11) & 7      ; }
5902   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
5903   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
5904   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5905   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5906   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5907   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5908   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5909   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5910 
5911   void print() const {
5912     // condition codes
5913     char c[5];
5914     c[0] = (C3()) ? '3' : '-';
5915     c[1] = (C2()) ? '2' : '-';
5916     c[2] = (C1()) ? '1' : '-';
5917     c[3] = (C0()) ? '0' : '-';
5918     c[4] = '\x0';
5919     // flags
5920     char f[9];
5921     f[0] = (error_status()) ? 'E' : '-';
5922     f[1] = (stack_fault ()) ? 'S' : '-';
5923     f[2] = (precision   ()) ? 'P' : '-';
5924     f[3] = (underflow   ()) ? 'U' : '-';
5925     f[4] = (overflow    ()) ? 'O' : '-';
5926     f[5] = (zero_divide ()) ? 'Z' : '-';
5927     f[6] = (denormalized()) ? 'D' : '-';
5928     f[7] = (invalid     ()) ? 'I' : '-';
5929     f[8] = '\x0';
5930     // output
5931     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
5932   }
5933 
5934 };
5935 
5936 class TagWord {
5937  public:
5938   int32_t _value;
5939 
5940   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
5941 
5942   void print() const {
5943     printf("%04x", _value & 0xFFFF);
5944   }
5945 
5946 };
5947 
5948 class FPU_Register {
5949  public:
5950   int32_t _m0;
5951   int32_t _m1;
5952   int16_t _ex;
5953 
5954   bool is_indefinite() const           {
5955     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
5956   }
5957 
5958   void print() const {
5959     char  sign = (_ex < 0) ? '-' : '+';
5960     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
5961     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
5962   };
5963 
5964 };
5965 
5966 class FPU_State {
5967  public:
5968   enum {
5969     register_size       = 10,
5970     number_of_registers =  8,
5971     register_mask       =  7
5972   };
5973 
5974   ControlWord  _control_word;
5975   StatusWord   _status_word;
5976   TagWord      _tag_word;
5977   int32_t      _error_offset;
5978   int32_t      _error_selector;
5979   int32_t      _data_offset;
5980   int32_t      _data_selector;
5981   int8_t       _register[register_size * number_of_registers];
5982 
5983   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
5984   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
5985 
5986   const char* tag_as_string(int tag) const {
5987     switch (tag) {
5988       case 0: return "valid";
5989       case 1: return "zero";
5990       case 2: return "special";
5991       case 3: return "empty";
5992     }
5993     ShouldNotReachHere();
5994     return NULL;
5995   }
5996 
5997   void print() const {
5998     // print computation registers
5999     { int t = _status_word.top();
6000       for (int i = 0; i < number_of_registers; i++) {
6001         int j = (i - t) & register_mask;
6002         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6003         st(j)->print();
6004         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6005       }
6006     }
6007     printf("\n");
6008     // print control registers
6009     printf("ctrl = "); _control_word.print(); printf("\n");
6010     printf("stat = "); _status_word .print(); printf("\n");
6011     printf("tags = "); _tag_word    .print(); printf("\n");
6012   }
6013 
6014 };
6015 
6016 class Flag_Register {
6017  public:
6018   int32_t _value;
6019 
6020   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6021   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6022   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6023   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6024   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6025   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6026   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6027 
6028   void print() const {
6029     // flags
6030     char f[8];
6031     f[0] = (overflow       ()) ? 'O' : '-';
6032     f[1] = (direction      ()) ? 'D' : '-';
6033     f[2] = (sign           ()) ? 'S' : '-';
6034     f[3] = (zero           ()) ? 'Z' : '-';
6035     f[4] = (auxiliary_carry()) ? 'A' : '-';
6036     f[5] = (parity         ()) ? 'P' : '-';
6037     f[6] = (carry          ()) ? 'C' : '-';
6038     f[7] = '\x0';
6039     // output
6040     printf("%08x  flags = %s", _value, f);
6041   }
6042 
6043 };
6044 
6045 class IU_Register {
6046  public:
6047   int32_t _value;
6048 
6049   void print() const {
6050     printf("%08x  %11d", _value, _value);
6051   }
6052 
6053 };
6054 
6055 class IU_State {
6056  public:
6057   Flag_Register _eflags;
6058   IU_Register   _rdi;
6059   IU_Register   _rsi;
6060   IU_Register   _rbp;
6061   IU_Register   _rsp;
6062   IU_Register   _rbx;
6063   IU_Register   _rdx;
6064   IU_Register   _rcx;
6065   IU_Register   _rax;
6066 
6067   void print() const {
6068     // computation registers
6069     printf("rax,  = "); _rax.print(); printf("\n");
6070     printf("rbx,  = "); _rbx.print(); printf("\n");
6071     printf("rcx  = "); _rcx.print(); printf("\n");
6072     printf("rdx  = "); _rdx.print(); printf("\n");
6073     printf("rdi  = "); _rdi.print(); printf("\n");
6074     printf("rsi  = "); _rsi.print(); printf("\n");
6075     printf("rbp,  = "); _rbp.print(); printf("\n");
6076     printf("rsp  = "); _rsp.print(); printf("\n");
6077     printf("\n");
6078     // control registers
6079     printf("flgs = "); _eflags.print(); printf("\n");
6080   }
6081 };
6082 
6083 
6084 class CPU_State {
6085  public:
6086   FPU_State _fpu_state;
6087   IU_State  _iu_state;
6088 
6089   void print() const {
6090     printf("--------------------------------------------------\n");
6091     _iu_state .print();
6092     printf("\n");
6093     _fpu_state.print();
6094     printf("--------------------------------------------------\n");
6095   }
6096 
6097 };
6098 
6099 
6100 static void _print_CPU_state(CPU_State* state) {
6101   state->print();
6102 };
6103 
6104 
6105 void MacroAssembler::print_CPU_state() {
6106   push_CPU_state();
6107   push(rsp);                // pass CPU state
6108   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6109   addptr(rsp, wordSize);       // discard argument
6110   pop_CPU_state();
6111 }
6112 
6113 
6114 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6115   static int counter = 0;
6116   FPU_State* fs = &state->_fpu_state;
6117   counter++;
6118   // For leaf calls, only verify that the top few elements remain empty.
6119   // We only need 1 empty at the top for C2 code.
6120   if( stack_depth < 0 ) {
6121     if( fs->tag_for_st(7) != 3 ) {
6122       printf("FPR7 not empty\n");
6123       state->print();
6124       assert(false, "error");
6125       return false;
6126     }
6127     return true;                // All other stack states do not matter
6128   }
6129 
6130   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6131          "bad FPU control word");
6132 
6133   // compute stack depth
6134   int i = 0;
6135   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6136   int d = i;
6137   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6138   // verify findings
6139   if (i != FPU_State::number_of_registers) {
6140     // stack not contiguous
6141     printf("%s: stack not contiguous at ST%d\n", s, i);
6142     state->print();
6143     assert(false, "error");
6144     return false;
6145   }
6146   // check if computed stack depth corresponds to expected stack depth
6147   if (stack_depth < 0) {
6148     // expected stack depth is -stack_depth or less
6149     if (d > -stack_depth) {
6150       // too many elements on the stack
6151       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6152       state->print();
6153       assert(false, "error");
6154       return false;
6155     }
6156   } else {
6157     // expected stack depth is stack_depth
6158     if (d != stack_depth) {
6159       // wrong stack depth
6160       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6161       state->print();
6162       assert(false, "error");
6163       return false;
6164     }
6165   }
6166   // everything is cool
6167   return true;
6168 }
6169 
6170 
6171 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6172   if (!VerifyFPU) return;
6173   push_CPU_state();
6174   push(rsp);                // pass CPU state
6175   ExternalAddress msg((address) s);
6176   // pass message string s
6177   pushptr(msg.addr());
6178   push(stack_depth);        // pass stack depth
6179   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6180   addptr(rsp, 3 * wordSize);   // discard arguments
6181   // check for error
6182   { Label L;
6183     testl(rax, rax);
6184     jcc(Assembler::notZero, L);
6185     int3();                  // break if error condition
6186     bind(L);
6187   }
6188   pop_CPU_state();
6189 }
6190 
6191 void MacroAssembler::restore_cpu_control_state_after_jni() {
6192   // Either restore the MXCSR register after returning from the JNI Call
6193   // or verify that it wasn't changed (with -Xcheck:jni flag).
6194   if (VM_Version::supports_sse()) {
6195     if (RestoreMXCSROnJNICalls) {
6196       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6197     } else if (CheckJNICalls) {
6198       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6199     }
6200   }
6201   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6202   vzeroupper();
6203   // Reset k1 to 0xffff.
6204   if (VM_Version::supports_evex()) {
6205     push(rcx);
6206     movl(rcx, 0xffff);
6207     kmovwl(k1, rcx);
6208     pop(rcx);
6209   }
6210 
6211 #ifndef _LP64
6212   // Either restore the x87 floating pointer control word after returning
6213   // from the JNI call or verify that it wasn't changed.
6214   if (CheckJNICalls) {
6215     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6216   }
6217 #endif // _LP64
6218 }
6219 
6220 // ((OopHandle)result).resolve();
6221 void MacroAssembler::resolve_oop_handle(Register result, Register tmp) {
6222   assert_different_registers(result, tmp);
6223 
6224   // Only 64 bit platforms support GCs that require a tmp register
6225   // Only IN_HEAP loads require a thread_tmp register
6226   // OopHandle::resolve is an indirection like jobject.
6227   access_load_at(T_OBJECT, IN_NATIVE,
6228                  result, Address(result, 0), tmp, /*tmp_thread*/noreg);
6229 }
6230 
6231 void MacroAssembler::load_mirror(Register mirror, Register method, Register tmp) {
6232   // get mirror
6233   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6234   movptr(mirror, Address(method, Method::const_offset()));
6235   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6236   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6237   movptr(mirror, Address(mirror, mirror_offset));
6238   resolve_oop_handle(mirror, tmp);
6239 }
6240 
6241 void MacroAssembler::load_klass(Register dst, Register src) {
6242 #ifdef _LP64
6243   if (UseCompressedClassPointers) {
6244     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6245     decode_klass_not_null(dst);
6246   } else
6247 #endif
6248     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6249 }
6250 
6251 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6252   load_klass(dst, src);
6253   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6254 }
6255 
6256 void MacroAssembler::store_klass(Register dst, Register src) {
6257 #ifdef _LP64
6258   if (UseCompressedClassPointers) {
6259     encode_klass_not_null(src);
6260     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6261   } else
6262 #endif
6263     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6264 }
6265 
6266 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators, Register dst, Address src,
6267                                     Register tmp1, Register thread_tmp) {
6268   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6269   decorators = AccessInternal::decorator_fixup(decorators);
6270   bool as_raw = (decorators & AS_RAW) != 0;
6271   if (as_raw) {
6272     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
6273   } else {
6274     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
6275   }
6276 }
6277 
6278 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators, Address dst, Register src,
6279                                      Register tmp1, Register tmp2) {
6280   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6281   decorators = AccessInternal::decorator_fixup(decorators);
6282   bool as_raw = (decorators & AS_RAW) != 0;
6283   if (as_raw) {
6284     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, tmp2);
6285   } else {
6286     bs->store_at(this, decorators, type, dst, src, tmp1, tmp2);
6287   }
6288 }
6289 
6290 void MacroAssembler::resolve_for_read(DecoratorSet decorators, Register obj) {
6291   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6292   return bs->resolve_for_read(this, decorators, obj);
6293 }
6294 
6295 void MacroAssembler::resolve_for_write(DecoratorSet decorators, Register obj) {
6296   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6297   return bs->resolve_for_write(this, decorators, obj);
6298 }
6299 
6300 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
6301                                    Register thread_tmp, DecoratorSet decorators) {
6302   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
6303 }
6304 
6305 // Doesn't do verfication, generates fixed size code
6306 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
6307                                             Register thread_tmp, DecoratorSet decorators) {
6308   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
6309 }
6310 
6311 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
6312                                     Register tmp2, DecoratorSet decorators) {
6313   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
6314 }
6315 
6316 // Used for storing NULLs.
6317 void MacroAssembler::store_heap_oop_null(Address dst) {
6318   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg);
6319 }
6320 
6321 #ifdef _LP64
6322 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6323   if (UseCompressedClassPointers) {
6324     // Store to klass gap in destination
6325     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6326   }
6327 }
6328 
6329 #ifdef ASSERT
6330 void MacroAssembler::verify_heapbase(const char* msg) {
6331   assert (UseCompressedOops, "should be compressed");
6332   assert (Universe::heap() != NULL, "java heap should be initialized");
6333   if (CheckCompressedOops) {
6334     Label ok;
6335     push(rscratch1); // cmpptr trashes rscratch1
6336     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6337     jcc(Assembler::equal, ok);
6338     STOP(msg);
6339     bind(ok);
6340     pop(rscratch1);
6341   }
6342 }
6343 #endif
6344 
6345 // Algorithm must match oop.inline.hpp encode_heap_oop.
6346 void MacroAssembler::encode_heap_oop(Register r) {
6347 #ifdef ASSERT
6348   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6349 #endif
6350   verify_oop(r, "broken oop in encode_heap_oop");
6351   if (Universe::narrow_oop_base() == NULL) {
6352     if (Universe::narrow_oop_shift() != 0) {
6353       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6354       shrq(r, LogMinObjAlignmentInBytes);
6355     }
6356     return;
6357   }
6358   testq(r, r);
6359   cmovq(Assembler::equal, r, r12_heapbase);
6360   subq(r, r12_heapbase);
6361   shrq(r, LogMinObjAlignmentInBytes);
6362 }
6363 
6364 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6365 #ifdef ASSERT
6366   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6367   if (CheckCompressedOops) {
6368     Label ok;
6369     testq(r, r);
6370     jcc(Assembler::notEqual, ok);
6371     STOP("null oop passed to encode_heap_oop_not_null");
6372     bind(ok);
6373   }
6374 #endif
6375   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6376   if (Universe::narrow_oop_base() != NULL) {
6377     subq(r, r12_heapbase);
6378   }
6379   if (Universe::narrow_oop_shift() != 0) {
6380     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6381     shrq(r, LogMinObjAlignmentInBytes);
6382   }
6383 }
6384 
6385 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6386 #ifdef ASSERT
6387   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6388   if (CheckCompressedOops) {
6389     Label ok;
6390     testq(src, src);
6391     jcc(Assembler::notEqual, ok);
6392     STOP("null oop passed to encode_heap_oop_not_null2");
6393     bind(ok);
6394   }
6395 #endif
6396   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6397   if (dst != src) {
6398     movq(dst, src);
6399   }
6400   if (Universe::narrow_oop_base() != NULL) {
6401     subq(dst, r12_heapbase);
6402   }
6403   if (Universe::narrow_oop_shift() != 0) {
6404     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6405     shrq(dst, LogMinObjAlignmentInBytes);
6406   }
6407 }
6408 
6409 void  MacroAssembler::decode_heap_oop(Register r) {
6410 #ifdef ASSERT
6411   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6412 #endif
6413   if (Universe::narrow_oop_base() == NULL) {
6414     if (Universe::narrow_oop_shift() != 0) {
6415       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6416       shlq(r, LogMinObjAlignmentInBytes);
6417     }
6418   } else {
6419     Label done;
6420     shlq(r, LogMinObjAlignmentInBytes);
6421     jccb(Assembler::equal, done);
6422     addq(r, r12_heapbase);
6423     bind(done);
6424   }
6425   verify_oop(r, "broken oop in decode_heap_oop");
6426 }
6427 
6428 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6429   // Note: it will change flags
6430   assert (UseCompressedOops, "should only be used for compressed headers");
6431   assert (Universe::heap() != NULL, "java heap should be initialized");
6432   // Cannot assert, unverified entry point counts instructions (see .ad file)
6433   // vtableStubs also counts instructions in pd_code_size_limit.
6434   // Also do not verify_oop as this is called by verify_oop.
6435   if (Universe::narrow_oop_shift() != 0) {
6436     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6437     shlq(r, LogMinObjAlignmentInBytes);
6438     if (Universe::narrow_oop_base() != NULL) {
6439       addq(r, r12_heapbase);
6440     }
6441   } else {
6442     assert (Universe::narrow_oop_base() == NULL, "sanity");
6443   }
6444 }
6445 
6446 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6447   // Note: it will change flags
6448   assert (UseCompressedOops, "should only be used for compressed headers");
6449   assert (Universe::heap() != NULL, "java heap should be initialized");
6450   // Cannot assert, unverified entry point counts instructions (see .ad file)
6451   // vtableStubs also counts instructions in pd_code_size_limit.
6452   // Also do not verify_oop as this is called by verify_oop.
6453   if (Universe::narrow_oop_shift() != 0) {
6454     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6455     if (LogMinObjAlignmentInBytes == Address::times_8) {
6456       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6457     } else {
6458       if (dst != src) {
6459         movq(dst, src);
6460       }
6461       shlq(dst, LogMinObjAlignmentInBytes);
6462       if (Universe::narrow_oop_base() != NULL) {
6463         addq(dst, r12_heapbase);
6464       }
6465     }
6466   } else {
6467     assert (Universe::narrow_oop_base() == NULL, "sanity");
6468     if (dst != src) {
6469       movq(dst, src);
6470     }
6471   }
6472 }
6473 
6474 void MacroAssembler::encode_klass_not_null(Register r) {
6475   if (Universe::narrow_klass_base() != NULL) {
6476     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6477     assert(r != r12_heapbase, "Encoding a klass in r12");
6478     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6479     subq(r, r12_heapbase);
6480   }
6481   if (Universe::narrow_klass_shift() != 0) {
6482     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6483     shrq(r, LogKlassAlignmentInBytes);
6484   }
6485   if (Universe::narrow_klass_base() != NULL) {
6486     reinit_heapbase();
6487   }
6488 }
6489 
6490 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6491   if (dst == src) {
6492     encode_klass_not_null(src);
6493   } else {
6494     if (Universe::narrow_klass_base() != NULL) {
6495       mov64(dst, (int64_t)Universe::narrow_klass_base());
6496       negq(dst);
6497       addq(dst, src);
6498     } else {
6499       movptr(dst, src);
6500     }
6501     if (Universe::narrow_klass_shift() != 0) {
6502       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6503       shrq(dst, LogKlassAlignmentInBytes);
6504     }
6505   }
6506 }
6507 
6508 // Function instr_size_for_decode_klass_not_null() counts the instructions
6509 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6510 // when (Universe::heap() != NULL).  Hence, if the instructions they
6511 // generate change, then this method needs to be updated.
6512 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6513   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6514   if (Universe::narrow_klass_base() != NULL) {
6515     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6516     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6517   } else {
6518     // longest load decode klass function, mov64, leaq
6519     return 16;
6520   }
6521 }
6522 
6523 // !!! If the instructions that get generated here change then function
6524 // instr_size_for_decode_klass_not_null() needs to get updated.
6525 void  MacroAssembler::decode_klass_not_null(Register r) {
6526   // Note: it will change flags
6527   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6528   assert(r != r12_heapbase, "Decoding a klass in r12");
6529   // Cannot assert, unverified entry point counts instructions (see .ad file)
6530   // vtableStubs also counts instructions in pd_code_size_limit.
6531   // Also do not verify_oop as this is called by verify_oop.
6532   if (Universe::narrow_klass_shift() != 0) {
6533     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6534     shlq(r, LogKlassAlignmentInBytes);
6535   }
6536   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6537   if (Universe::narrow_klass_base() != NULL) {
6538     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6539     addq(r, r12_heapbase);
6540     reinit_heapbase();
6541   }
6542 }
6543 
6544 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6545   // Note: it will change flags
6546   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6547   if (dst == src) {
6548     decode_klass_not_null(dst);
6549   } else {
6550     // Cannot assert, unverified entry point counts instructions (see .ad file)
6551     // vtableStubs also counts instructions in pd_code_size_limit.
6552     // Also do not verify_oop as this is called by verify_oop.
6553     mov64(dst, (int64_t)Universe::narrow_klass_base());
6554     if (Universe::narrow_klass_shift() != 0) {
6555       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6556       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6557       leaq(dst, Address(dst, src, Address::times_8, 0));
6558     } else {
6559       addq(dst, src);
6560     }
6561   }
6562 }
6563 
6564 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6565   assert (UseCompressedOops, "should only be used for compressed headers");
6566   assert (Universe::heap() != NULL, "java heap should be initialized");
6567   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6568   int oop_index = oop_recorder()->find_index(obj);
6569   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6570   mov_narrow_oop(dst, oop_index, rspec);
6571 }
6572 
6573 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6574   assert (UseCompressedOops, "should only be used for compressed headers");
6575   assert (Universe::heap() != NULL, "java heap should be initialized");
6576   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6577   int oop_index = oop_recorder()->find_index(obj);
6578   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6579   mov_narrow_oop(dst, oop_index, rspec);
6580 }
6581 
6582 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6583   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6584   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6585   int klass_index = oop_recorder()->find_index(k);
6586   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6587   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6588 }
6589 
6590 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
6591   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6592   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6593   int klass_index = oop_recorder()->find_index(k);
6594   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6595   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6596 }
6597 
6598 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
6599   assert (UseCompressedOops, "should only be used for compressed headers");
6600   assert (Universe::heap() != NULL, "java heap should be initialized");
6601   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6602   int oop_index = oop_recorder()->find_index(obj);
6603   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6604   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6605 }
6606 
6607 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
6608   assert (UseCompressedOops, "should only be used for compressed headers");
6609   assert (Universe::heap() != NULL, "java heap should be initialized");
6610   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6611   int oop_index = oop_recorder()->find_index(obj);
6612   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6613   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6614 }
6615 
6616 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
6617   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6618   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6619   int klass_index = oop_recorder()->find_index(k);
6620   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6621   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6622 }
6623 
6624 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
6625   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6626   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6627   int klass_index = oop_recorder()->find_index(k);
6628   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6629   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6630 }
6631 
6632 void MacroAssembler::reinit_heapbase() {
6633   if (UseCompressedOops || UseCompressedClassPointers) {
6634     if (Universe::heap() != NULL) {
6635       if (Universe::narrow_oop_base() == NULL) {
6636         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
6637       } else {
6638         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
6639       }
6640     } else {
6641       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6642     }
6643   }
6644 }
6645 
6646 #endif // _LP64
6647 
6648 // C2 compiled method's prolog code.
6649 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
6650 
6651   // WARNING: Initial instruction MUST be 5 bytes or longer so that
6652   // NativeJump::patch_verified_entry will be able to patch out the entry
6653   // code safely. The push to verify stack depth is ok at 5 bytes,
6654   // the frame allocation can be either 3 or 6 bytes. So if we don't do
6655   // stack bang then we must use the 6 byte frame allocation even if
6656   // we have no frame. :-(
6657   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
6658 
6659   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6660   // Remove word for return addr
6661   framesize -= wordSize;
6662   stack_bang_size -= wordSize;
6663 
6664   // Calls to C2R adapters often do not accept exceptional returns.
6665   // We require that their callers must bang for them.  But be careful, because
6666   // some VM calls (such as call site linkage) can use several kilobytes of
6667   // stack.  But the stack safety zone should account for that.
6668   // See bugs 4446381, 4468289, 4497237.
6669   if (stack_bang_size > 0) {
6670     generate_stack_overflow_check(stack_bang_size);
6671 
6672     // We always push rbp, so that on return to interpreter rbp, will be
6673     // restored correctly and we can correct the stack.
6674     push(rbp);
6675     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6676     if (PreserveFramePointer) {
6677       mov(rbp, rsp);
6678     }
6679     // Remove word for ebp
6680     framesize -= wordSize;
6681 
6682     // Create frame
6683     if (framesize) {
6684       subptr(rsp, framesize);
6685     }
6686   } else {
6687     // Create frame (force generation of a 4 byte immediate value)
6688     subptr_imm32(rsp, framesize);
6689 
6690     // Save RBP register now.
6691     framesize -= wordSize;
6692     movptr(Address(rsp, framesize), rbp);
6693     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6694     if (PreserveFramePointer) {
6695       movptr(rbp, rsp);
6696       if (framesize > 0) {
6697         addptr(rbp, framesize);
6698       }
6699     }
6700   }
6701 
6702   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
6703     framesize -= wordSize;
6704     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
6705   }
6706 
6707 #ifndef _LP64
6708   // If method sets FPU control word do it now
6709   if (fp_mode_24b) {
6710     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
6711   }
6712   if (UseSSE >= 2 && VerifyFPU) {
6713     verify_FPU(0, "FPU stack must be clean on entry");
6714   }
6715 #endif
6716 
6717 #ifdef ASSERT
6718   if (VerifyStackAtCalls) {
6719     Label L;
6720     push(rax);
6721     mov(rax, rsp);
6722     andptr(rax, StackAlignmentInBytes-1);
6723     cmpptr(rax, StackAlignmentInBytes-wordSize);
6724     pop(rax);
6725     jcc(Assembler::equal, L);
6726     STOP("Stack is not properly aligned!");
6727     bind(L);
6728   }
6729 #endif
6730 
6731 }
6732 
6733 // clear memory of size 'cnt' qwords, starting at 'base' using XMM/YMM registers
6734 void MacroAssembler::xmm_clear_mem(Register base, Register cnt, XMMRegister xtmp) {
6735   // cnt - number of qwords (8-byte words).
6736   // base - start address, qword aligned.
6737   Label L_zero_64_bytes, L_loop, L_sloop, L_tail, L_end;
6738   if (UseAVX >= 2) {
6739     vpxor(xtmp, xtmp, xtmp, AVX_256bit);
6740   } else {
6741     pxor(xtmp, xtmp);
6742   }
6743   jmp(L_zero_64_bytes);
6744 
6745   BIND(L_loop);
6746   if (UseAVX >= 2) {
6747     vmovdqu(Address(base,  0), xtmp);
6748     vmovdqu(Address(base, 32), xtmp);
6749   } else {
6750     movdqu(Address(base,  0), xtmp);
6751     movdqu(Address(base, 16), xtmp);
6752     movdqu(Address(base, 32), xtmp);
6753     movdqu(Address(base, 48), xtmp);
6754   }
6755   addptr(base, 64);
6756 
6757   BIND(L_zero_64_bytes);
6758   subptr(cnt, 8);
6759   jccb(Assembler::greaterEqual, L_loop);
6760   addptr(cnt, 4);
6761   jccb(Assembler::less, L_tail);
6762   // Copy trailing 32 bytes
6763   if (UseAVX >= 2) {
6764     vmovdqu(Address(base, 0), xtmp);
6765   } else {
6766     movdqu(Address(base,  0), xtmp);
6767     movdqu(Address(base, 16), xtmp);
6768   }
6769   addptr(base, 32);
6770   subptr(cnt, 4);
6771 
6772   BIND(L_tail);
6773   addptr(cnt, 4);
6774   jccb(Assembler::lessEqual, L_end);
6775   decrement(cnt);
6776 
6777   BIND(L_sloop);
6778   movq(Address(base, 0), xtmp);
6779   addptr(base, 8);
6780   decrement(cnt);
6781   jccb(Assembler::greaterEqual, L_sloop);
6782   BIND(L_end);
6783 }
6784 
6785 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, XMMRegister xtmp, bool is_large) {
6786   // cnt - number of qwords (8-byte words).
6787   // base - start address, qword aligned.
6788   // is_large - if optimizers know cnt is larger than InitArrayShortSize
6789   assert(base==rdi, "base register must be edi for rep stos");
6790   assert(tmp==rax,   "tmp register must be eax for rep stos");
6791   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
6792   assert(InitArrayShortSize % BytesPerLong == 0,
6793     "InitArrayShortSize should be the multiple of BytesPerLong");
6794 
6795   Label DONE;
6796 
6797   if (!is_large || !UseXMMForObjInit) {
6798     xorptr(tmp, tmp);
6799   }
6800 
6801   if (!is_large) {
6802     Label LOOP, LONG;
6803     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
6804     jccb(Assembler::greater, LONG);
6805 
6806     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6807 
6808     decrement(cnt);
6809     jccb(Assembler::negative, DONE); // Zero length
6810 
6811     // Use individual pointer-sized stores for small counts:
6812     BIND(LOOP);
6813     movptr(Address(base, cnt, Address::times_ptr), tmp);
6814     decrement(cnt);
6815     jccb(Assembler::greaterEqual, LOOP);
6816     jmpb(DONE);
6817 
6818     BIND(LONG);
6819   }
6820 
6821   // Use longer rep-prefixed ops for non-small counts:
6822   if (UseFastStosb) {
6823     shlptr(cnt, 3); // convert to number of bytes
6824     rep_stosb();
6825   } else if (UseXMMForObjInit) {
6826     movptr(tmp, base);
6827     xmm_clear_mem(tmp, cnt, xtmp);
6828   } else {
6829     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6830     rep_stos();
6831   }
6832 
6833   BIND(DONE);
6834 }
6835 
6836 #ifdef COMPILER2
6837 
6838 // IndexOf for constant substrings with size >= 8 chars
6839 // which don't need to be loaded through stack.
6840 void MacroAssembler::string_indexofC8(Register str1, Register str2,
6841                                       Register cnt1, Register cnt2,
6842                                       int int_cnt2,  Register result,
6843                                       XMMRegister vec, Register tmp,
6844                                       int ae) {
6845   ShortBranchVerifier sbv(this);
6846   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6847   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6848 
6849   // This method uses the pcmpestri instruction with bound registers
6850   //   inputs:
6851   //     xmm - substring
6852   //     rax - substring length (elements count)
6853   //     mem - scanned string
6854   //     rdx - string length (elements count)
6855   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6856   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6857   //   outputs:
6858   //     rcx - matched index in string
6859   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6860   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
6861   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
6862   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
6863   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
6864 
6865   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
6866         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
6867         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
6868 
6869   // Note, inline_string_indexOf() generates checks:
6870   // if (substr.count > string.count) return -1;
6871   // if (substr.count == 0) return 0;
6872   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
6873 
6874   // Load substring.
6875   if (ae == StrIntrinsicNode::UL) {
6876     pmovzxbw(vec, Address(str2, 0));
6877   } else {
6878     movdqu(vec, Address(str2, 0));
6879   }
6880   movl(cnt2, int_cnt2);
6881   movptr(result, str1); // string addr
6882 
6883   if (int_cnt2 > stride) {
6884     jmpb(SCAN_TO_SUBSTR);
6885 
6886     // Reload substr for rescan, this code
6887     // is executed only for large substrings (> 8 chars)
6888     bind(RELOAD_SUBSTR);
6889     if (ae == StrIntrinsicNode::UL) {
6890       pmovzxbw(vec, Address(str2, 0));
6891     } else {
6892       movdqu(vec, Address(str2, 0));
6893     }
6894     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
6895 
6896     bind(RELOAD_STR);
6897     // We came here after the beginning of the substring was
6898     // matched but the rest of it was not so we need to search
6899     // again. Start from the next element after the previous match.
6900 
6901     // cnt2 is number of substring reminding elements and
6902     // cnt1 is number of string reminding elements when cmp failed.
6903     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
6904     subl(cnt1, cnt2);
6905     addl(cnt1, int_cnt2);
6906     movl(cnt2, int_cnt2); // Now restore cnt2
6907 
6908     decrementl(cnt1);     // Shift to next element
6909     cmpl(cnt1, cnt2);
6910     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6911 
6912     addptr(result, (1<<scale1));
6913 
6914   } // (int_cnt2 > 8)
6915 
6916   // Scan string for start of substr in 16-byte vectors
6917   bind(SCAN_TO_SUBSTR);
6918   pcmpestri(vec, Address(result, 0), mode);
6919   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6920   subl(cnt1, stride);
6921   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6922   cmpl(cnt1, cnt2);
6923   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6924   addptr(result, 16);
6925   jmpb(SCAN_TO_SUBSTR);
6926 
6927   // Found a potential substr
6928   bind(FOUND_CANDIDATE);
6929   // Matched whole vector if first element matched (tmp(rcx) == 0).
6930   if (int_cnt2 == stride) {
6931     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
6932   } else { // int_cnt2 > 8
6933     jccb(Assembler::overflow, FOUND_SUBSTR);
6934   }
6935   // After pcmpestri tmp(rcx) contains matched element index
6936   // Compute start addr of substr
6937   lea(result, Address(result, tmp, scale1));
6938 
6939   // Make sure string is still long enough
6940   subl(cnt1, tmp);
6941   cmpl(cnt1, cnt2);
6942   if (int_cnt2 == stride) {
6943     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6944   } else { // int_cnt2 > 8
6945     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
6946   }
6947   // Left less then substring.
6948 
6949   bind(RET_NOT_FOUND);
6950   movl(result, -1);
6951   jmp(EXIT);
6952 
6953   if (int_cnt2 > stride) {
6954     // This code is optimized for the case when whole substring
6955     // is matched if its head is matched.
6956     bind(MATCH_SUBSTR_HEAD);
6957     pcmpestri(vec, Address(result, 0), mode);
6958     // Reload only string if does not match
6959     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
6960 
6961     Label CONT_SCAN_SUBSTR;
6962     // Compare the rest of substring (> 8 chars).
6963     bind(FOUND_SUBSTR);
6964     // First 8 chars are already matched.
6965     negptr(cnt2);
6966     addptr(cnt2, stride);
6967 
6968     bind(SCAN_SUBSTR);
6969     subl(cnt1, stride);
6970     cmpl(cnt2, -stride); // Do not read beyond substring
6971     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
6972     // Back-up strings to avoid reading beyond substring:
6973     // cnt1 = cnt1 - cnt2 + 8
6974     addl(cnt1, cnt2); // cnt2 is negative
6975     addl(cnt1, stride);
6976     movl(cnt2, stride); negptr(cnt2);
6977     bind(CONT_SCAN_SUBSTR);
6978     if (int_cnt2 < (int)G) {
6979       int tail_off1 = int_cnt2<<scale1;
6980       int tail_off2 = int_cnt2<<scale2;
6981       if (ae == StrIntrinsicNode::UL) {
6982         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
6983       } else {
6984         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
6985       }
6986       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
6987     } else {
6988       // calculate index in register to avoid integer overflow (int_cnt2*2)
6989       movl(tmp, int_cnt2);
6990       addptr(tmp, cnt2);
6991       if (ae == StrIntrinsicNode::UL) {
6992         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
6993       } else {
6994         movdqu(vec, Address(str2, tmp, scale2, 0));
6995       }
6996       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
6997     }
6998     // Need to reload strings pointers if not matched whole vector
6999     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7000     addptr(cnt2, stride);
7001     jcc(Assembler::negative, SCAN_SUBSTR);
7002     // Fall through if found full substring
7003 
7004   } // (int_cnt2 > 8)
7005 
7006   bind(RET_FOUND);
7007   // Found result if we matched full small substring.
7008   // Compute substr offset
7009   subptr(result, str1);
7010   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7011     shrl(result, 1); // index
7012   }
7013   bind(EXIT);
7014 
7015 } // string_indexofC8
7016 
7017 // Small strings are loaded through stack if they cross page boundary.
7018 void MacroAssembler::string_indexof(Register str1, Register str2,
7019                                     Register cnt1, Register cnt2,
7020                                     int int_cnt2,  Register result,
7021                                     XMMRegister vec, Register tmp,
7022                                     int ae) {
7023   ShortBranchVerifier sbv(this);
7024   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7025   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7026 
7027   //
7028   // int_cnt2 is length of small (< 8 chars) constant substring
7029   // or (-1) for non constant substring in which case its length
7030   // is in cnt2 register.
7031   //
7032   // Note, inline_string_indexOf() generates checks:
7033   // if (substr.count > string.count) return -1;
7034   // if (substr.count == 0) return 0;
7035   //
7036   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7037   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7038   // This method uses the pcmpestri instruction with bound registers
7039   //   inputs:
7040   //     xmm - substring
7041   //     rax - substring length (elements count)
7042   //     mem - scanned string
7043   //     rdx - string length (elements count)
7044   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7045   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7046   //   outputs:
7047   //     rcx - matched index in string
7048   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7049   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7050   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7051   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7052 
7053   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7054         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7055         FOUND_CANDIDATE;
7056 
7057   { //========================================================
7058     // We don't know where these strings are located
7059     // and we can't read beyond them. Load them through stack.
7060     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7061 
7062     movptr(tmp, rsp); // save old SP
7063 
7064     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7065       if (int_cnt2 == (1>>scale2)) { // One byte
7066         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7067         load_unsigned_byte(result, Address(str2, 0));
7068         movdl(vec, result); // move 32 bits
7069       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7070         // Not enough header space in 32-bit VM: 12+3 = 15.
7071         movl(result, Address(str2, -1));
7072         shrl(result, 8);
7073         movdl(vec, result); // move 32 bits
7074       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7075         load_unsigned_short(result, Address(str2, 0));
7076         movdl(vec, result); // move 32 bits
7077       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7078         movdl(vec, Address(str2, 0)); // move 32 bits
7079       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7080         movq(vec, Address(str2, 0));  // move 64 bits
7081       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7082         // Array header size is 12 bytes in 32-bit VM
7083         // + 6 bytes for 3 chars == 18 bytes,
7084         // enough space to load vec and shift.
7085         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7086         if (ae == StrIntrinsicNode::UL) {
7087           int tail_off = int_cnt2-8;
7088           pmovzxbw(vec, Address(str2, tail_off));
7089           psrldq(vec, -2*tail_off);
7090         }
7091         else {
7092           int tail_off = int_cnt2*(1<<scale2);
7093           movdqu(vec, Address(str2, tail_off-16));
7094           psrldq(vec, 16-tail_off);
7095         }
7096       }
7097     } else { // not constant substring
7098       cmpl(cnt2, stride);
7099       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7100 
7101       // We can read beyond string if srt+16 does not cross page boundary
7102       // since heaps are aligned and mapped by pages.
7103       assert(os::vm_page_size() < (int)G, "default page should be small");
7104       movl(result, str2); // We need only low 32 bits
7105       andl(result, (os::vm_page_size()-1));
7106       cmpl(result, (os::vm_page_size()-16));
7107       jccb(Assembler::belowEqual, CHECK_STR);
7108 
7109       // Move small strings to stack to allow load 16 bytes into vec.
7110       subptr(rsp, 16);
7111       int stk_offset = wordSize-(1<<scale2);
7112       push(cnt2);
7113 
7114       bind(COPY_SUBSTR);
7115       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7116         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7117         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7118       } else if (ae == StrIntrinsicNode::UU) {
7119         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7120         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7121       }
7122       decrement(cnt2);
7123       jccb(Assembler::notZero, COPY_SUBSTR);
7124 
7125       pop(cnt2);
7126       movptr(str2, rsp);  // New substring address
7127     } // non constant
7128 
7129     bind(CHECK_STR);
7130     cmpl(cnt1, stride);
7131     jccb(Assembler::aboveEqual, BIG_STRINGS);
7132 
7133     // Check cross page boundary.
7134     movl(result, str1); // We need only low 32 bits
7135     andl(result, (os::vm_page_size()-1));
7136     cmpl(result, (os::vm_page_size()-16));
7137     jccb(Assembler::belowEqual, BIG_STRINGS);
7138 
7139     subptr(rsp, 16);
7140     int stk_offset = -(1<<scale1);
7141     if (int_cnt2 < 0) { // not constant
7142       push(cnt2);
7143       stk_offset += wordSize;
7144     }
7145     movl(cnt2, cnt1);
7146 
7147     bind(COPY_STR);
7148     if (ae == StrIntrinsicNode::LL) {
7149       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7150       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7151     } else {
7152       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7153       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7154     }
7155     decrement(cnt2);
7156     jccb(Assembler::notZero, COPY_STR);
7157 
7158     if (int_cnt2 < 0) { // not constant
7159       pop(cnt2);
7160     }
7161     movptr(str1, rsp);  // New string address
7162 
7163     bind(BIG_STRINGS);
7164     // Load substring.
7165     if (int_cnt2 < 0) { // -1
7166       if (ae == StrIntrinsicNode::UL) {
7167         pmovzxbw(vec, Address(str2, 0));
7168       } else {
7169         movdqu(vec, Address(str2, 0));
7170       }
7171       push(cnt2);       // substr count
7172       push(str2);       // substr addr
7173       push(str1);       // string addr
7174     } else {
7175       // Small (< 8 chars) constant substrings are loaded already.
7176       movl(cnt2, int_cnt2);
7177     }
7178     push(tmp);  // original SP
7179 
7180   } // Finished loading
7181 
7182   //========================================================
7183   // Start search
7184   //
7185 
7186   movptr(result, str1); // string addr
7187 
7188   if (int_cnt2  < 0) {  // Only for non constant substring
7189     jmpb(SCAN_TO_SUBSTR);
7190 
7191     // SP saved at sp+0
7192     // String saved at sp+1*wordSize
7193     // Substr saved at sp+2*wordSize
7194     // Substr count saved at sp+3*wordSize
7195 
7196     // Reload substr for rescan, this code
7197     // is executed only for large substrings (> 8 chars)
7198     bind(RELOAD_SUBSTR);
7199     movptr(str2, Address(rsp, 2*wordSize));
7200     movl(cnt2, Address(rsp, 3*wordSize));
7201     if (ae == StrIntrinsicNode::UL) {
7202       pmovzxbw(vec, Address(str2, 0));
7203     } else {
7204       movdqu(vec, Address(str2, 0));
7205     }
7206     // We came here after the beginning of the substring was
7207     // matched but the rest of it was not so we need to search
7208     // again. Start from the next element after the previous match.
7209     subptr(str1, result); // Restore counter
7210     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7211       shrl(str1, 1);
7212     }
7213     addl(cnt1, str1);
7214     decrementl(cnt1);   // Shift to next element
7215     cmpl(cnt1, cnt2);
7216     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7217 
7218     addptr(result, (1<<scale1));
7219   } // non constant
7220 
7221   // Scan string for start of substr in 16-byte vectors
7222   bind(SCAN_TO_SUBSTR);
7223   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7224   pcmpestri(vec, Address(result, 0), mode);
7225   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7226   subl(cnt1, stride);
7227   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7228   cmpl(cnt1, cnt2);
7229   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7230   addptr(result, 16);
7231 
7232   bind(ADJUST_STR);
7233   cmpl(cnt1, stride); // Do not read beyond string
7234   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7235   // Back-up string to avoid reading beyond string.
7236   lea(result, Address(result, cnt1, scale1, -16));
7237   movl(cnt1, stride);
7238   jmpb(SCAN_TO_SUBSTR);
7239 
7240   // Found a potential substr
7241   bind(FOUND_CANDIDATE);
7242   // After pcmpestri tmp(rcx) contains matched element index
7243 
7244   // Make sure string is still long enough
7245   subl(cnt1, tmp);
7246   cmpl(cnt1, cnt2);
7247   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7248   // Left less then substring.
7249 
7250   bind(RET_NOT_FOUND);
7251   movl(result, -1);
7252   jmpb(CLEANUP);
7253 
7254   bind(FOUND_SUBSTR);
7255   // Compute start addr of substr
7256   lea(result, Address(result, tmp, scale1));
7257   if (int_cnt2 > 0) { // Constant substring
7258     // Repeat search for small substring (< 8 chars)
7259     // from new point without reloading substring.
7260     // Have to check that we don't read beyond string.
7261     cmpl(tmp, stride-int_cnt2);
7262     jccb(Assembler::greater, ADJUST_STR);
7263     // Fall through if matched whole substring.
7264   } else { // non constant
7265     assert(int_cnt2 == -1, "should be != 0");
7266 
7267     addl(tmp, cnt2);
7268     // Found result if we matched whole substring.
7269     cmpl(tmp, stride);
7270     jccb(Assembler::lessEqual, RET_FOUND);
7271 
7272     // Repeat search for small substring (<= 8 chars)
7273     // from new point 'str1' without reloading substring.
7274     cmpl(cnt2, stride);
7275     // Have to check that we don't read beyond string.
7276     jccb(Assembler::lessEqual, ADJUST_STR);
7277 
7278     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7279     // Compare the rest of substring (> 8 chars).
7280     movptr(str1, result);
7281 
7282     cmpl(tmp, cnt2);
7283     // First 8 chars are already matched.
7284     jccb(Assembler::equal, CHECK_NEXT);
7285 
7286     bind(SCAN_SUBSTR);
7287     pcmpestri(vec, Address(str1, 0), mode);
7288     // Need to reload strings pointers if not matched whole vector
7289     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7290 
7291     bind(CHECK_NEXT);
7292     subl(cnt2, stride);
7293     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7294     addptr(str1, 16);
7295     if (ae == StrIntrinsicNode::UL) {
7296       addptr(str2, 8);
7297     } else {
7298       addptr(str2, 16);
7299     }
7300     subl(cnt1, stride);
7301     cmpl(cnt2, stride); // Do not read beyond substring
7302     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7303     // Back-up strings to avoid reading beyond substring.
7304 
7305     if (ae == StrIntrinsicNode::UL) {
7306       lea(str2, Address(str2, cnt2, scale2, -8));
7307       lea(str1, Address(str1, cnt2, scale1, -16));
7308     } else {
7309       lea(str2, Address(str2, cnt2, scale2, -16));
7310       lea(str1, Address(str1, cnt2, scale1, -16));
7311     }
7312     subl(cnt1, cnt2);
7313     movl(cnt2, stride);
7314     addl(cnt1, stride);
7315     bind(CONT_SCAN_SUBSTR);
7316     if (ae == StrIntrinsicNode::UL) {
7317       pmovzxbw(vec, Address(str2, 0));
7318     } else {
7319       movdqu(vec, Address(str2, 0));
7320     }
7321     jmp(SCAN_SUBSTR);
7322 
7323     bind(RET_FOUND_LONG);
7324     movptr(str1, Address(rsp, wordSize));
7325   } // non constant
7326 
7327   bind(RET_FOUND);
7328   // Compute substr offset
7329   subptr(result, str1);
7330   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7331     shrl(result, 1); // index
7332   }
7333   bind(CLEANUP);
7334   pop(rsp); // restore SP
7335 
7336 } // string_indexof
7337 
7338 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7339                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7340   ShortBranchVerifier sbv(this);
7341   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7342 
7343   int stride = 8;
7344 
7345   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7346         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7347         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7348         FOUND_SEQ_CHAR, DONE_LABEL;
7349 
7350   movptr(result, str1);
7351   if (UseAVX >= 2) {
7352     cmpl(cnt1, stride);
7353     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7354     cmpl(cnt1, 2*stride);
7355     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7356     movdl(vec1, ch);
7357     vpbroadcastw(vec1, vec1);
7358     vpxor(vec2, vec2);
7359     movl(tmp, cnt1);
7360     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7361     andl(cnt1,0x0000000F);  //tail count (in chars)
7362 
7363     bind(SCAN_TO_16_CHAR_LOOP);
7364     vmovdqu(vec3, Address(result, 0));
7365     vpcmpeqw(vec3, vec3, vec1, 1);
7366     vptest(vec2, vec3);
7367     jcc(Assembler::carryClear, FOUND_CHAR);
7368     addptr(result, 32);
7369     subl(tmp, 2*stride);
7370     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7371     jmp(SCAN_TO_8_CHAR);
7372     bind(SCAN_TO_8_CHAR_INIT);
7373     movdl(vec1, ch);
7374     pshuflw(vec1, vec1, 0x00);
7375     pshufd(vec1, vec1, 0);
7376     pxor(vec2, vec2);
7377   }
7378   bind(SCAN_TO_8_CHAR);
7379   cmpl(cnt1, stride);
7380   if (UseAVX >= 2) {
7381     jcc(Assembler::less, SCAN_TO_CHAR);
7382   } else {
7383     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7384     movdl(vec1, ch);
7385     pshuflw(vec1, vec1, 0x00);
7386     pshufd(vec1, vec1, 0);
7387     pxor(vec2, vec2);
7388   }
7389   movl(tmp, cnt1);
7390   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7391   andl(cnt1,0x00000007);  //tail count (in chars)
7392 
7393   bind(SCAN_TO_8_CHAR_LOOP);
7394   movdqu(vec3, Address(result, 0));
7395   pcmpeqw(vec3, vec1);
7396   ptest(vec2, vec3);
7397   jcc(Assembler::carryClear, FOUND_CHAR);
7398   addptr(result, 16);
7399   subl(tmp, stride);
7400   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7401   bind(SCAN_TO_CHAR);
7402   testl(cnt1, cnt1);
7403   jcc(Assembler::zero, RET_NOT_FOUND);
7404   bind(SCAN_TO_CHAR_LOOP);
7405   load_unsigned_short(tmp, Address(result, 0));
7406   cmpl(ch, tmp);
7407   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7408   addptr(result, 2);
7409   subl(cnt1, 1);
7410   jccb(Assembler::zero, RET_NOT_FOUND);
7411   jmp(SCAN_TO_CHAR_LOOP);
7412 
7413   bind(RET_NOT_FOUND);
7414   movl(result, -1);
7415   jmpb(DONE_LABEL);
7416 
7417   bind(FOUND_CHAR);
7418   if (UseAVX >= 2) {
7419     vpmovmskb(tmp, vec3);
7420   } else {
7421     pmovmskb(tmp, vec3);
7422   }
7423   bsfl(ch, tmp);
7424   addl(result, ch);
7425 
7426   bind(FOUND_SEQ_CHAR);
7427   subptr(result, str1);
7428   shrl(result, 1);
7429 
7430   bind(DONE_LABEL);
7431 } // string_indexof_char
7432 
7433 // helper function for string_compare
7434 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7435                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7436                                         Address::ScaleFactor scale2, Register index, int ae) {
7437   if (ae == StrIntrinsicNode::LL) {
7438     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7439     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7440   } else if (ae == StrIntrinsicNode::UU) {
7441     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7442     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7443   } else {
7444     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7445     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7446   }
7447 }
7448 
7449 // Compare strings, used for char[] and byte[].
7450 void MacroAssembler::string_compare(Register str1, Register str2,
7451                                     Register cnt1, Register cnt2, Register result,
7452                                     XMMRegister vec1, int ae) {
7453   ShortBranchVerifier sbv(this);
7454   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7455   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7456   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7457   int stride2x2 = 0x40;
7458   Address::ScaleFactor scale = Address::no_scale;
7459   Address::ScaleFactor scale1 = Address::no_scale;
7460   Address::ScaleFactor scale2 = Address::no_scale;
7461 
7462   if (ae != StrIntrinsicNode::LL) {
7463     stride2x2 = 0x20;
7464   }
7465 
7466   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7467     shrl(cnt2, 1);
7468   }
7469   // Compute the minimum of the string lengths and the
7470   // difference of the string lengths (stack).
7471   // Do the conditional move stuff
7472   movl(result, cnt1);
7473   subl(cnt1, cnt2);
7474   push(cnt1);
7475   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7476 
7477   // Is the minimum length zero?
7478   testl(cnt2, cnt2);
7479   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7480   if (ae == StrIntrinsicNode::LL) {
7481     // Load first bytes
7482     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7483     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7484   } else if (ae == StrIntrinsicNode::UU) {
7485     // Load first characters
7486     load_unsigned_short(result, Address(str1, 0));
7487     load_unsigned_short(cnt1, Address(str2, 0));
7488   } else {
7489     load_unsigned_byte(result, Address(str1, 0));
7490     load_unsigned_short(cnt1, Address(str2, 0));
7491   }
7492   subl(result, cnt1);
7493   jcc(Assembler::notZero,  POP_LABEL);
7494 
7495   if (ae == StrIntrinsicNode::UU) {
7496     // Divide length by 2 to get number of chars
7497     shrl(cnt2, 1);
7498   }
7499   cmpl(cnt2, 1);
7500   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7501 
7502   // Check if the strings start at the same location and setup scale and stride
7503   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7504     cmpptr(str1, str2);
7505     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7506     if (ae == StrIntrinsicNode::LL) {
7507       scale = Address::times_1;
7508       stride = 16;
7509     } else {
7510       scale = Address::times_2;
7511       stride = 8;
7512     }
7513   } else {
7514     scale1 = Address::times_1;
7515     scale2 = Address::times_2;
7516     // scale not used
7517     stride = 8;
7518   }
7519 
7520   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7521     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7522     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7523     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7524     Label COMPARE_TAIL_LONG;
7525     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7526 
7527     int pcmpmask = 0x19;
7528     if (ae == StrIntrinsicNode::LL) {
7529       pcmpmask &= ~0x01;
7530     }
7531 
7532     // Setup to compare 16-chars (32-bytes) vectors,
7533     // start from first character again because it has aligned address.
7534     if (ae == StrIntrinsicNode::LL) {
7535       stride2 = 32;
7536     } else {
7537       stride2 = 16;
7538     }
7539     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7540       adr_stride = stride << scale;
7541     } else {
7542       adr_stride1 = 8;  //stride << scale1;
7543       adr_stride2 = 16; //stride << scale2;
7544     }
7545 
7546     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7547     // rax and rdx are used by pcmpestri as elements counters
7548     movl(result, cnt2);
7549     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7550     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7551 
7552     // fast path : compare first 2 8-char vectors.
7553     bind(COMPARE_16_CHARS);
7554     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7555       movdqu(vec1, Address(str1, 0));
7556     } else {
7557       pmovzxbw(vec1, Address(str1, 0));
7558     }
7559     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7560     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7561 
7562     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7563       movdqu(vec1, Address(str1, adr_stride));
7564       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7565     } else {
7566       pmovzxbw(vec1, Address(str1, adr_stride1));
7567       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7568     }
7569     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7570     addl(cnt1, stride);
7571 
7572     // Compare the characters at index in cnt1
7573     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7574     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7575     subl(result, cnt2);
7576     jmp(POP_LABEL);
7577 
7578     // Setup the registers to start vector comparison loop
7579     bind(COMPARE_WIDE_VECTORS);
7580     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7581       lea(str1, Address(str1, result, scale));
7582       lea(str2, Address(str2, result, scale));
7583     } else {
7584       lea(str1, Address(str1, result, scale1));
7585       lea(str2, Address(str2, result, scale2));
7586     }
7587     subl(result, stride2);
7588     subl(cnt2, stride2);
7589     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7590     negptr(result);
7591 
7592     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7593     bind(COMPARE_WIDE_VECTORS_LOOP);
7594 
7595 #ifdef _LP64
7596     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7597       cmpl(cnt2, stride2x2);
7598       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7599       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7600       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7601 
7602       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7603       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7604         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7605         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7606       } else {
7607         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7608         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7609       }
7610       kortestql(k7, k7);
7611       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7612       addptr(result, stride2x2);  // update since we already compared at this addr
7613       subl(cnt2, stride2x2);      // and sub the size too
7614       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7615 
7616       vpxor(vec1, vec1);
7617       jmpb(COMPARE_WIDE_TAIL);
7618     }//if (VM_Version::supports_avx512vlbw())
7619 #endif // _LP64
7620 
7621 
7622     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7623     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7624       vmovdqu(vec1, Address(str1, result, scale));
7625       vpxor(vec1, Address(str2, result, scale));
7626     } else {
7627       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7628       vpxor(vec1, Address(str2, result, scale2));
7629     }
7630     vptest(vec1, vec1);
7631     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7632     addptr(result, stride2);
7633     subl(cnt2, stride2);
7634     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7635     // clean upper bits of YMM registers
7636     vpxor(vec1, vec1);
7637 
7638     // compare wide vectors tail
7639     bind(COMPARE_WIDE_TAIL);
7640     testptr(result, result);
7641     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7642 
7643     movl(result, stride2);
7644     movl(cnt2, result);
7645     negptr(result);
7646     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7647 
7648     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7649     bind(VECTOR_NOT_EQUAL);
7650     // clean upper bits of YMM registers
7651     vpxor(vec1, vec1);
7652     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7653       lea(str1, Address(str1, result, scale));
7654       lea(str2, Address(str2, result, scale));
7655     } else {
7656       lea(str1, Address(str1, result, scale1));
7657       lea(str2, Address(str2, result, scale2));
7658     }
7659     jmp(COMPARE_16_CHARS);
7660 
7661     // Compare tail chars, length between 1 to 15 chars
7662     bind(COMPARE_TAIL_LONG);
7663     movl(cnt2, result);
7664     cmpl(cnt2, stride);
7665     jcc(Assembler::less, COMPARE_SMALL_STR);
7666 
7667     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7668       movdqu(vec1, Address(str1, 0));
7669     } else {
7670       pmovzxbw(vec1, Address(str1, 0));
7671     }
7672     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7673     jcc(Assembler::below, COMPARE_INDEX_CHAR);
7674     subptr(cnt2, stride);
7675     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7676     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7677       lea(str1, Address(str1, result, scale));
7678       lea(str2, Address(str2, result, scale));
7679     } else {
7680       lea(str1, Address(str1, result, scale1));
7681       lea(str2, Address(str2, result, scale2));
7682     }
7683     negptr(cnt2);
7684     jmpb(WHILE_HEAD_LABEL);
7685 
7686     bind(COMPARE_SMALL_STR);
7687   } else if (UseSSE42Intrinsics) {
7688     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
7689     int pcmpmask = 0x19;
7690     // Setup to compare 8-char (16-byte) vectors,
7691     // start from first character again because it has aligned address.
7692     movl(result, cnt2);
7693     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
7694     if (ae == StrIntrinsicNode::LL) {
7695       pcmpmask &= ~0x01;
7696     }
7697     jcc(Assembler::zero, COMPARE_TAIL);
7698     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7699       lea(str1, Address(str1, result, scale));
7700       lea(str2, Address(str2, result, scale));
7701     } else {
7702       lea(str1, Address(str1, result, scale1));
7703       lea(str2, Address(str2, result, scale2));
7704     }
7705     negptr(result);
7706 
7707     // pcmpestri
7708     //   inputs:
7709     //     vec1- substring
7710     //     rax - negative string length (elements count)
7711     //     mem - scanned string
7712     //     rdx - string length (elements count)
7713     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
7714     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
7715     //   outputs:
7716     //     rcx - first mismatched element index
7717     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7718 
7719     bind(COMPARE_WIDE_VECTORS);
7720     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7721       movdqu(vec1, Address(str1, result, scale));
7722       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7723     } else {
7724       pmovzxbw(vec1, Address(str1, result, scale1));
7725       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7726     }
7727     // After pcmpestri cnt1(rcx) contains mismatched element index
7728 
7729     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
7730     addptr(result, stride);
7731     subptr(cnt2, stride);
7732     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
7733 
7734     // compare wide vectors tail
7735     testptr(result, result);
7736     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7737 
7738     movl(cnt2, stride);
7739     movl(result, stride);
7740     negptr(result);
7741     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7742       movdqu(vec1, Address(str1, result, scale));
7743       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7744     } else {
7745       pmovzxbw(vec1, Address(str1, result, scale1));
7746       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7747     }
7748     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
7749 
7750     // Mismatched characters in the vectors
7751     bind(VECTOR_NOT_EQUAL);
7752     addptr(cnt1, result);
7753     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7754     subl(result, cnt2);
7755     jmpb(POP_LABEL);
7756 
7757     bind(COMPARE_TAIL); // limit is zero
7758     movl(cnt2, result);
7759     // Fallthru to tail compare
7760   }
7761   // Shift str2 and str1 to the end of the arrays, negate min
7762   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7763     lea(str1, Address(str1, cnt2, scale));
7764     lea(str2, Address(str2, cnt2, scale));
7765   } else {
7766     lea(str1, Address(str1, cnt2, scale1));
7767     lea(str2, Address(str2, cnt2, scale2));
7768   }
7769   decrementl(cnt2);  // first character was compared already
7770   negptr(cnt2);
7771 
7772   // Compare the rest of the elements
7773   bind(WHILE_HEAD_LABEL);
7774   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
7775   subl(result, cnt1);
7776   jccb(Assembler::notZero, POP_LABEL);
7777   increment(cnt2);
7778   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
7779 
7780   // Strings are equal up to min length.  Return the length difference.
7781   bind(LENGTH_DIFF_LABEL);
7782   pop(result);
7783   if (ae == StrIntrinsicNode::UU) {
7784     // Divide diff by 2 to get number of chars
7785     sarl(result, 1);
7786   }
7787   jmpb(DONE_LABEL);
7788 
7789 #ifdef _LP64
7790   if (VM_Version::supports_avx512vlbw()) {
7791 
7792     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
7793 
7794     kmovql(cnt1, k7);
7795     notq(cnt1);
7796     bsfq(cnt2, cnt1);
7797     if (ae != StrIntrinsicNode::LL) {
7798       // Divide diff by 2 to get number of chars
7799       sarl(cnt2, 1);
7800     }
7801     addq(result, cnt2);
7802     if (ae == StrIntrinsicNode::LL) {
7803       load_unsigned_byte(cnt1, Address(str2, result));
7804       load_unsigned_byte(result, Address(str1, result));
7805     } else if (ae == StrIntrinsicNode::UU) {
7806       load_unsigned_short(cnt1, Address(str2, result, scale));
7807       load_unsigned_short(result, Address(str1, result, scale));
7808     } else {
7809       load_unsigned_short(cnt1, Address(str2, result, scale2));
7810       load_unsigned_byte(result, Address(str1, result, scale1));
7811     }
7812     subl(result, cnt1);
7813     jmpb(POP_LABEL);
7814   }//if (VM_Version::supports_avx512vlbw())
7815 #endif // _LP64
7816 
7817   // Discard the stored length difference
7818   bind(POP_LABEL);
7819   pop(cnt1);
7820 
7821   // That's it
7822   bind(DONE_LABEL);
7823   if(ae == StrIntrinsicNode::UL) {
7824     negl(result);
7825   }
7826 
7827 }
7828 
7829 // Search for Non-ASCII character (Negative byte value) in a byte array,
7830 // return true if it has any and false otherwise.
7831 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
7832 //   @HotSpotIntrinsicCandidate
7833 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
7834 //     for (int i = off; i < off + len; i++) {
7835 //       if (ba[i] < 0) {
7836 //         return true;
7837 //       }
7838 //     }
7839 //     return false;
7840 //   }
7841 void MacroAssembler::has_negatives(Register ary1, Register len,
7842   Register result, Register tmp1,
7843   XMMRegister vec1, XMMRegister vec2) {
7844   // rsi: byte array
7845   // rcx: len
7846   // rax: result
7847   ShortBranchVerifier sbv(this);
7848   assert_different_registers(ary1, len, result, tmp1);
7849   assert_different_registers(vec1, vec2);
7850   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
7851 
7852   // len == 0
7853   testl(len, len);
7854   jcc(Assembler::zero, FALSE_LABEL);
7855 
7856   if ((UseAVX > 2) && // AVX512
7857     VM_Version::supports_avx512vlbw() &&
7858     VM_Version::supports_bmi2()) {
7859 
7860     set_vector_masking();  // opening of the stub context for programming mask registers
7861 
7862     Label test_64_loop, test_tail;
7863     Register tmp3_aliased = len;
7864 
7865     movl(tmp1, len);
7866     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
7867 
7868     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
7869     andl(len, ~(64 - 1));    // vector count (in chars)
7870     jccb(Assembler::zero, test_tail);
7871 
7872     lea(ary1, Address(ary1, len, Address::times_1));
7873     negptr(len);
7874 
7875     bind(test_64_loop);
7876     // Check whether our 64 elements of size byte contain negatives
7877     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
7878     kortestql(k2, k2);
7879     jcc(Assembler::notZero, TRUE_LABEL);
7880 
7881     addptr(len, 64);
7882     jccb(Assembler::notZero, test_64_loop);
7883 
7884 
7885     bind(test_tail);
7886     // bail out when there is nothing to be done
7887     testl(tmp1, -1);
7888     jcc(Assembler::zero, FALSE_LABEL);
7889 
7890     // Save k1
7891     kmovql(k3, k1);
7892 
7893     // ~(~0 << len) applied up to two times (for 32-bit scenario)
7894 #ifdef _LP64
7895     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
7896     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
7897     notq(tmp3_aliased);
7898     kmovql(k1, tmp3_aliased);
7899 #else
7900     Label k_init;
7901     jmp(k_init);
7902 
7903     // We could not read 64-bits from a general purpose register thus we move
7904     // data required to compose 64 1's to the instruction stream
7905     // We emit 64 byte wide series of elements from 0..63 which later on would
7906     // be used as a compare targets with tail count contained in tmp1 register.
7907     // Result would be a k1 register having tmp1 consecutive number or 1
7908     // counting from least significant bit.
7909     address tmp = pc();
7910     emit_int64(0x0706050403020100);
7911     emit_int64(0x0F0E0D0C0B0A0908);
7912     emit_int64(0x1716151413121110);
7913     emit_int64(0x1F1E1D1C1B1A1918);
7914     emit_int64(0x2726252423222120);
7915     emit_int64(0x2F2E2D2C2B2A2928);
7916     emit_int64(0x3736353433323130);
7917     emit_int64(0x3F3E3D3C3B3A3938);
7918 
7919     bind(k_init);
7920     lea(len, InternalAddress(tmp));
7921     // create mask to test for negative byte inside a vector
7922     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
7923     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
7924 
7925 #endif
7926     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
7927     ktestq(k2, k1);
7928     // Restore k1
7929     kmovql(k1, k3);
7930     jcc(Assembler::notZero, TRUE_LABEL);
7931 
7932     jmp(FALSE_LABEL);
7933 
7934     clear_vector_masking();   // closing of the stub context for programming mask registers
7935   } else {
7936     movl(result, len); // copy
7937 
7938     if (UseAVX == 2 && UseSSE >= 2) {
7939       // With AVX2, use 32-byte vector compare
7940       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7941 
7942       // Compare 32-byte vectors
7943       andl(result, 0x0000001f);  //   tail count (in bytes)
7944       andl(len, 0xffffffe0);   // vector count (in bytes)
7945       jccb(Assembler::zero, COMPARE_TAIL);
7946 
7947       lea(ary1, Address(ary1, len, Address::times_1));
7948       negptr(len);
7949 
7950       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
7951       movdl(vec2, tmp1);
7952       vpbroadcastd(vec2, vec2);
7953 
7954       bind(COMPARE_WIDE_VECTORS);
7955       vmovdqu(vec1, Address(ary1, len, Address::times_1));
7956       vptest(vec1, vec2);
7957       jccb(Assembler::notZero, TRUE_LABEL);
7958       addptr(len, 32);
7959       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7960 
7961       testl(result, result);
7962       jccb(Assembler::zero, FALSE_LABEL);
7963 
7964       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7965       vptest(vec1, vec2);
7966       jccb(Assembler::notZero, TRUE_LABEL);
7967       jmpb(FALSE_LABEL);
7968 
7969       bind(COMPARE_TAIL); // len is zero
7970       movl(len, result);
7971       // Fallthru to tail compare
7972     } else if (UseSSE42Intrinsics) {
7973       // With SSE4.2, use double quad vector compare
7974       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7975 
7976       // Compare 16-byte vectors
7977       andl(result, 0x0000000f);  //   tail count (in bytes)
7978       andl(len, 0xfffffff0);   // vector count (in bytes)
7979       jccb(Assembler::zero, COMPARE_TAIL);
7980 
7981       lea(ary1, Address(ary1, len, Address::times_1));
7982       negptr(len);
7983 
7984       movl(tmp1, 0x80808080);
7985       movdl(vec2, tmp1);
7986       pshufd(vec2, vec2, 0);
7987 
7988       bind(COMPARE_WIDE_VECTORS);
7989       movdqu(vec1, Address(ary1, len, Address::times_1));
7990       ptest(vec1, vec2);
7991       jccb(Assembler::notZero, TRUE_LABEL);
7992       addptr(len, 16);
7993       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7994 
7995       testl(result, result);
7996       jccb(Assembler::zero, FALSE_LABEL);
7997 
7998       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
7999       ptest(vec1, vec2);
8000       jccb(Assembler::notZero, TRUE_LABEL);
8001       jmpb(FALSE_LABEL);
8002 
8003       bind(COMPARE_TAIL); // len is zero
8004       movl(len, result);
8005       // Fallthru to tail compare
8006     }
8007   }
8008   // Compare 4-byte vectors
8009   andl(len, 0xfffffffc); // vector count (in bytes)
8010   jccb(Assembler::zero, COMPARE_CHAR);
8011 
8012   lea(ary1, Address(ary1, len, Address::times_1));
8013   negptr(len);
8014 
8015   bind(COMPARE_VECTORS);
8016   movl(tmp1, Address(ary1, len, Address::times_1));
8017   andl(tmp1, 0x80808080);
8018   jccb(Assembler::notZero, TRUE_LABEL);
8019   addptr(len, 4);
8020   jcc(Assembler::notZero, COMPARE_VECTORS);
8021 
8022   // Compare trailing char (final 2 bytes), if any
8023   bind(COMPARE_CHAR);
8024   testl(result, 0x2);   // tail  char
8025   jccb(Assembler::zero, COMPARE_BYTE);
8026   load_unsigned_short(tmp1, Address(ary1, 0));
8027   andl(tmp1, 0x00008080);
8028   jccb(Assembler::notZero, TRUE_LABEL);
8029   subptr(result, 2);
8030   lea(ary1, Address(ary1, 2));
8031 
8032   bind(COMPARE_BYTE);
8033   testl(result, 0x1);   // tail  byte
8034   jccb(Assembler::zero, FALSE_LABEL);
8035   load_unsigned_byte(tmp1, Address(ary1, 0));
8036   andl(tmp1, 0x00000080);
8037   jccb(Assembler::notEqual, TRUE_LABEL);
8038   jmpb(FALSE_LABEL);
8039 
8040   bind(TRUE_LABEL);
8041   movl(result, 1);   // return true
8042   jmpb(DONE);
8043 
8044   bind(FALSE_LABEL);
8045   xorl(result, result); // return false
8046 
8047   // That's it
8048   bind(DONE);
8049   if (UseAVX >= 2 && UseSSE >= 2) {
8050     // clean upper bits of YMM registers
8051     vpxor(vec1, vec1);
8052     vpxor(vec2, vec2);
8053   }
8054 }
8055 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8056 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8057                                    Register limit, Register result, Register chr,
8058                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8059   ShortBranchVerifier sbv(this);
8060   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8061 
8062   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8063   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8064 
8065   if (is_array_equ) {
8066     // Check the input args
8067     cmpoop(ary1, ary2);
8068     jcc(Assembler::equal, TRUE_LABEL);
8069 
8070     // Need additional checks for arrays_equals.
8071     testptr(ary1, ary1);
8072     jcc(Assembler::zero, FALSE_LABEL);
8073     testptr(ary2, ary2);
8074     jcc(Assembler::zero, FALSE_LABEL);
8075 
8076     // Check the lengths
8077     movl(limit, Address(ary1, length_offset));
8078     cmpl(limit, Address(ary2, length_offset));
8079     jcc(Assembler::notEqual, FALSE_LABEL);
8080   }
8081 
8082   // count == 0
8083   testl(limit, limit);
8084   jcc(Assembler::zero, TRUE_LABEL);
8085 
8086   if (is_array_equ) {
8087     // Load array address
8088     lea(ary1, Address(ary1, base_offset));
8089     lea(ary2, Address(ary2, base_offset));
8090   }
8091 
8092   if (is_array_equ && is_char) {
8093     // arrays_equals when used for char[].
8094     shll(limit, 1);      // byte count != 0
8095   }
8096   movl(result, limit); // copy
8097 
8098   if (UseAVX >= 2) {
8099     // With AVX2, use 32-byte vector compare
8100     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8101 
8102     // Compare 32-byte vectors
8103     andl(result, 0x0000001f);  //   tail count (in bytes)
8104     andl(limit, 0xffffffe0);   // vector count (in bytes)
8105     jcc(Assembler::zero, COMPARE_TAIL);
8106 
8107     lea(ary1, Address(ary1, limit, Address::times_1));
8108     lea(ary2, Address(ary2, limit, Address::times_1));
8109     negptr(limit);
8110 
8111     bind(COMPARE_WIDE_VECTORS);
8112 
8113 #ifdef _LP64
8114     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8115       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8116 
8117       cmpl(limit, -64);
8118       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8119 
8120       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8121 
8122       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8123       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8124       kortestql(k7, k7);
8125       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8126       addptr(limit, 64);  // update since we already compared at this addr
8127       cmpl(limit, -64);
8128       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8129 
8130       // At this point we may still need to compare -limit+result bytes.
8131       // We could execute the next two instruction and just continue via non-wide path:
8132       //  cmpl(limit, 0);
8133       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8134       // But since we stopped at the points ary{1,2}+limit which are
8135       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8136       // (|limit| <= 32 and result < 32),
8137       // we may just compare the last 64 bytes.
8138       //
8139       addptr(result, -64);   // it is safe, bc we just came from this area
8140       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8141       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8142       kortestql(k7, k7);
8143       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8144 
8145       jmp(TRUE_LABEL);
8146 
8147       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8148 
8149     }//if (VM_Version::supports_avx512vlbw())
8150 #endif //_LP64
8151 
8152     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8153     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8154     vpxor(vec1, vec2);
8155 
8156     vptest(vec1, vec1);
8157     jcc(Assembler::notZero, FALSE_LABEL);
8158     addptr(limit, 32);
8159     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8160 
8161     testl(result, result);
8162     jcc(Assembler::zero, TRUE_LABEL);
8163 
8164     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8165     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8166     vpxor(vec1, vec2);
8167 
8168     vptest(vec1, vec1);
8169     jccb(Assembler::notZero, FALSE_LABEL);
8170     jmpb(TRUE_LABEL);
8171 
8172     bind(COMPARE_TAIL); // limit is zero
8173     movl(limit, result);
8174     // Fallthru to tail compare
8175   } else if (UseSSE42Intrinsics) {
8176     // With SSE4.2, use double quad vector compare
8177     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8178 
8179     // Compare 16-byte vectors
8180     andl(result, 0x0000000f);  //   tail count (in bytes)
8181     andl(limit, 0xfffffff0);   // vector count (in bytes)
8182     jcc(Assembler::zero, COMPARE_TAIL);
8183 
8184     lea(ary1, Address(ary1, limit, Address::times_1));
8185     lea(ary2, Address(ary2, limit, Address::times_1));
8186     negptr(limit);
8187 
8188     bind(COMPARE_WIDE_VECTORS);
8189     movdqu(vec1, Address(ary1, limit, Address::times_1));
8190     movdqu(vec2, Address(ary2, limit, Address::times_1));
8191     pxor(vec1, vec2);
8192 
8193     ptest(vec1, vec1);
8194     jcc(Assembler::notZero, FALSE_LABEL);
8195     addptr(limit, 16);
8196     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8197 
8198     testl(result, result);
8199     jcc(Assembler::zero, TRUE_LABEL);
8200 
8201     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8202     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8203     pxor(vec1, vec2);
8204 
8205     ptest(vec1, vec1);
8206     jccb(Assembler::notZero, FALSE_LABEL);
8207     jmpb(TRUE_LABEL);
8208 
8209     bind(COMPARE_TAIL); // limit is zero
8210     movl(limit, result);
8211     // Fallthru to tail compare
8212   }
8213 
8214   // Compare 4-byte vectors
8215   andl(limit, 0xfffffffc); // vector count (in bytes)
8216   jccb(Assembler::zero, COMPARE_CHAR);
8217 
8218   lea(ary1, Address(ary1, limit, Address::times_1));
8219   lea(ary2, Address(ary2, limit, Address::times_1));
8220   negptr(limit);
8221 
8222   bind(COMPARE_VECTORS);
8223   movl(chr, Address(ary1, limit, Address::times_1));
8224   cmpl(chr, Address(ary2, limit, Address::times_1));
8225   jccb(Assembler::notEqual, FALSE_LABEL);
8226   addptr(limit, 4);
8227   jcc(Assembler::notZero, COMPARE_VECTORS);
8228 
8229   // Compare trailing char (final 2 bytes), if any
8230   bind(COMPARE_CHAR);
8231   testl(result, 0x2);   // tail  char
8232   jccb(Assembler::zero, COMPARE_BYTE);
8233   load_unsigned_short(chr, Address(ary1, 0));
8234   load_unsigned_short(limit, Address(ary2, 0));
8235   cmpl(chr, limit);
8236   jccb(Assembler::notEqual, FALSE_LABEL);
8237 
8238   if (is_array_equ && is_char) {
8239     bind(COMPARE_BYTE);
8240   } else {
8241     lea(ary1, Address(ary1, 2));
8242     lea(ary2, Address(ary2, 2));
8243 
8244     bind(COMPARE_BYTE);
8245     testl(result, 0x1);   // tail  byte
8246     jccb(Assembler::zero, TRUE_LABEL);
8247     load_unsigned_byte(chr, Address(ary1, 0));
8248     load_unsigned_byte(limit, Address(ary2, 0));
8249     cmpl(chr, limit);
8250     jccb(Assembler::notEqual, FALSE_LABEL);
8251   }
8252   bind(TRUE_LABEL);
8253   movl(result, 1);   // return true
8254   jmpb(DONE);
8255 
8256   bind(FALSE_LABEL);
8257   xorl(result, result); // return false
8258 
8259   // That's it
8260   bind(DONE);
8261   if (UseAVX >= 2) {
8262     // clean upper bits of YMM registers
8263     vpxor(vec1, vec1);
8264     vpxor(vec2, vec2);
8265   }
8266 }
8267 
8268 #endif
8269 
8270 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8271                                    Register to, Register value, Register count,
8272                                    Register rtmp, XMMRegister xtmp) {
8273   ShortBranchVerifier sbv(this);
8274   assert_different_registers(to, value, count, rtmp);
8275   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8276   Label L_fill_2_bytes, L_fill_4_bytes;
8277 
8278   int shift = -1;
8279   switch (t) {
8280     case T_BYTE:
8281       shift = 2;
8282       break;
8283     case T_SHORT:
8284       shift = 1;
8285       break;
8286     case T_INT:
8287       shift = 0;
8288       break;
8289     default: ShouldNotReachHere();
8290   }
8291 
8292   if (t == T_BYTE) {
8293     andl(value, 0xff);
8294     movl(rtmp, value);
8295     shll(rtmp, 8);
8296     orl(value, rtmp);
8297   }
8298   if (t == T_SHORT) {
8299     andl(value, 0xffff);
8300   }
8301   if (t == T_BYTE || t == T_SHORT) {
8302     movl(rtmp, value);
8303     shll(rtmp, 16);
8304     orl(value, rtmp);
8305   }
8306 
8307   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8308   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8309   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8310     // align source address at 4 bytes address boundary
8311     if (t == T_BYTE) {
8312       // One byte misalignment happens only for byte arrays
8313       testptr(to, 1);
8314       jccb(Assembler::zero, L_skip_align1);
8315       movb(Address(to, 0), value);
8316       increment(to);
8317       decrement(count);
8318       BIND(L_skip_align1);
8319     }
8320     // Two bytes misalignment happens only for byte and short (char) arrays
8321     testptr(to, 2);
8322     jccb(Assembler::zero, L_skip_align2);
8323     movw(Address(to, 0), value);
8324     addptr(to, 2);
8325     subl(count, 1<<(shift-1));
8326     BIND(L_skip_align2);
8327   }
8328   if (UseSSE < 2) {
8329     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8330     // Fill 32-byte chunks
8331     subl(count, 8 << shift);
8332     jcc(Assembler::less, L_check_fill_8_bytes);
8333     align(16);
8334 
8335     BIND(L_fill_32_bytes_loop);
8336 
8337     for (int i = 0; i < 32; i += 4) {
8338       movl(Address(to, i), value);
8339     }
8340 
8341     addptr(to, 32);
8342     subl(count, 8 << shift);
8343     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8344     BIND(L_check_fill_8_bytes);
8345     addl(count, 8 << shift);
8346     jccb(Assembler::zero, L_exit);
8347     jmpb(L_fill_8_bytes);
8348 
8349     //
8350     // length is too short, just fill qwords
8351     //
8352     BIND(L_fill_8_bytes_loop);
8353     movl(Address(to, 0), value);
8354     movl(Address(to, 4), value);
8355     addptr(to, 8);
8356     BIND(L_fill_8_bytes);
8357     subl(count, 1 << (shift + 1));
8358     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8359     // fall through to fill 4 bytes
8360   } else {
8361     Label L_fill_32_bytes;
8362     if (!UseUnalignedLoadStores) {
8363       // align to 8 bytes, we know we are 4 byte aligned to start
8364       testptr(to, 4);
8365       jccb(Assembler::zero, L_fill_32_bytes);
8366       movl(Address(to, 0), value);
8367       addptr(to, 4);
8368       subl(count, 1<<shift);
8369     }
8370     BIND(L_fill_32_bytes);
8371     {
8372       assert( UseSSE >= 2, "supported cpu only" );
8373       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8374       if (UseAVX > 2) {
8375         movl(rtmp, 0xffff);
8376         kmovwl(k1, rtmp);
8377       }
8378       movdl(xtmp, value);
8379       if (UseAVX > 2 && UseUnalignedLoadStores) {
8380         // Fill 64-byte chunks
8381         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8382         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8383 
8384         subl(count, 16 << shift);
8385         jcc(Assembler::less, L_check_fill_32_bytes);
8386         align(16);
8387 
8388         BIND(L_fill_64_bytes_loop);
8389         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8390         addptr(to, 64);
8391         subl(count, 16 << shift);
8392         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8393 
8394         BIND(L_check_fill_32_bytes);
8395         addl(count, 8 << shift);
8396         jccb(Assembler::less, L_check_fill_8_bytes);
8397         vmovdqu(Address(to, 0), xtmp);
8398         addptr(to, 32);
8399         subl(count, 8 << shift);
8400 
8401         BIND(L_check_fill_8_bytes);
8402       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8403         // Fill 64-byte chunks
8404         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8405         vpbroadcastd(xtmp, xtmp);
8406 
8407         subl(count, 16 << shift);
8408         jcc(Assembler::less, L_check_fill_32_bytes);
8409         align(16);
8410 
8411         BIND(L_fill_64_bytes_loop);
8412         vmovdqu(Address(to, 0), xtmp);
8413         vmovdqu(Address(to, 32), xtmp);
8414         addptr(to, 64);
8415         subl(count, 16 << shift);
8416         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8417 
8418         BIND(L_check_fill_32_bytes);
8419         addl(count, 8 << shift);
8420         jccb(Assembler::less, L_check_fill_8_bytes);
8421         vmovdqu(Address(to, 0), xtmp);
8422         addptr(to, 32);
8423         subl(count, 8 << shift);
8424 
8425         BIND(L_check_fill_8_bytes);
8426         // clean upper bits of YMM registers
8427         movdl(xtmp, value);
8428         pshufd(xtmp, xtmp, 0);
8429       } else {
8430         // Fill 32-byte chunks
8431         pshufd(xtmp, xtmp, 0);
8432 
8433         subl(count, 8 << shift);
8434         jcc(Assembler::less, L_check_fill_8_bytes);
8435         align(16);
8436 
8437         BIND(L_fill_32_bytes_loop);
8438 
8439         if (UseUnalignedLoadStores) {
8440           movdqu(Address(to, 0), xtmp);
8441           movdqu(Address(to, 16), xtmp);
8442         } else {
8443           movq(Address(to, 0), xtmp);
8444           movq(Address(to, 8), xtmp);
8445           movq(Address(to, 16), xtmp);
8446           movq(Address(to, 24), xtmp);
8447         }
8448 
8449         addptr(to, 32);
8450         subl(count, 8 << shift);
8451         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8452 
8453         BIND(L_check_fill_8_bytes);
8454       }
8455       addl(count, 8 << shift);
8456       jccb(Assembler::zero, L_exit);
8457       jmpb(L_fill_8_bytes);
8458 
8459       //
8460       // length is too short, just fill qwords
8461       //
8462       BIND(L_fill_8_bytes_loop);
8463       movq(Address(to, 0), xtmp);
8464       addptr(to, 8);
8465       BIND(L_fill_8_bytes);
8466       subl(count, 1 << (shift + 1));
8467       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8468     }
8469   }
8470   // fill trailing 4 bytes
8471   BIND(L_fill_4_bytes);
8472   testl(count, 1<<shift);
8473   jccb(Assembler::zero, L_fill_2_bytes);
8474   movl(Address(to, 0), value);
8475   if (t == T_BYTE || t == T_SHORT) {
8476     addptr(to, 4);
8477     BIND(L_fill_2_bytes);
8478     // fill trailing 2 bytes
8479     testl(count, 1<<(shift-1));
8480     jccb(Assembler::zero, L_fill_byte);
8481     movw(Address(to, 0), value);
8482     if (t == T_BYTE) {
8483       addptr(to, 2);
8484       BIND(L_fill_byte);
8485       // fill trailing byte
8486       testl(count, 1);
8487       jccb(Assembler::zero, L_exit);
8488       movb(Address(to, 0), value);
8489     } else {
8490       BIND(L_fill_byte);
8491     }
8492   } else {
8493     BIND(L_fill_2_bytes);
8494   }
8495   BIND(L_exit);
8496 }
8497 
8498 // encode char[] to byte[] in ISO_8859_1
8499    //@HotSpotIntrinsicCandidate
8500    //private static int implEncodeISOArray(byte[] sa, int sp,
8501    //byte[] da, int dp, int len) {
8502    //  int i = 0;
8503    //  for (; i < len; i++) {
8504    //    char c = StringUTF16.getChar(sa, sp++);
8505    //    if (c > '\u00FF')
8506    //      break;
8507    //    da[dp++] = (byte)c;
8508    //  }
8509    //  return i;
8510    //}
8511 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8512   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8513   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8514   Register tmp5, Register result) {
8515 
8516   // rsi: src
8517   // rdi: dst
8518   // rdx: len
8519   // rcx: tmp5
8520   // rax: result
8521   ShortBranchVerifier sbv(this);
8522   assert_different_registers(src, dst, len, tmp5, result);
8523   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8524 
8525   // set result
8526   xorl(result, result);
8527   // check for zero length
8528   testl(len, len);
8529   jcc(Assembler::zero, L_done);
8530 
8531   movl(result, len);
8532 
8533   // Setup pointers
8534   lea(src, Address(src, len, Address::times_2)); // char[]
8535   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8536   negptr(len);
8537 
8538   if (UseSSE42Intrinsics || UseAVX >= 2) {
8539     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8540     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8541 
8542     if (UseAVX >= 2) {
8543       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8544       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8545       movdl(tmp1Reg, tmp5);
8546       vpbroadcastd(tmp1Reg, tmp1Reg);
8547       jmp(L_chars_32_check);
8548 
8549       bind(L_copy_32_chars);
8550       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8551       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8552       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8553       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8554       jccb(Assembler::notZero, L_copy_32_chars_exit);
8555       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8556       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8557       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8558 
8559       bind(L_chars_32_check);
8560       addptr(len, 32);
8561       jcc(Assembler::lessEqual, L_copy_32_chars);
8562 
8563       bind(L_copy_32_chars_exit);
8564       subptr(len, 16);
8565       jccb(Assembler::greater, L_copy_16_chars_exit);
8566 
8567     } else if (UseSSE42Intrinsics) {
8568       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8569       movdl(tmp1Reg, tmp5);
8570       pshufd(tmp1Reg, tmp1Reg, 0);
8571       jmpb(L_chars_16_check);
8572     }
8573 
8574     bind(L_copy_16_chars);
8575     if (UseAVX >= 2) {
8576       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8577       vptest(tmp2Reg, tmp1Reg);
8578       jcc(Assembler::notZero, L_copy_16_chars_exit);
8579       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8580       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8581     } else {
8582       if (UseAVX > 0) {
8583         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8584         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8585         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8586       } else {
8587         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8588         por(tmp2Reg, tmp3Reg);
8589         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8590         por(tmp2Reg, tmp4Reg);
8591       }
8592       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8593       jccb(Assembler::notZero, L_copy_16_chars_exit);
8594       packuswb(tmp3Reg, tmp4Reg);
8595     }
8596     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8597 
8598     bind(L_chars_16_check);
8599     addptr(len, 16);
8600     jcc(Assembler::lessEqual, L_copy_16_chars);
8601 
8602     bind(L_copy_16_chars_exit);
8603     if (UseAVX >= 2) {
8604       // clean upper bits of YMM registers
8605       vpxor(tmp2Reg, tmp2Reg);
8606       vpxor(tmp3Reg, tmp3Reg);
8607       vpxor(tmp4Reg, tmp4Reg);
8608       movdl(tmp1Reg, tmp5);
8609       pshufd(tmp1Reg, tmp1Reg, 0);
8610     }
8611     subptr(len, 8);
8612     jccb(Assembler::greater, L_copy_8_chars_exit);
8613 
8614     bind(L_copy_8_chars);
8615     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8616     ptest(tmp3Reg, tmp1Reg);
8617     jccb(Assembler::notZero, L_copy_8_chars_exit);
8618     packuswb(tmp3Reg, tmp1Reg);
8619     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8620     addptr(len, 8);
8621     jccb(Assembler::lessEqual, L_copy_8_chars);
8622 
8623     bind(L_copy_8_chars_exit);
8624     subptr(len, 8);
8625     jccb(Assembler::zero, L_done);
8626   }
8627 
8628   bind(L_copy_1_char);
8629   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8630   testl(tmp5, 0xff00);      // check if Unicode char
8631   jccb(Assembler::notZero, L_copy_1_char_exit);
8632   movb(Address(dst, len, Address::times_1, 0), tmp5);
8633   addptr(len, 1);
8634   jccb(Assembler::less, L_copy_1_char);
8635 
8636   bind(L_copy_1_char_exit);
8637   addptr(result, len); // len is negative count of not processed elements
8638 
8639   bind(L_done);
8640 }
8641 
8642 #ifdef _LP64
8643 /**
8644  * Helper for multiply_to_len().
8645  */
8646 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8647   addq(dest_lo, src1);
8648   adcq(dest_hi, 0);
8649   addq(dest_lo, src2);
8650   adcq(dest_hi, 0);
8651 }
8652 
8653 /**
8654  * Multiply 64 bit by 64 bit first loop.
8655  */
8656 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8657                                            Register y, Register y_idx, Register z,
8658                                            Register carry, Register product,
8659                                            Register idx, Register kdx) {
8660   //
8661   //  jlong carry, x[], y[], z[];
8662   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8663   //    huge_128 product = y[idx] * x[xstart] + carry;
8664   //    z[kdx] = (jlong)product;
8665   //    carry  = (jlong)(product >>> 64);
8666   //  }
8667   //  z[xstart] = carry;
8668   //
8669 
8670   Label L_first_loop, L_first_loop_exit;
8671   Label L_one_x, L_one_y, L_multiply;
8672 
8673   decrementl(xstart);
8674   jcc(Assembler::negative, L_one_x);
8675 
8676   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8677   rorq(x_xstart, 32); // convert big-endian to little-endian
8678 
8679   bind(L_first_loop);
8680   decrementl(idx);
8681   jcc(Assembler::negative, L_first_loop_exit);
8682   decrementl(idx);
8683   jcc(Assembler::negative, L_one_y);
8684   movq(y_idx, Address(y, idx, Address::times_4,  0));
8685   rorq(y_idx, 32); // convert big-endian to little-endian
8686   bind(L_multiply);
8687   movq(product, x_xstart);
8688   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8689   addq(product, carry);
8690   adcq(rdx, 0);
8691   subl(kdx, 2);
8692   movl(Address(z, kdx, Address::times_4,  4), product);
8693   shrq(product, 32);
8694   movl(Address(z, kdx, Address::times_4,  0), product);
8695   movq(carry, rdx);
8696   jmp(L_first_loop);
8697 
8698   bind(L_one_y);
8699   movl(y_idx, Address(y,  0));
8700   jmp(L_multiply);
8701 
8702   bind(L_one_x);
8703   movl(x_xstart, Address(x,  0));
8704   jmp(L_first_loop);
8705 
8706   bind(L_first_loop_exit);
8707 }
8708 
8709 /**
8710  * Multiply 64 bit by 64 bit and add 128 bit.
8711  */
8712 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8713                                             Register yz_idx, Register idx,
8714                                             Register carry, Register product, int offset) {
8715   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8716   //     z[kdx] = (jlong)product;
8717 
8718   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8719   rorq(yz_idx, 32); // convert big-endian to little-endian
8720   movq(product, x_xstart);
8721   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8722   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8723   rorq(yz_idx, 32); // convert big-endian to little-endian
8724 
8725   add2_with_carry(rdx, product, carry, yz_idx);
8726 
8727   movl(Address(z, idx, Address::times_4,  offset+4), product);
8728   shrq(product, 32);
8729   movl(Address(z, idx, Address::times_4,  offset), product);
8730 
8731 }
8732 
8733 /**
8734  * Multiply 128 bit by 128 bit. Unrolled inner loop.
8735  */
8736 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
8737                                              Register yz_idx, Register idx, Register jdx,
8738                                              Register carry, Register product,
8739                                              Register carry2) {
8740   //   jlong carry, x[], y[], z[];
8741   //   int kdx = ystart+1;
8742   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8743   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
8744   //     z[kdx+idx+1] = (jlong)product;
8745   //     jlong carry2  = (jlong)(product >>> 64);
8746   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
8747   //     z[kdx+idx] = (jlong)product;
8748   //     carry  = (jlong)(product >>> 64);
8749   //   }
8750   //   idx += 2;
8751   //   if (idx > 0) {
8752   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
8753   //     z[kdx+idx] = (jlong)product;
8754   //     carry  = (jlong)(product >>> 64);
8755   //   }
8756   //
8757 
8758   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8759 
8760   movl(jdx, idx);
8761   andl(jdx, 0xFFFFFFFC);
8762   shrl(jdx, 2);
8763 
8764   bind(L_third_loop);
8765   subl(jdx, 1);
8766   jcc(Assembler::negative, L_third_loop_exit);
8767   subl(idx, 4);
8768 
8769   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
8770   movq(carry2, rdx);
8771 
8772   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
8773   movq(carry, rdx);
8774   jmp(L_third_loop);
8775 
8776   bind (L_third_loop_exit);
8777 
8778   andl (idx, 0x3);
8779   jcc(Assembler::zero, L_post_third_loop_done);
8780 
8781   Label L_check_1;
8782   subl(idx, 2);
8783   jcc(Assembler::negative, L_check_1);
8784 
8785   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
8786   movq(carry, rdx);
8787 
8788   bind (L_check_1);
8789   addl (idx, 0x2);
8790   andl (idx, 0x1);
8791   subl(idx, 1);
8792   jcc(Assembler::negative, L_post_third_loop_done);
8793 
8794   movl(yz_idx, Address(y, idx, Address::times_4,  0));
8795   movq(product, x_xstart);
8796   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
8797   movl(yz_idx, Address(z, idx, Address::times_4,  0));
8798 
8799   add2_with_carry(rdx, product, yz_idx, carry);
8800 
8801   movl(Address(z, idx, Address::times_4,  0), product);
8802   shrq(product, 32);
8803 
8804   shlq(rdx, 32);
8805   orq(product, rdx);
8806   movq(carry, product);
8807 
8808   bind(L_post_third_loop_done);
8809 }
8810 
8811 /**
8812  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
8813  *
8814  */
8815 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
8816                                                   Register carry, Register carry2,
8817                                                   Register idx, Register jdx,
8818                                                   Register yz_idx1, Register yz_idx2,
8819                                                   Register tmp, Register tmp3, Register tmp4) {
8820   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
8821 
8822   //   jlong carry, x[], y[], z[];
8823   //   int kdx = ystart+1;
8824   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8825   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
8826   //     jlong carry2  = (jlong)(tmp3 >>> 64);
8827   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
8828   //     carry  = (jlong)(tmp4 >>> 64);
8829   //     z[kdx+idx+1] = (jlong)tmp3;
8830   //     z[kdx+idx] = (jlong)tmp4;
8831   //   }
8832   //   idx += 2;
8833   //   if (idx > 0) {
8834   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
8835   //     z[kdx+idx] = (jlong)yz_idx1;
8836   //     carry  = (jlong)(yz_idx1 >>> 64);
8837   //   }
8838   //
8839 
8840   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8841 
8842   movl(jdx, idx);
8843   andl(jdx, 0xFFFFFFFC);
8844   shrl(jdx, 2);
8845 
8846   bind(L_third_loop);
8847   subl(jdx, 1);
8848   jcc(Assembler::negative, L_third_loop_exit);
8849   subl(idx, 4);
8850 
8851   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
8852   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
8853   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
8854   rorxq(yz_idx2, yz_idx2, 32);
8855 
8856   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
8857   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
8858 
8859   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
8860   rorxq(yz_idx1, yz_idx1, 32);
8861   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8862   rorxq(yz_idx2, yz_idx2, 32);
8863 
8864   if (VM_Version::supports_adx()) {
8865     adcxq(tmp3, carry);
8866     adoxq(tmp3, yz_idx1);
8867 
8868     adcxq(tmp4, tmp);
8869     adoxq(tmp4, yz_idx2);
8870 
8871     movl(carry, 0); // does not affect flags
8872     adcxq(carry2, carry);
8873     adoxq(carry2, carry);
8874   } else {
8875     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
8876     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
8877   }
8878   movq(carry, carry2);
8879 
8880   movl(Address(z, idx, Address::times_4, 12), tmp3);
8881   shrq(tmp3, 32);
8882   movl(Address(z, idx, Address::times_4,  8), tmp3);
8883 
8884   movl(Address(z, idx, Address::times_4,  4), tmp4);
8885   shrq(tmp4, 32);
8886   movl(Address(z, idx, Address::times_4,  0), tmp4);
8887 
8888   jmp(L_third_loop);
8889 
8890   bind (L_third_loop_exit);
8891 
8892   andl (idx, 0x3);
8893   jcc(Assembler::zero, L_post_third_loop_done);
8894 
8895   Label L_check_1;
8896   subl(idx, 2);
8897   jcc(Assembler::negative, L_check_1);
8898 
8899   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
8900   rorxq(yz_idx1, yz_idx1, 32);
8901   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
8902   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8903   rorxq(yz_idx2, yz_idx2, 32);
8904 
8905   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
8906 
8907   movl(Address(z, idx, Address::times_4,  4), tmp3);
8908   shrq(tmp3, 32);
8909   movl(Address(z, idx, Address::times_4,  0), tmp3);
8910   movq(carry, tmp4);
8911 
8912   bind (L_check_1);
8913   addl (idx, 0x2);
8914   andl (idx, 0x1);
8915   subl(idx, 1);
8916   jcc(Assembler::negative, L_post_third_loop_done);
8917   movl(tmp4, Address(y, idx, Address::times_4,  0));
8918   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
8919   movl(tmp4, Address(z, idx, Address::times_4,  0));
8920 
8921   add2_with_carry(carry2, tmp3, tmp4, carry);
8922 
8923   movl(Address(z, idx, Address::times_4,  0), tmp3);
8924   shrq(tmp3, 32);
8925 
8926   shlq(carry2, 32);
8927   orq(tmp3, carry2);
8928   movq(carry, tmp3);
8929 
8930   bind(L_post_third_loop_done);
8931 }
8932 
8933 /**
8934  * Code for BigInteger::multiplyToLen() instrinsic.
8935  *
8936  * rdi: x
8937  * rax: xlen
8938  * rsi: y
8939  * rcx: ylen
8940  * r8:  z
8941  * r11: zlen
8942  * r12: tmp1
8943  * r13: tmp2
8944  * r14: tmp3
8945  * r15: tmp4
8946  * rbx: tmp5
8947  *
8948  */
8949 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
8950                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
8951   ShortBranchVerifier sbv(this);
8952   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
8953 
8954   push(tmp1);
8955   push(tmp2);
8956   push(tmp3);
8957   push(tmp4);
8958   push(tmp5);
8959 
8960   push(xlen);
8961   push(zlen);
8962 
8963   const Register idx = tmp1;
8964   const Register kdx = tmp2;
8965   const Register xstart = tmp3;
8966 
8967   const Register y_idx = tmp4;
8968   const Register carry = tmp5;
8969   const Register product  = xlen;
8970   const Register x_xstart = zlen;  // reuse register
8971 
8972   // First Loop.
8973   //
8974   //  final static long LONG_MASK = 0xffffffffL;
8975   //  int xstart = xlen - 1;
8976   //  int ystart = ylen - 1;
8977   //  long carry = 0;
8978   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8979   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
8980   //    z[kdx] = (int)product;
8981   //    carry = product >>> 32;
8982   //  }
8983   //  z[xstart] = (int)carry;
8984   //
8985 
8986   movl(idx, ylen);      // idx = ylen;
8987   movl(kdx, zlen);      // kdx = xlen+ylen;
8988   xorq(carry, carry);   // carry = 0;
8989 
8990   Label L_done;
8991 
8992   movl(xstart, xlen);
8993   decrementl(xstart);
8994   jcc(Assembler::negative, L_done);
8995 
8996   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
8997 
8998   Label L_second_loop;
8999   testl(kdx, kdx);
9000   jcc(Assembler::zero, L_second_loop);
9001 
9002   Label L_carry;
9003   subl(kdx, 1);
9004   jcc(Assembler::zero, L_carry);
9005 
9006   movl(Address(z, kdx, Address::times_4,  0), carry);
9007   shrq(carry, 32);
9008   subl(kdx, 1);
9009 
9010   bind(L_carry);
9011   movl(Address(z, kdx, Address::times_4,  0), carry);
9012 
9013   // Second and third (nested) loops.
9014   //
9015   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9016   //   carry = 0;
9017   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9018   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9019   //                    (z[k] & LONG_MASK) + carry;
9020   //     z[k] = (int)product;
9021   //     carry = product >>> 32;
9022   //   }
9023   //   z[i] = (int)carry;
9024   // }
9025   //
9026   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9027 
9028   const Register jdx = tmp1;
9029 
9030   bind(L_second_loop);
9031   xorl(carry, carry);    // carry = 0;
9032   movl(jdx, ylen);       // j = ystart+1
9033 
9034   subl(xstart, 1);       // i = xstart-1;
9035   jcc(Assembler::negative, L_done);
9036 
9037   push (z);
9038 
9039   Label L_last_x;
9040   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9041   subl(xstart, 1);       // i = xstart-1;
9042   jcc(Assembler::negative, L_last_x);
9043 
9044   if (UseBMI2Instructions) {
9045     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9046     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9047   } else {
9048     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9049     rorq(x_xstart, 32);  // convert big-endian to little-endian
9050   }
9051 
9052   Label L_third_loop_prologue;
9053   bind(L_third_loop_prologue);
9054 
9055   push (x);
9056   push (xstart);
9057   push (ylen);
9058 
9059 
9060   if (UseBMI2Instructions) {
9061     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9062   } else { // !UseBMI2Instructions
9063     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9064   }
9065 
9066   pop(ylen);
9067   pop(xlen);
9068   pop(x);
9069   pop(z);
9070 
9071   movl(tmp3, xlen);
9072   addl(tmp3, 1);
9073   movl(Address(z, tmp3, Address::times_4,  0), carry);
9074   subl(tmp3, 1);
9075   jccb(Assembler::negative, L_done);
9076 
9077   shrq(carry, 32);
9078   movl(Address(z, tmp3, Address::times_4,  0), carry);
9079   jmp(L_second_loop);
9080 
9081   // Next infrequent code is moved outside loops.
9082   bind(L_last_x);
9083   if (UseBMI2Instructions) {
9084     movl(rdx, Address(x,  0));
9085   } else {
9086     movl(x_xstart, Address(x,  0));
9087   }
9088   jmp(L_third_loop_prologue);
9089 
9090   bind(L_done);
9091 
9092   pop(zlen);
9093   pop(xlen);
9094 
9095   pop(tmp5);
9096   pop(tmp4);
9097   pop(tmp3);
9098   pop(tmp2);
9099   pop(tmp1);
9100 }
9101 
9102 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9103   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9104   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9105   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9106   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9107   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9108   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9109   Label SAME_TILL_END, DONE;
9110   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9111 
9112   //scale is in rcx in both Win64 and Unix
9113   ShortBranchVerifier sbv(this);
9114 
9115   shlq(length);
9116   xorq(result, result);
9117 
9118   if ((UseAVX > 2) &&
9119       VM_Version::supports_avx512vlbw()) {
9120     set_vector_masking();  // opening of the stub context for programming mask registers
9121     cmpq(length, 64);
9122     jcc(Assembler::less, VECTOR32_TAIL);
9123     movq(tmp1, length);
9124     andq(tmp1, 0x3F);      // tail count
9125     andq(length, ~(0x3F)); //vector count
9126 
9127     bind(VECTOR64_LOOP);
9128     // AVX512 code to compare 64 byte vectors.
9129     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9130     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9131     kortestql(k7, k7);
9132     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9133     addq(result, 64);
9134     subq(length, 64);
9135     jccb(Assembler::notZero, VECTOR64_LOOP);
9136 
9137     //bind(VECTOR64_TAIL);
9138     testq(tmp1, tmp1);
9139     jcc(Assembler::zero, SAME_TILL_END);
9140 
9141     bind(VECTOR64_TAIL);
9142     // AVX512 code to compare upto 63 byte vectors.
9143     // Save k1
9144     kmovql(k3, k1);
9145     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9146     shlxq(tmp2, tmp2, tmp1);
9147     notq(tmp2);
9148     kmovql(k1, tmp2);
9149 
9150     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9151     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9152 
9153     ktestql(k7, k1);
9154     // Restore k1
9155     kmovql(k1, k3);
9156     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9157 
9158     bind(VECTOR64_NOT_EQUAL);
9159     kmovql(tmp1, k7);
9160     notq(tmp1);
9161     tzcntq(tmp1, tmp1);
9162     addq(result, tmp1);
9163     shrq(result);
9164     jmp(DONE);
9165     bind(VECTOR32_TAIL);
9166     clear_vector_masking();   // closing of the stub context for programming mask registers
9167   }
9168 
9169   cmpq(length, 8);
9170   jcc(Assembler::equal, VECTOR8_LOOP);
9171   jcc(Assembler::less, VECTOR4_TAIL);
9172 
9173   if (UseAVX >= 2) {
9174 
9175     cmpq(length, 16);
9176     jcc(Assembler::equal, VECTOR16_LOOP);
9177     jcc(Assembler::less, VECTOR8_LOOP);
9178 
9179     cmpq(length, 32);
9180     jccb(Assembler::less, VECTOR16_TAIL);
9181 
9182     subq(length, 32);
9183     bind(VECTOR32_LOOP);
9184     vmovdqu(rymm0, Address(obja, result));
9185     vmovdqu(rymm1, Address(objb, result));
9186     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9187     vptest(rymm2, rymm2);
9188     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9189     addq(result, 32);
9190     subq(length, 32);
9191     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9192     addq(length, 32);
9193     jcc(Assembler::equal, SAME_TILL_END);
9194     //falling through if less than 32 bytes left //close the branch here.
9195 
9196     bind(VECTOR16_TAIL);
9197     cmpq(length, 16);
9198     jccb(Assembler::less, VECTOR8_TAIL);
9199     bind(VECTOR16_LOOP);
9200     movdqu(rymm0, Address(obja, result));
9201     movdqu(rymm1, Address(objb, result));
9202     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9203     ptest(rymm2, rymm2);
9204     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9205     addq(result, 16);
9206     subq(length, 16);
9207     jcc(Assembler::equal, SAME_TILL_END);
9208     //falling through if less than 16 bytes left
9209   } else {//regular intrinsics
9210 
9211     cmpq(length, 16);
9212     jccb(Assembler::less, VECTOR8_TAIL);
9213 
9214     subq(length, 16);
9215     bind(VECTOR16_LOOP);
9216     movdqu(rymm0, Address(obja, result));
9217     movdqu(rymm1, Address(objb, result));
9218     pxor(rymm0, rymm1);
9219     ptest(rymm0, rymm0);
9220     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9221     addq(result, 16);
9222     subq(length, 16);
9223     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9224     addq(length, 16);
9225     jcc(Assembler::equal, SAME_TILL_END);
9226     //falling through if less than 16 bytes left
9227   }
9228 
9229   bind(VECTOR8_TAIL);
9230   cmpq(length, 8);
9231   jccb(Assembler::less, VECTOR4_TAIL);
9232   bind(VECTOR8_LOOP);
9233   movq(tmp1, Address(obja, result));
9234   movq(tmp2, Address(objb, result));
9235   xorq(tmp1, tmp2);
9236   testq(tmp1, tmp1);
9237   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9238   addq(result, 8);
9239   subq(length, 8);
9240   jcc(Assembler::equal, SAME_TILL_END);
9241   //falling through if less than 8 bytes left
9242 
9243   bind(VECTOR4_TAIL);
9244   cmpq(length, 4);
9245   jccb(Assembler::less, BYTES_TAIL);
9246   bind(VECTOR4_LOOP);
9247   movl(tmp1, Address(obja, result));
9248   xorl(tmp1, Address(objb, result));
9249   testl(tmp1, tmp1);
9250   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9251   addq(result, 4);
9252   subq(length, 4);
9253   jcc(Assembler::equal, SAME_TILL_END);
9254   //falling through if less than 4 bytes left
9255 
9256   bind(BYTES_TAIL);
9257   bind(BYTES_LOOP);
9258   load_unsigned_byte(tmp1, Address(obja, result));
9259   load_unsigned_byte(tmp2, Address(objb, result));
9260   xorl(tmp1, tmp2);
9261   testl(tmp1, tmp1);
9262   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9263   decq(length);
9264   jccb(Assembler::zero, SAME_TILL_END);
9265   incq(result);
9266   load_unsigned_byte(tmp1, Address(obja, result));
9267   load_unsigned_byte(tmp2, Address(objb, result));
9268   xorl(tmp1, tmp2);
9269   testl(tmp1, tmp1);
9270   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9271   decq(length);
9272   jccb(Assembler::zero, SAME_TILL_END);
9273   incq(result);
9274   load_unsigned_byte(tmp1, Address(obja, result));
9275   load_unsigned_byte(tmp2, Address(objb, result));
9276   xorl(tmp1, tmp2);
9277   testl(tmp1, tmp1);
9278   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9279   jmpb(SAME_TILL_END);
9280 
9281   if (UseAVX >= 2) {
9282     bind(VECTOR32_NOT_EQUAL);
9283     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9284     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9285     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9286     vpmovmskb(tmp1, rymm0);
9287     bsfq(tmp1, tmp1);
9288     addq(result, tmp1);
9289     shrq(result);
9290     jmpb(DONE);
9291   }
9292 
9293   bind(VECTOR16_NOT_EQUAL);
9294   if (UseAVX >= 2) {
9295     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9296     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9297     pxor(rymm0, rymm2);
9298   } else {
9299     pcmpeqb(rymm2, rymm2);
9300     pxor(rymm0, rymm1);
9301     pcmpeqb(rymm0, rymm1);
9302     pxor(rymm0, rymm2);
9303   }
9304   pmovmskb(tmp1, rymm0);
9305   bsfq(tmp1, tmp1);
9306   addq(result, tmp1);
9307   shrq(result);
9308   jmpb(DONE);
9309 
9310   bind(VECTOR8_NOT_EQUAL);
9311   bind(VECTOR4_NOT_EQUAL);
9312   bsfq(tmp1, tmp1);
9313   shrq(tmp1, 3);
9314   addq(result, tmp1);
9315   bind(BYTES_NOT_EQUAL);
9316   shrq(result);
9317   jmpb(DONE);
9318 
9319   bind(SAME_TILL_END);
9320   mov64(result, -1);
9321 
9322   bind(DONE);
9323 }
9324 
9325 //Helper functions for square_to_len()
9326 
9327 /**
9328  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9329  * Preserves x and z and modifies rest of the registers.
9330  */
9331 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9332   // Perform square and right shift by 1
9333   // Handle odd xlen case first, then for even xlen do the following
9334   // jlong carry = 0;
9335   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9336   //     huge_128 product = x[j:j+1] * x[j:j+1];
9337   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9338   //     z[i+2:i+3] = (jlong)(product >>> 1);
9339   //     carry = (jlong)product;
9340   // }
9341 
9342   xorq(tmp5, tmp5);     // carry
9343   xorq(rdxReg, rdxReg);
9344   xorl(tmp1, tmp1);     // index for x
9345   xorl(tmp4, tmp4);     // index for z
9346 
9347   Label L_first_loop, L_first_loop_exit;
9348 
9349   testl(xlen, 1);
9350   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9351 
9352   // Square and right shift by 1 the odd element using 32 bit multiply
9353   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9354   imulq(raxReg, raxReg);
9355   shrq(raxReg, 1);
9356   adcq(tmp5, 0);
9357   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9358   incrementl(tmp1);
9359   addl(tmp4, 2);
9360 
9361   // Square and  right shift by 1 the rest using 64 bit multiply
9362   bind(L_first_loop);
9363   cmpptr(tmp1, xlen);
9364   jccb(Assembler::equal, L_first_loop_exit);
9365 
9366   // Square
9367   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9368   rorq(raxReg, 32);    // convert big-endian to little-endian
9369   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9370 
9371   // Right shift by 1 and save carry
9372   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9373   rcrq(rdxReg, 1);
9374   rcrq(raxReg, 1);
9375   adcq(tmp5, 0);
9376 
9377   // Store result in z
9378   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9379   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9380 
9381   // Update indices for x and z
9382   addl(tmp1, 2);
9383   addl(tmp4, 4);
9384   jmp(L_first_loop);
9385 
9386   bind(L_first_loop_exit);
9387 }
9388 
9389 
9390 /**
9391  * Perform the following multiply add operation using BMI2 instructions
9392  * carry:sum = sum + op1*op2 + carry
9393  * op2 should be in rdx
9394  * op2 is preserved, all other registers are modified
9395  */
9396 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9397   // assert op2 is rdx
9398   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9399   addq(sum, carry);
9400   adcq(tmp2, 0);
9401   addq(sum, op1);
9402   adcq(tmp2, 0);
9403   movq(carry, tmp2);
9404 }
9405 
9406 /**
9407  * Perform the following multiply add operation:
9408  * carry:sum = sum + op1*op2 + carry
9409  * Preserves op1, op2 and modifies rest of registers
9410  */
9411 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9412   // rdx:rax = op1 * op2
9413   movq(raxReg, op2);
9414   mulq(op1);
9415 
9416   //  rdx:rax = sum + carry + rdx:rax
9417   addq(sum, carry);
9418   adcq(rdxReg, 0);
9419   addq(sum, raxReg);
9420   adcq(rdxReg, 0);
9421 
9422   // carry:sum = rdx:sum
9423   movq(carry, rdxReg);
9424 }
9425 
9426 /**
9427  * Add 64 bit long carry into z[] with carry propogation.
9428  * Preserves z and carry register values and modifies rest of registers.
9429  *
9430  */
9431 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9432   Label L_fourth_loop, L_fourth_loop_exit;
9433 
9434   movl(tmp1, 1);
9435   subl(zlen, 2);
9436   addq(Address(z, zlen, Address::times_4, 0), carry);
9437 
9438   bind(L_fourth_loop);
9439   jccb(Assembler::carryClear, L_fourth_loop_exit);
9440   subl(zlen, 2);
9441   jccb(Assembler::negative, L_fourth_loop_exit);
9442   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9443   jmp(L_fourth_loop);
9444   bind(L_fourth_loop_exit);
9445 }
9446 
9447 /**
9448  * Shift z[] left by 1 bit.
9449  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9450  *
9451  */
9452 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9453 
9454   Label L_fifth_loop, L_fifth_loop_exit;
9455 
9456   // Fifth loop
9457   // Perform primitiveLeftShift(z, zlen, 1)
9458 
9459   const Register prev_carry = tmp1;
9460   const Register new_carry = tmp4;
9461   const Register value = tmp2;
9462   const Register zidx = tmp3;
9463 
9464   // int zidx, carry;
9465   // long value;
9466   // carry = 0;
9467   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9468   //    (carry:value)  = (z[i] << 1) | carry ;
9469   //    z[i] = value;
9470   // }
9471 
9472   movl(zidx, zlen);
9473   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9474 
9475   bind(L_fifth_loop);
9476   decl(zidx);  // Use decl to preserve carry flag
9477   decl(zidx);
9478   jccb(Assembler::negative, L_fifth_loop_exit);
9479 
9480   if (UseBMI2Instructions) {
9481      movq(value, Address(z, zidx, Address::times_4, 0));
9482      rclq(value, 1);
9483      rorxq(value, value, 32);
9484      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9485   }
9486   else {
9487     // clear new_carry
9488     xorl(new_carry, new_carry);
9489 
9490     // Shift z[i] by 1, or in previous carry and save new carry
9491     movq(value, Address(z, zidx, Address::times_4, 0));
9492     shlq(value, 1);
9493     adcl(new_carry, 0);
9494 
9495     orq(value, prev_carry);
9496     rorq(value, 0x20);
9497     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9498 
9499     // Set previous carry = new carry
9500     movl(prev_carry, new_carry);
9501   }
9502   jmp(L_fifth_loop);
9503 
9504   bind(L_fifth_loop_exit);
9505 }
9506 
9507 
9508 /**
9509  * Code for BigInteger::squareToLen() intrinsic
9510  *
9511  * rdi: x
9512  * rsi: len
9513  * r8:  z
9514  * rcx: zlen
9515  * r12: tmp1
9516  * r13: tmp2
9517  * r14: tmp3
9518  * r15: tmp4
9519  * rbx: tmp5
9520  *
9521  */
9522 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) {
9523 
9524   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;
9525   push(tmp1);
9526   push(tmp2);
9527   push(tmp3);
9528   push(tmp4);
9529   push(tmp5);
9530 
9531   // First loop
9532   // Store the squares, right shifted one bit (i.e., divided by 2).
9533   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9534 
9535   // Add in off-diagonal sums.
9536   //
9537   // Second, third (nested) and fourth loops.
9538   // zlen +=2;
9539   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9540   //    carry = 0;
9541   //    long op2 = x[xidx:xidx+1];
9542   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9543   //       k -= 2;
9544   //       long op1 = x[j:j+1];
9545   //       long sum = z[k:k+1];
9546   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9547   //       z[k:k+1] = sum;
9548   //    }
9549   //    add_one_64(z, k, carry, tmp_regs);
9550   // }
9551 
9552   const Register carry = tmp5;
9553   const Register sum = tmp3;
9554   const Register op1 = tmp4;
9555   Register op2 = tmp2;
9556 
9557   push(zlen);
9558   push(len);
9559   addl(zlen,2);
9560   bind(L_second_loop);
9561   xorq(carry, carry);
9562   subl(zlen, 4);
9563   subl(len, 2);
9564   push(zlen);
9565   push(len);
9566   cmpl(len, 0);
9567   jccb(Assembler::lessEqual, L_second_loop_exit);
9568 
9569   // Multiply an array by one 64 bit long.
9570   if (UseBMI2Instructions) {
9571     op2 = rdxReg;
9572     movq(op2, Address(x, len, Address::times_4,  0));
9573     rorxq(op2, op2, 32);
9574   }
9575   else {
9576     movq(op2, Address(x, len, Address::times_4,  0));
9577     rorq(op2, 32);
9578   }
9579 
9580   bind(L_third_loop);
9581   decrementl(len);
9582   jccb(Assembler::negative, L_third_loop_exit);
9583   decrementl(len);
9584   jccb(Assembler::negative, L_last_x);
9585 
9586   movq(op1, Address(x, len, Address::times_4,  0));
9587   rorq(op1, 32);
9588 
9589   bind(L_multiply);
9590   subl(zlen, 2);
9591   movq(sum, Address(z, zlen, Address::times_4,  0));
9592 
9593   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9594   if (UseBMI2Instructions) {
9595     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9596   }
9597   else {
9598     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9599   }
9600 
9601   movq(Address(z, zlen, Address::times_4, 0), sum);
9602 
9603   jmp(L_third_loop);
9604   bind(L_third_loop_exit);
9605 
9606   // Fourth loop
9607   // Add 64 bit long carry into z with carry propogation.
9608   // Uses offsetted zlen.
9609   add_one_64(z, zlen, carry, tmp1);
9610 
9611   pop(len);
9612   pop(zlen);
9613   jmp(L_second_loop);
9614 
9615   // Next infrequent code is moved outside loops.
9616   bind(L_last_x);
9617   movl(op1, Address(x, 0));
9618   jmp(L_multiply);
9619 
9620   bind(L_second_loop_exit);
9621   pop(len);
9622   pop(zlen);
9623   pop(len);
9624   pop(zlen);
9625 
9626   // Fifth loop
9627   // Shift z left 1 bit.
9628   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9629 
9630   // z[zlen-1] |= x[len-1] & 1;
9631   movl(tmp3, Address(x, len, Address::times_4, -4));
9632   andl(tmp3, 1);
9633   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9634 
9635   pop(tmp5);
9636   pop(tmp4);
9637   pop(tmp3);
9638   pop(tmp2);
9639   pop(tmp1);
9640 }
9641 
9642 /**
9643  * Helper function for mul_add()
9644  * Multiply the in[] by int k and add to out[] starting at offset offs using
9645  * 128 bit by 32 bit multiply and return the carry in tmp5.
9646  * Only quad int aligned length of in[] is operated on in this function.
9647  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9648  * This function preserves out, in and k registers.
9649  * len and offset point to the appropriate index in "in" & "out" correspondingly
9650  * tmp5 has the carry.
9651  * other registers are temporary and are modified.
9652  *
9653  */
9654 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9655   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9656   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9657 
9658   Label L_first_loop, L_first_loop_exit;
9659 
9660   movl(tmp1, len);
9661   shrl(tmp1, 2);
9662 
9663   bind(L_first_loop);
9664   subl(tmp1, 1);
9665   jccb(Assembler::negative, L_first_loop_exit);
9666 
9667   subl(len, 4);
9668   subl(offset, 4);
9669 
9670   Register op2 = tmp2;
9671   const Register sum = tmp3;
9672   const Register op1 = tmp4;
9673   const Register carry = tmp5;
9674 
9675   if (UseBMI2Instructions) {
9676     op2 = rdxReg;
9677   }
9678 
9679   movq(op1, Address(in, len, Address::times_4,  8));
9680   rorq(op1, 32);
9681   movq(sum, Address(out, offset, Address::times_4,  8));
9682   rorq(sum, 32);
9683   if (UseBMI2Instructions) {
9684     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9685   }
9686   else {
9687     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9688   }
9689   // Store back in big endian from little endian
9690   rorq(sum, 0x20);
9691   movq(Address(out, offset, Address::times_4,  8), sum);
9692 
9693   movq(op1, Address(in, len, Address::times_4,  0));
9694   rorq(op1, 32);
9695   movq(sum, Address(out, offset, Address::times_4,  0));
9696   rorq(sum, 32);
9697   if (UseBMI2Instructions) {
9698     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9699   }
9700   else {
9701     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9702   }
9703   // Store back in big endian from little endian
9704   rorq(sum, 0x20);
9705   movq(Address(out, offset, Address::times_4,  0), sum);
9706 
9707   jmp(L_first_loop);
9708   bind(L_first_loop_exit);
9709 }
9710 
9711 /**
9712  * Code for BigInteger::mulAdd() intrinsic
9713  *
9714  * rdi: out
9715  * rsi: in
9716  * r11: offs (out.length - offset)
9717  * rcx: len
9718  * r8:  k
9719  * r12: tmp1
9720  * r13: tmp2
9721  * r14: tmp3
9722  * r15: tmp4
9723  * rbx: tmp5
9724  * Multiply the in[] by word k and add to out[], return the carry in rax
9725  */
9726 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9727    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9728    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9729 
9730   Label L_carry, L_last_in, L_done;
9731 
9732 // carry = 0;
9733 // for (int j=len-1; j >= 0; j--) {
9734 //    long product = (in[j] & LONG_MASK) * kLong +
9735 //                   (out[offs] & LONG_MASK) + carry;
9736 //    out[offs--] = (int)product;
9737 //    carry = product >>> 32;
9738 // }
9739 //
9740   push(tmp1);
9741   push(tmp2);
9742   push(tmp3);
9743   push(tmp4);
9744   push(tmp5);
9745 
9746   Register op2 = tmp2;
9747   const Register sum = tmp3;
9748   const Register op1 = tmp4;
9749   const Register carry =  tmp5;
9750 
9751   if (UseBMI2Instructions) {
9752     op2 = rdxReg;
9753     movl(op2, k);
9754   }
9755   else {
9756     movl(op2, k);
9757   }
9758 
9759   xorq(carry, carry);
9760 
9761   //First loop
9762 
9763   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9764   //The carry is in tmp5
9765   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9766 
9767   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9768   decrementl(len);
9769   jccb(Assembler::negative, L_carry);
9770   decrementl(len);
9771   jccb(Assembler::negative, L_last_in);
9772 
9773   movq(op1, Address(in, len, Address::times_4,  0));
9774   rorq(op1, 32);
9775 
9776   subl(offs, 2);
9777   movq(sum, Address(out, offs, Address::times_4,  0));
9778   rorq(sum, 32);
9779 
9780   if (UseBMI2Instructions) {
9781     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9782   }
9783   else {
9784     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9785   }
9786 
9787   // Store back in big endian from little endian
9788   rorq(sum, 0x20);
9789   movq(Address(out, offs, Address::times_4,  0), sum);
9790 
9791   testl(len, len);
9792   jccb(Assembler::zero, L_carry);
9793 
9794   //Multiply the last in[] entry, if any
9795   bind(L_last_in);
9796   movl(op1, Address(in, 0));
9797   movl(sum, Address(out, offs, Address::times_4,  -4));
9798 
9799   movl(raxReg, k);
9800   mull(op1); //tmp4 * eax -> edx:eax
9801   addl(sum, carry);
9802   adcl(rdxReg, 0);
9803   addl(sum, raxReg);
9804   adcl(rdxReg, 0);
9805   movl(carry, rdxReg);
9806 
9807   movl(Address(out, offs, Address::times_4,  -4), sum);
9808 
9809   bind(L_carry);
9810   //return tmp5/carry as carry in rax
9811   movl(rax, carry);
9812 
9813   bind(L_done);
9814   pop(tmp5);
9815   pop(tmp4);
9816   pop(tmp3);
9817   pop(tmp2);
9818   pop(tmp1);
9819 }
9820 #endif
9821 
9822 /**
9823  * Emits code to update CRC-32 with a byte value according to constants in table
9824  *
9825  * @param [in,out]crc   Register containing the crc.
9826  * @param [in]val       Register containing the byte to fold into the CRC.
9827  * @param [in]table     Register containing the table of crc constants.
9828  *
9829  * uint32_t crc;
9830  * val = crc_table[(val ^ crc) & 0xFF];
9831  * crc = val ^ (crc >> 8);
9832  *
9833  */
9834 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9835   xorl(val, crc);
9836   andl(val, 0xFF);
9837   shrl(crc, 8); // unsigned shift
9838   xorl(crc, Address(table, val, Address::times_4, 0));
9839 }
9840 
9841 /**
9842 * Fold four 128-bit data chunks
9843 */
9844 void MacroAssembler::fold_128bit_crc32_avx512(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9845   evpclmulhdq(xtmp, xK, xcrc, Assembler::AVX_512bit); // [123:64]
9846   evpclmulldq(xcrc, xK, xcrc, Assembler::AVX_512bit); // [63:0]
9847   evpxorq(xcrc, xcrc, Address(buf, offset), Assembler::AVX_512bit /* vector_len */);
9848   evpxorq(xcrc, xcrc, xtmp, Assembler::AVX_512bit /* vector_len */);
9849 }
9850 
9851 /**
9852  * Fold 128-bit data chunk
9853  */
9854 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9855   if (UseAVX > 0) {
9856     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9857     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9858     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9859     pxor(xcrc, xtmp);
9860   } else {
9861     movdqa(xtmp, xcrc);
9862     pclmulhdq(xtmp, xK);   // [123:64]
9863     pclmulldq(xcrc, xK);   // [63:0]
9864     pxor(xcrc, xtmp);
9865     movdqu(xtmp, Address(buf, offset));
9866     pxor(xcrc, xtmp);
9867   }
9868 }
9869 
9870 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9871   if (UseAVX > 0) {
9872     vpclmulhdq(xtmp, xK, xcrc);
9873     vpclmulldq(xcrc, xK, xcrc);
9874     pxor(xcrc, xbuf);
9875     pxor(xcrc, xtmp);
9876   } else {
9877     movdqa(xtmp, xcrc);
9878     pclmulhdq(xtmp, xK);
9879     pclmulldq(xcrc, xK);
9880     pxor(xcrc, xbuf);
9881     pxor(xcrc, xtmp);
9882   }
9883 }
9884 
9885 /**
9886  * 8-bit folds to compute 32-bit CRC
9887  *
9888  * uint64_t xcrc;
9889  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9890  */
9891 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9892   movdl(tmp, xcrc);
9893   andl(tmp, 0xFF);
9894   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
9895   psrldq(xcrc, 1); // unsigned shift one byte
9896   pxor(xcrc, xtmp);
9897 }
9898 
9899 /**
9900  * uint32_t crc;
9901  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
9902  */
9903 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
9904   movl(tmp, crc);
9905   andl(tmp, 0xFF);
9906   shrl(crc, 8);
9907   xorl(crc, Address(table, tmp, Address::times_4, 0));
9908 }
9909 
9910 /**
9911  * @param crc   register containing existing CRC (32-bit)
9912  * @param buf   register pointing to input byte buffer (byte*)
9913  * @param len   register containing number of bytes
9914  * @param table register that will contain address of CRC table
9915  * @param tmp   scratch register
9916  */
9917 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
9918   assert_different_registers(crc, buf, len, table, tmp, rax);
9919 
9920   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
9921   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
9922 
9923   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
9924   // context for the registers used, where all instructions below are using 128-bit mode
9925   // On EVEX without VL and BW, these instructions will all be AVX.
9926   if (VM_Version::supports_avx512vlbw()) {
9927     movl(tmp, 0xffff);
9928     kmovwl(k1, tmp);
9929   }
9930 
9931   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
9932   notl(crc); // ~crc
9933   cmpl(len, 16);
9934   jcc(Assembler::less, L_tail);
9935 
9936   // Align buffer to 16 bytes
9937   movl(tmp, buf);
9938   andl(tmp, 0xF);
9939   jccb(Assembler::zero, L_aligned);
9940   subl(tmp,  16);
9941   addl(len, tmp);
9942 
9943   align(4);
9944   BIND(L_align_loop);
9945   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9946   update_byte_crc32(crc, rax, table);
9947   increment(buf);
9948   incrementl(tmp);
9949   jccb(Assembler::less, L_align_loop);
9950 
9951   BIND(L_aligned);
9952   movl(tmp, len); // save
9953   shrl(len, 4);
9954   jcc(Assembler::zero, L_tail_restore);
9955 
9956   // Fold total 512 bits of polynomial on each iteration
9957   if (VM_Version::supports_vpclmulqdq()) {
9958     Label Parallel_loop, L_No_Parallel;
9959 
9960     cmpl(len, 8);
9961     jccb(Assembler::less, L_No_Parallel);
9962 
9963     movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9964     evmovdquq(xmm1, Address(buf, 0), Assembler::AVX_512bit);
9965     movdl(xmm5, crc);
9966     evpxorq(xmm1, xmm1, xmm5, Assembler::AVX_512bit);
9967     addptr(buf, 64);
9968     subl(len, 7);
9969     evshufi64x2(xmm0, xmm0, xmm0, 0x00, Assembler::AVX_512bit); //propagate the mask from 128 bits to 512 bits
9970 
9971     BIND(Parallel_loop);
9972     fold_128bit_crc32_avx512(xmm1, xmm0, xmm5, buf, 0);
9973     addptr(buf, 64);
9974     subl(len, 4);
9975     jcc(Assembler::greater, Parallel_loop);
9976 
9977     vextracti64x2(xmm2, xmm1, 0x01);
9978     vextracti64x2(xmm3, xmm1, 0x02);
9979     vextracti64x2(xmm4, xmm1, 0x03);
9980     jmp(L_fold_512b);
9981 
9982     BIND(L_No_Parallel);
9983   }
9984   // Fold crc into first bytes of vector
9985   movdqa(xmm1, Address(buf, 0));
9986   movdl(rax, xmm1);
9987   xorl(crc, rax);
9988   if (VM_Version::supports_sse4_1()) {
9989     pinsrd(xmm1, crc, 0);
9990   } else {
9991     pinsrw(xmm1, crc, 0);
9992     shrl(crc, 16);
9993     pinsrw(xmm1, crc, 1);
9994   }
9995   addptr(buf, 16);
9996   subl(len, 4); // len > 0
9997   jcc(Assembler::less, L_fold_tail);
9998 
9999   movdqa(xmm2, Address(buf,  0));
10000   movdqa(xmm3, Address(buf, 16));
10001   movdqa(xmm4, Address(buf, 32));
10002   addptr(buf, 48);
10003   subl(len, 3);
10004   jcc(Assembler::lessEqual, L_fold_512b);
10005 
10006   // Fold total 512 bits of polynomial on each iteration,
10007   // 128 bits per each of 4 parallel streams.
10008   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10009 
10010   align(32);
10011   BIND(L_fold_512b_loop);
10012   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10013   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10014   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10015   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10016   addptr(buf, 64);
10017   subl(len, 4);
10018   jcc(Assembler::greater, L_fold_512b_loop);
10019 
10020   // Fold 512 bits to 128 bits.
10021   BIND(L_fold_512b);
10022   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10023   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10024   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10025   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10026 
10027   // Fold the rest of 128 bits data chunks
10028   BIND(L_fold_tail);
10029   addl(len, 3);
10030   jccb(Assembler::lessEqual, L_fold_128b);
10031   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10032 
10033   BIND(L_fold_tail_loop);
10034   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10035   addptr(buf, 16);
10036   decrementl(len);
10037   jccb(Assembler::greater, L_fold_tail_loop);
10038 
10039   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10040   BIND(L_fold_128b);
10041   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10042   if (UseAVX > 0) {
10043     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10044     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10045     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10046   } else {
10047     movdqa(xmm2, xmm0);
10048     pclmulqdq(xmm2, xmm1, 0x1);
10049     movdqa(xmm3, xmm0);
10050     pand(xmm3, xmm2);
10051     pclmulqdq(xmm0, xmm3, 0x1);
10052   }
10053   psrldq(xmm1, 8);
10054   psrldq(xmm2, 4);
10055   pxor(xmm0, xmm1);
10056   pxor(xmm0, xmm2);
10057 
10058   // 8 8-bit folds to compute 32-bit CRC.
10059   for (int j = 0; j < 4; j++) {
10060     fold_8bit_crc32(xmm0, table, xmm1, rax);
10061   }
10062   movdl(crc, xmm0); // mov 32 bits to general register
10063   for (int j = 0; j < 4; j++) {
10064     fold_8bit_crc32(crc, table, rax);
10065   }
10066 
10067   BIND(L_tail_restore);
10068   movl(len, tmp); // restore
10069   BIND(L_tail);
10070   andl(len, 0xf);
10071   jccb(Assembler::zero, L_exit);
10072 
10073   // Fold the rest of bytes
10074   align(4);
10075   BIND(L_tail_loop);
10076   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10077   update_byte_crc32(crc, rax, table);
10078   increment(buf);
10079   decrementl(len);
10080   jccb(Assembler::greater, L_tail_loop);
10081 
10082   BIND(L_exit);
10083   notl(crc); // ~c
10084 }
10085 
10086 #ifdef _LP64
10087 // S. Gueron / Information Processing Letters 112 (2012) 184
10088 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10089 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10090 // Output: the 64-bit carry-less product of B * CONST
10091 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10092                                      Register tmp1, Register tmp2, Register tmp3) {
10093   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10094   if (n > 0) {
10095     addq(tmp3, n * 256 * 8);
10096   }
10097   //    Q1 = TABLEExt[n][B & 0xFF];
10098   movl(tmp1, in);
10099   andl(tmp1, 0x000000FF);
10100   shll(tmp1, 3);
10101   addq(tmp1, tmp3);
10102   movq(tmp1, Address(tmp1, 0));
10103 
10104   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10105   movl(tmp2, in);
10106   shrl(tmp2, 8);
10107   andl(tmp2, 0x000000FF);
10108   shll(tmp2, 3);
10109   addq(tmp2, tmp3);
10110   movq(tmp2, Address(tmp2, 0));
10111 
10112   shlq(tmp2, 8);
10113   xorq(tmp1, tmp2);
10114 
10115   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10116   movl(tmp2, in);
10117   shrl(tmp2, 16);
10118   andl(tmp2, 0x000000FF);
10119   shll(tmp2, 3);
10120   addq(tmp2, tmp3);
10121   movq(tmp2, Address(tmp2, 0));
10122 
10123   shlq(tmp2, 16);
10124   xorq(tmp1, tmp2);
10125 
10126   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10127   shrl(in, 24);
10128   andl(in, 0x000000FF);
10129   shll(in, 3);
10130   addq(in, tmp3);
10131   movq(in, Address(in, 0));
10132 
10133   shlq(in, 24);
10134   xorq(in, tmp1);
10135   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10136 }
10137 
10138 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10139                                       Register in_out,
10140                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10141                                       XMMRegister w_xtmp2,
10142                                       Register tmp1,
10143                                       Register n_tmp2, Register n_tmp3) {
10144   if (is_pclmulqdq_supported) {
10145     movdl(w_xtmp1, in_out); // modified blindly
10146 
10147     movl(tmp1, const_or_pre_comp_const_index);
10148     movdl(w_xtmp2, tmp1);
10149     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10150 
10151     movdq(in_out, w_xtmp1);
10152   } else {
10153     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10154   }
10155 }
10156 
10157 // Recombination Alternative 2: No bit-reflections
10158 // T1 = (CRC_A * U1) << 1
10159 // T2 = (CRC_B * U2) << 1
10160 // C1 = T1 >> 32
10161 // C2 = T2 >> 32
10162 // T1 = T1 & 0xFFFFFFFF
10163 // T2 = T2 & 0xFFFFFFFF
10164 // T1 = CRC32(0, T1)
10165 // T2 = CRC32(0, T2)
10166 // C1 = C1 ^ T1
10167 // C2 = C2 ^ T2
10168 // CRC = C1 ^ C2 ^ CRC_C
10169 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,
10170                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10171                                      Register tmp1, Register tmp2,
10172                                      Register n_tmp3) {
10173   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10174   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10175   shlq(in_out, 1);
10176   movl(tmp1, in_out);
10177   shrq(in_out, 32);
10178   xorl(tmp2, tmp2);
10179   crc32(tmp2, tmp1, 4);
10180   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10181   shlq(in1, 1);
10182   movl(tmp1, in1);
10183   shrq(in1, 32);
10184   xorl(tmp2, tmp2);
10185   crc32(tmp2, tmp1, 4);
10186   xorl(in1, tmp2);
10187   xorl(in_out, in1);
10188   xorl(in_out, in2);
10189 }
10190 
10191 // Set N to predefined value
10192 // Subtract from a lenght of a buffer
10193 // execute in a loop:
10194 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10195 // for i = 1 to N do
10196 //  CRC_A = CRC32(CRC_A, A[i])
10197 //  CRC_B = CRC32(CRC_B, B[i])
10198 //  CRC_C = CRC32(CRC_C, C[i])
10199 // end for
10200 // Recombine
10201 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,
10202                                        Register in_out1, Register in_out2, Register in_out3,
10203                                        Register tmp1, Register tmp2, Register tmp3,
10204                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10205                                        Register tmp4, Register tmp5,
10206                                        Register n_tmp6) {
10207   Label L_processPartitions;
10208   Label L_processPartition;
10209   Label L_exit;
10210 
10211   bind(L_processPartitions);
10212   cmpl(in_out1, 3 * size);
10213   jcc(Assembler::less, L_exit);
10214     xorl(tmp1, tmp1);
10215     xorl(tmp2, tmp2);
10216     movq(tmp3, in_out2);
10217     addq(tmp3, size);
10218 
10219     bind(L_processPartition);
10220       crc32(in_out3, Address(in_out2, 0), 8);
10221       crc32(tmp1, Address(in_out2, size), 8);
10222       crc32(tmp2, Address(in_out2, size * 2), 8);
10223       addq(in_out2, 8);
10224       cmpq(in_out2, tmp3);
10225       jcc(Assembler::less, L_processPartition);
10226     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10227             w_xtmp1, w_xtmp2, w_xtmp3,
10228             tmp4, tmp5,
10229             n_tmp6);
10230     addq(in_out2, 2 * size);
10231     subl(in_out1, 3 * size);
10232     jmp(L_processPartitions);
10233 
10234   bind(L_exit);
10235 }
10236 #else
10237 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10238                                      Register tmp1, Register tmp2, Register tmp3,
10239                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10240   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10241   if (n > 0) {
10242     addl(tmp3, n * 256 * 8);
10243   }
10244   //    Q1 = TABLEExt[n][B & 0xFF];
10245   movl(tmp1, in_out);
10246   andl(tmp1, 0x000000FF);
10247   shll(tmp1, 3);
10248   addl(tmp1, tmp3);
10249   movq(xtmp1, Address(tmp1, 0));
10250 
10251   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10252   movl(tmp2, in_out);
10253   shrl(tmp2, 8);
10254   andl(tmp2, 0x000000FF);
10255   shll(tmp2, 3);
10256   addl(tmp2, tmp3);
10257   movq(xtmp2, Address(tmp2, 0));
10258 
10259   psllq(xtmp2, 8);
10260   pxor(xtmp1, xtmp2);
10261 
10262   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10263   movl(tmp2, in_out);
10264   shrl(tmp2, 16);
10265   andl(tmp2, 0x000000FF);
10266   shll(tmp2, 3);
10267   addl(tmp2, tmp3);
10268   movq(xtmp2, Address(tmp2, 0));
10269 
10270   psllq(xtmp2, 16);
10271   pxor(xtmp1, xtmp2);
10272 
10273   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10274   shrl(in_out, 24);
10275   andl(in_out, 0x000000FF);
10276   shll(in_out, 3);
10277   addl(in_out, tmp3);
10278   movq(xtmp2, Address(in_out, 0));
10279 
10280   psllq(xtmp2, 24);
10281   pxor(xtmp1, xtmp2); // Result in CXMM
10282   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10283 }
10284 
10285 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10286                                       Register in_out,
10287                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10288                                       XMMRegister w_xtmp2,
10289                                       Register tmp1,
10290                                       Register n_tmp2, Register n_tmp3) {
10291   if (is_pclmulqdq_supported) {
10292     movdl(w_xtmp1, in_out);
10293 
10294     movl(tmp1, const_or_pre_comp_const_index);
10295     movdl(w_xtmp2, tmp1);
10296     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10297     // Keep result in XMM since GPR is 32 bit in length
10298   } else {
10299     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10300   }
10301 }
10302 
10303 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,
10304                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10305                                      Register tmp1, Register tmp2,
10306                                      Register n_tmp3) {
10307   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10308   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10309 
10310   psllq(w_xtmp1, 1);
10311   movdl(tmp1, w_xtmp1);
10312   psrlq(w_xtmp1, 32);
10313   movdl(in_out, w_xtmp1);
10314 
10315   xorl(tmp2, tmp2);
10316   crc32(tmp2, tmp1, 4);
10317   xorl(in_out, tmp2);
10318 
10319   psllq(w_xtmp2, 1);
10320   movdl(tmp1, w_xtmp2);
10321   psrlq(w_xtmp2, 32);
10322   movdl(in1, w_xtmp2);
10323 
10324   xorl(tmp2, tmp2);
10325   crc32(tmp2, tmp1, 4);
10326   xorl(in1, tmp2);
10327   xorl(in_out, in1);
10328   xorl(in_out, in2);
10329 }
10330 
10331 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,
10332                                        Register in_out1, Register in_out2, Register in_out3,
10333                                        Register tmp1, Register tmp2, Register tmp3,
10334                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10335                                        Register tmp4, Register tmp5,
10336                                        Register n_tmp6) {
10337   Label L_processPartitions;
10338   Label L_processPartition;
10339   Label L_exit;
10340 
10341   bind(L_processPartitions);
10342   cmpl(in_out1, 3 * size);
10343   jcc(Assembler::less, L_exit);
10344     xorl(tmp1, tmp1);
10345     xorl(tmp2, tmp2);
10346     movl(tmp3, in_out2);
10347     addl(tmp3, size);
10348 
10349     bind(L_processPartition);
10350       crc32(in_out3, Address(in_out2, 0), 4);
10351       crc32(tmp1, Address(in_out2, size), 4);
10352       crc32(tmp2, Address(in_out2, size*2), 4);
10353       crc32(in_out3, Address(in_out2, 0+4), 4);
10354       crc32(tmp1, Address(in_out2, size+4), 4);
10355       crc32(tmp2, Address(in_out2, size*2+4), 4);
10356       addl(in_out2, 8);
10357       cmpl(in_out2, tmp3);
10358       jcc(Assembler::less, L_processPartition);
10359 
10360         push(tmp3);
10361         push(in_out1);
10362         push(in_out2);
10363         tmp4 = tmp3;
10364         tmp5 = in_out1;
10365         n_tmp6 = in_out2;
10366 
10367       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10368             w_xtmp1, w_xtmp2, w_xtmp3,
10369             tmp4, tmp5,
10370             n_tmp6);
10371 
10372         pop(in_out2);
10373         pop(in_out1);
10374         pop(tmp3);
10375 
10376     addl(in_out2, 2 * size);
10377     subl(in_out1, 3 * size);
10378     jmp(L_processPartitions);
10379 
10380   bind(L_exit);
10381 }
10382 #endif //LP64
10383 
10384 #ifdef _LP64
10385 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10386 // Input: A buffer I of L bytes.
10387 // Output: the CRC32C value of the buffer.
10388 // Notations:
10389 // Write L = 24N + r, with N = floor (L/24).
10390 // r = L mod 24 (0 <= r < 24).
10391 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10392 // N quadwords, and R consists of r bytes.
10393 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10394 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10395 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10396 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10397 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10398                                           Register tmp1, Register tmp2, Register tmp3,
10399                                           Register tmp4, Register tmp5, Register tmp6,
10400                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10401                                           bool is_pclmulqdq_supported) {
10402   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10403   Label L_wordByWord;
10404   Label L_byteByByteProlog;
10405   Label L_byteByByte;
10406   Label L_exit;
10407 
10408   if (is_pclmulqdq_supported ) {
10409     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10410     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10411 
10412     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10413     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10414 
10415     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10416     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10417     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10418   } else {
10419     const_or_pre_comp_const_index[0] = 1;
10420     const_or_pre_comp_const_index[1] = 0;
10421 
10422     const_or_pre_comp_const_index[2] = 3;
10423     const_or_pre_comp_const_index[3] = 2;
10424 
10425     const_or_pre_comp_const_index[4] = 5;
10426     const_or_pre_comp_const_index[5] = 4;
10427    }
10428   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10429                     in2, in1, in_out,
10430                     tmp1, tmp2, tmp3,
10431                     w_xtmp1, w_xtmp2, w_xtmp3,
10432                     tmp4, tmp5,
10433                     tmp6);
10434   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10435                     in2, in1, in_out,
10436                     tmp1, tmp2, tmp3,
10437                     w_xtmp1, w_xtmp2, w_xtmp3,
10438                     tmp4, tmp5,
10439                     tmp6);
10440   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10441                     in2, in1, in_out,
10442                     tmp1, tmp2, tmp3,
10443                     w_xtmp1, w_xtmp2, w_xtmp3,
10444                     tmp4, tmp5,
10445                     tmp6);
10446   movl(tmp1, in2);
10447   andl(tmp1, 0x00000007);
10448   negl(tmp1);
10449   addl(tmp1, in2);
10450   addq(tmp1, in1);
10451 
10452   BIND(L_wordByWord);
10453   cmpq(in1, tmp1);
10454   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10455     crc32(in_out, Address(in1, 0), 4);
10456     addq(in1, 4);
10457     jmp(L_wordByWord);
10458 
10459   BIND(L_byteByByteProlog);
10460   andl(in2, 0x00000007);
10461   movl(tmp2, 1);
10462 
10463   BIND(L_byteByByte);
10464   cmpl(tmp2, in2);
10465   jccb(Assembler::greater, L_exit);
10466     crc32(in_out, Address(in1, 0), 1);
10467     incq(in1);
10468     incl(tmp2);
10469     jmp(L_byteByByte);
10470 
10471   BIND(L_exit);
10472 }
10473 #else
10474 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10475                                           Register tmp1, Register  tmp2, Register tmp3,
10476                                           Register tmp4, Register  tmp5, Register tmp6,
10477                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10478                                           bool is_pclmulqdq_supported) {
10479   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10480   Label L_wordByWord;
10481   Label L_byteByByteProlog;
10482   Label L_byteByByte;
10483   Label L_exit;
10484 
10485   if (is_pclmulqdq_supported) {
10486     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10487     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10488 
10489     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10490     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10491 
10492     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10493     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10494   } else {
10495     const_or_pre_comp_const_index[0] = 1;
10496     const_or_pre_comp_const_index[1] = 0;
10497 
10498     const_or_pre_comp_const_index[2] = 3;
10499     const_or_pre_comp_const_index[3] = 2;
10500 
10501     const_or_pre_comp_const_index[4] = 5;
10502     const_or_pre_comp_const_index[5] = 4;
10503   }
10504   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10505                     in2, in1, in_out,
10506                     tmp1, tmp2, tmp3,
10507                     w_xtmp1, w_xtmp2, w_xtmp3,
10508                     tmp4, tmp5,
10509                     tmp6);
10510   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10511                     in2, in1, in_out,
10512                     tmp1, tmp2, tmp3,
10513                     w_xtmp1, w_xtmp2, w_xtmp3,
10514                     tmp4, tmp5,
10515                     tmp6);
10516   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10517                     in2, in1, in_out,
10518                     tmp1, tmp2, tmp3,
10519                     w_xtmp1, w_xtmp2, w_xtmp3,
10520                     tmp4, tmp5,
10521                     tmp6);
10522   movl(tmp1, in2);
10523   andl(tmp1, 0x00000007);
10524   negl(tmp1);
10525   addl(tmp1, in2);
10526   addl(tmp1, in1);
10527 
10528   BIND(L_wordByWord);
10529   cmpl(in1, tmp1);
10530   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10531     crc32(in_out, Address(in1,0), 4);
10532     addl(in1, 4);
10533     jmp(L_wordByWord);
10534 
10535   BIND(L_byteByByteProlog);
10536   andl(in2, 0x00000007);
10537   movl(tmp2, 1);
10538 
10539   BIND(L_byteByByte);
10540   cmpl(tmp2, in2);
10541   jccb(Assembler::greater, L_exit);
10542     movb(tmp1, Address(in1, 0));
10543     crc32(in_out, tmp1, 1);
10544     incl(in1);
10545     incl(tmp2);
10546     jmp(L_byteByByte);
10547 
10548   BIND(L_exit);
10549 }
10550 #endif // LP64
10551 #undef BIND
10552 #undef BLOCK_COMMENT
10553 
10554 // Compress char[] array to byte[].
10555 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10556 //   @HotSpotIntrinsicCandidate
10557 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10558 //     for (int i = 0; i < len; i++) {
10559 //       int c = src[srcOff++];
10560 //       if (c >>> 8 != 0) {
10561 //         return 0;
10562 //       }
10563 //       dst[dstOff++] = (byte)c;
10564 //     }
10565 //     return len;
10566 //   }
10567 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10568   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10569   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10570   Register tmp5, Register result) {
10571   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10572 
10573   // rsi: src
10574   // rdi: dst
10575   // rdx: len
10576   // rcx: tmp5
10577   // rax: result
10578 
10579   // rsi holds start addr of source char[] to be compressed
10580   // rdi holds start addr of destination byte[]
10581   // rdx holds length
10582 
10583   assert(len != result, "");
10584 
10585   // save length for return
10586   push(len);
10587 
10588   if ((UseAVX > 2) && // AVX512
10589     VM_Version::supports_avx512vlbw() &&
10590     VM_Version::supports_bmi2()) {
10591 
10592     set_vector_masking();  // opening of the stub context for programming mask registers
10593 
10594     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10595 
10596     // alignement
10597     Label post_alignement;
10598 
10599     // if length of the string is less than 16, handle it in an old fashioned
10600     // way
10601     testl(len, -32);
10602     jcc(Assembler::zero, below_threshold);
10603 
10604     // First check whether a character is compressable ( <= 0xFF).
10605     // Create mask to test for Unicode chars inside zmm vector
10606     movl(result, 0x00FF);
10607     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10608 
10609     // Save k1
10610     kmovql(k3, k1);
10611 
10612     testl(len, -64);
10613     jcc(Assembler::zero, post_alignement);
10614 
10615     movl(tmp5, dst);
10616     andl(tmp5, (32 - 1));
10617     negl(tmp5);
10618     andl(tmp5, (32 - 1));
10619 
10620     // bail out when there is nothing to be done
10621     testl(tmp5, 0xFFFFFFFF);
10622     jcc(Assembler::zero, post_alignement);
10623 
10624     // ~(~0 << len), where len is the # of remaining elements to process
10625     movl(result, 0xFFFFFFFF);
10626     shlxl(result, result, tmp5);
10627     notl(result);
10628     kmovdl(k1, result);
10629 
10630     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10631     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10632     ktestd(k2, k1);
10633     jcc(Assembler::carryClear, restore_k1_return_zero);
10634 
10635     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10636 
10637     addptr(src, tmp5);
10638     addptr(src, tmp5);
10639     addptr(dst, tmp5);
10640     subl(len, tmp5);
10641 
10642     bind(post_alignement);
10643     // end of alignement
10644 
10645     movl(tmp5, len);
10646     andl(tmp5, (32 - 1));    // tail count (in chars)
10647     andl(len, ~(32 - 1));    // vector count (in chars)
10648     jcc(Assembler::zero, copy_loop_tail);
10649 
10650     lea(src, Address(src, len, Address::times_2));
10651     lea(dst, Address(dst, len, Address::times_1));
10652     negptr(len);
10653 
10654     bind(copy_32_loop);
10655     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10656     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10657     kortestdl(k2, k2);
10658     jcc(Assembler::carryClear, restore_k1_return_zero);
10659 
10660     // All elements in current processed chunk are valid candidates for
10661     // compression. Write a truncated byte elements to the memory.
10662     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10663     addptr(len, 32);
10664     jcc(Assembler::notZero, copy_32_loop);
10665 
10666     bind(copy_loop_tail);
10667     // bail out when there is nothing to be done
10668     testl(tmp5, 0xFFFFFFFF);
10669     // Restore k1
10670     kmovql(k1, k3);
10671     jcc(Assembler::zero, return_length);
10672 
10673     movl(len, tmp5);
10674 
10675     // ~(~0 << len), where len is the # of remaining elements to process
10676     movl(result, 0xFFFFFFFF);
10677     shlxl(result, result, len);
10678     notl(result);
10679 
10680     kmovdl(k1, result);
10681 
10682     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10683     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10684     ktestd(k2, k1);
10685     jcc(Assembler::carryClear, restore_k1_return_zero);
10686 
10687     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10688     // Restore k1
10689     kmovql(k1, k3);
10690     jmp(return_length);
10691 
10692     bind(restore_k1_return_zero);
10693     // Restore k1
10694     kmovql(k1, k3);
10695     jmp(return_zero);
10696 
10697     clear_vector_masking();   // closing of the stub context for programming mask registers
10698   }
10699   if (UseSSE42Intrinsics) {
10700     Label copy_32_loop, copy_16, copy_tail;
10701 
10702     bind(below_threshold);
10703 
10704     movl(result, len);
10705 
10706     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10707 
10708     // vectored compression
10709     andl(len, 0xfffffff0);    // vector count (in chars)
10710     andl(result, 0x0000000f);    // tail count (in chars)
10711     testl(len, len);
10712     jccb(Assembler::zero, copy_16);
10713 
10714     // compress 16 chars per iter
10715     movdl(tmp1Reg, tmp5);
10716     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10717     pxor(tmp4Reg, tmp4Reg);
10718 
10719     lea(src, Address(src, len, Address::times_2));
10720     lea(dst, Address(dst, len, Address::times_1));
10721     negptr(len);
10722 
10723     bind(copy_32_loop);
10724     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10725     por(tmp4Reg, tmp2Reg);
10726     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10727     por(tmp4Reg, tmp3Reg);
10728     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10729     jcc(Assembler::notZero, return_zero);
10730     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10731     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10732     addptr(len, 16);
10733     jcc(Assembler::notZero, copy_32_loop);
10734 
10735     // compress next vector of 8 chars (if any)
10736     bind(copy_16);
10737     movl(len, result);
10738     andl(len, 0xfffffff8);    // vector count (in chars)
10739     andl(result, 0x00000007);    // tail count (in chars)
10740     testl(len, len);
10741     jccb(Assembler::zero, copy_tail);
10742 
10743     movdl(tmp1Reg, tmp5);
10744     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10745     pxor(tmp3Reg, tmp3Reg);
10746 
10747     movdqu(tmp2Reg, Address(src, 0));
10748     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10749     jccb(Assembler::notZero, return_zero);
10750     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10751     movq(Address(dst, 0), tmp2Reg);
10752     addptr(src, 16);
10753     addptr(dst, 8);
10754 
10755     bind(copy_tail);
10756     movl(len, result);
10757   }
10758   // compress 1 char per iter
10759   testl(len, len);
10760   jccb(Assembler::zero, return_length);
10761   lea(src, Address(src, len, Address::times_2));
10762   lea(dst, Address(dst, len, Address::times_1));
10763   negptr(len);
10764 
10765   bind(copy_chars_loop);
10766   load_unsigned_short(result, Address(src, len, Address::times_2));
10767   testl(result, 0xff00);      // check if Unicode char
10768   jccb(Assembler::notZero, return_zero);
10769   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10770   increment(len);
10771   jcc(Assembler::notZero, copy_chars_loop);
10772 
10773   // if compression succeeded, return length
10774   bind(return_length);
10775   pop(result);
10776   jmpb(done);
10777 
10778   // if compression failed, return 0
10779   bind(return_zero);
10780   xorl(result, result);
10781   addptr(rsp, wordSize);
10782 
10783   bind(done);
10784 }
10785 
10786 // Inflate byte[] array to char[].
10787 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
10788 //   @HotSpotIntrinsicCandidate
10789 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
10790 //     for (int i = 0; i < len; i++) {
10791 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
10792 //     }
10793 //   }
10794 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10795   XMMRegister tmp1, Register tmp2) {
10796   Label copy_chars_loop, done, below_threshold;
10797   // rsi: src
10798   // rdi: dst
10799   // rdx: len
10800   // rcx: tmp2
10801 
10802   // rsi holds start addr of source byte[] to be inflated
10803   // rdi holds start addr of destination char[]
10804   // rdx holds length
10805   assert_different_registers(src, dst, len, tmp2);
10806 
10807   if ((UseAVX > 2) && // AVX512
10808     VM_Version::supports_avx512vlbw() &&
10809     VM_Version::supports_bmi2()) {
10810 
10811     set_vector_masking();  // opening of the stub context for programming mask registers
10812 
10813     Label copy_32_loop, copy_tail;
10814     Register tmp3_aliased = len;
10815 
10816     // if length of the string is less than 16, handle it in an old fashioned
10817     // way
10818     testl(len, -16);
10819     jcc(Assembler::zero, below_threshold);
10820 
10821     // In order to use only one arithmetic operation for the main loop we use
10822     // this pre-calculation
10823     movl(tmp2, len);
10824     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
10825     andl(len, -32);     // vector count
10826     jccb(Assembler::zero, copy_tail);
10827 
10828     lea(src, Address(src, len, Address::times_1));
10829     lea(dst, Address(dst, len, Address::times_2));
10830     negptr(len);
10831 
10832 
10833     // inflate 32 chars per iter
10834     bind(copy_32_loop);
10835     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
10836     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
10837     addptr(len, 32);
10838     jcc(Assembler::notZero, copy_32_loop);
10839 
10840     bind(copy_tail);
10841     // bail out when there is nothing to be done
10842     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
10843     jcc(Assembler::zero, done);
10844 
10845     // Save k1
10846     kmovql(k2, k1);
10847 
10848     // ~(~0 << length), where length is the # of remaining elements to process
10849     movl(tmp3_aliased, -1);
10850     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
10851     notl(tmp3_aliased);
10852     kmovdl(k1, tmp3_aliased);
10853     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
10854     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
10855 
10856     // Restore k1
10857     kmovql(k1, k2);
10858     jmp(done);
10859 
10860     clear_vector_masking();   // closing of the stub context for programming mask registers
10861   }
10862   if (UseSSE42Intrinsics) {
10863     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
10864 
10865     movl(tmp2, len);
10866 
10867     if (UseAVX > 1) {
10868       andl(tmp2, (16 - 1));
10869       andl(len, -16);
10870       jccb(Assembler::zero, copy_new_tail);
10871     } else {
10872       andl(tmp2, 0x00000007);   // tail count (in chars)
10873       andl(len, 0xfffffff8);    // vector count (in chars)
10874       jccb(Assembler::zero, copy_tail);
10875     }
10876 
10877     // vectored inflation
10878     lea(src, Address(src, len, Address::times_1));
10879     lea(dst, Address(dst, len, Address::times_2));
10880     negptr(len);
10881 
10882     if (UseAVX > 1) {
10883       bind(copy_16_loop);
10884       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
10885       vmovdqu(Address(dst, len, Address::times_2), tmp1);
10886       addptr(len, 16);
10887       jcc(Assembler::notZero, copy_16_loop);
10888 
10889       bind(below_threshold);
10890       bind(copy_new_tail);
10891       if ((UseAVX > 2) &&
10892         VM_Version::supports_avx512vlbw() &&
10893         VM_Version::supports_bmi2()) {
10894         movl(tmp2, len);
10895       } else {
10896         movl(len, tmp2);
10897       }
10898       andl(tmp2, 0x00000007);
10899       andl(len, 0xFFFFFFF8);
10900       jccb(Assembler::zero, copy_tail);
10901 
10902       pmovzxbw(tmp1, Address(src, 0));
10903       movdqu(Address(dst, 0), tmp1);
10904       addptr(src, 8);
10905       addptr(dst, 2 * 8);
10906 
10907       jmp(copy_tail, true);
10908     }
10909 
10910     // inflate 8 chars per iter
10911     bind(copy_8_loop);
10912     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10913     movdqu(Address(dst, len, Address::times_2), tmp1);
10914     addptr(len, 8);
10915     jcc(Assembler::notZero, copy_8_loop);
10916 
10917     bind(copy_tail);
10918     movl(len, tmp2);
10919 
10920     cmpl(len, 4);
10921     jccb(Assembler::less, copy_bytes);
10922 
10923     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10924     pmovzxbw(tmp1, tmp1);
10925     movq(Address(dst, 0), tmp1);
10926     subptr(len, 4);
10927     addptr(src, 4);
10928     addptr(dst, 8);
10929 
10930     bind(copy_bytes);
10931   }
10932   testl(len, len);
10933   jccb(Assembler::zero, done);
10934   lea(src, Address(src, len, Address::times_1));
10935   lea(dst, Address(dst, len, Address::times_2));
10936   negptr(len);
10937 
10938   // inflate 1 char per iter
10939   bind(copy_chars_loop);
10940   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10941   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10942   increment(len);
10943   jcc(Assembler::notZero, copy_chars_loop);
10944 
10945   bind(done);
10946 }
10947 
10948 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10949   switch (cond) {
10950     // Note some conditions are synonyms for others
10951     case Assembler::zero:         return Assembler::notZero;
10952     case Assembler::notZero:      return Assembler::zero;
10953     case Assembler::less:         return Assembler::greaterEqual;
10954     case Assembler::lessEqual:    return Assembler::greater;
10955     case Assembler::greater:      return Assembler::lessEqual;
10956     case Assembler::greaterEqual: return Assembler::less;
10957     case Assembler::below:        return Assembler::aboveEqual;
10958     case Assembler::belowEqual:   return Assembler::above;
10959     case Assembler::above:        return Assembler::belowEqual;
10960     case Assembler::aboveEqual:   return Assembler::below;
10961     case Assembler::overflow:     return Assembler::noOverflow;
10962     case Assembler::noOverflow:   return Assembler::overflow;
10963     case Assembler::negative:     return Assembler::positive;
10964     case Assembler::positive:     return Assembler::negative;
10965     case Assembler::parity:       return Assembler::noParity;
10966     case Assembler::noParity:     return Assembler::parity;
10967   }
10968   ShouldNotReachHere(); return Assembler::overflow;
10969 }
10970 
10971 SkipIfEqual::SkipIfEqual(
10972     MacroAssembler* masm, const bool* flag_addr, bool value) {
10973   _masm = masm;
10974   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10975   _masm->jcc(Assembler::equal, _label);
10976 }
10977 
10978 SkipIfEqual::~SkipIfEqual() {
10979   _masm->bind(_label);
10980 }
10981 
10982 // 32-bit Windows has its own fast-path implementation
10983 // of get_thread
10984 #if !defined(WIN32) || defined(_LP64)
10985 
10986 // This is simply a call to Thread::current()
10987 void MacroAssembler::get_thread(Register thread) {
10988   if (thread != rax) {
10989     push(rax);
10990   }
10991   LP64_ONLY(push(rdi);)
10992   LP64_ONLY(push(rsi);)
10993   push(rdx);
10994   push(rcx);
10995 #ifdef _LP64
10996   push(r8);
10997   push(r9);
10998   push(r10);
10999   push(r11);
11000 #endif
11001 
11002   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11003 
11004 #ifdef _LP64
11005   pop(r11);
11006   pop(r10);
11007   pop(r9);
11008   pop(r8);
11009 #endif
11010   pop(rcx);
11011   pop(rdx);
11012   LP64_ONLY(pop(rsi);)
11013   LP64_ONLY(pop(rdi);)
11014   if (thread != rax) {
11015     mov(thread, rax);
11016     pop(rax);
11017   }
11018 }
11019 
11020 #endif