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/access.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(Address src1, jobject obj) {
 122   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 123 }
 124 
 125 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 126   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 127 }
 128 
 129 void MacroAssembler::extend_sign(Register hi, Register lo) {
 130   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 131   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 132     cdql();
 133   } else {
 134     movl(hi, lo);
 135     sarl(hi, 31);
 136   }
 137 }
 138 
 139 void MacroAssembler::jC2(Register tmp, Label& L) {
 140   // set parity bit if FPU flag C2 is set (via rax)
 141   save_rax(tmp);
 142   fwait(); fnstsw_ax();
 143   sahf();
 144   restore_rax(tmp);
 145   // branch
 146   jcc(Assembler::parity, L);
 147 }
 148 
 149 void MacroAssembler::jnC2(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::noParity, L);
 157 }
 158 
 159 // 32bit can do a case table jump in one instruction but we no longer allow the base
 160 // to be installed in the Address class
 161 void MacroAssembler::jump(ArrayAddress entry) {
 162   jmp(as_Address(entry));
 163 }
 164 
 165 // Note: y_lo will be destroyed
 166 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 167   // Long compare for Java (semantics as described in JVM spec.)
 168   Label high, low, done;
 169 
 170   cmpl(x_hi, y_hi);
 171   jcc(Assembler::less, low);
 172   jcc(Assembler::greater, high);
 173   // x_hi is the return register
 174   xorl(x_hi, x_hi);
 175   cmpl(x_lo, y_lo);
 176   jcc(Assembler::below, low);
 177   jcc(Assembler::equal, done);
 178 
 179   bind(high);
 180   xorl(x_hi, x_hi);
 181   increment(x_hi);
 182   jmp(done);
 183 
 184   bind(low);
 185   xorl(x_hi, x_hi);
 186   decrementl(x_hi);
 187 
 188   bind(done);
 189 }
 190 
 191 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 192     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 193 }
 194 
 195 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 196   // leal(dst, as_Address(adr));
 197   // see note in movl as to why we must use a move
 198   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 199 }
 200 
 201 void MacroAssembler::leave() {
 202   mov(rsp, rbp);
 203   pop(rbp);
 204 }
 205 
 206 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 207   // Multiplication of two Java long values stored on the stack
 208   // as illustrated below. Result is in rdx:rax.
 209   //
 210   // rsp ---> [  ??  ] \               \
 211   //            ....    | y_rsp_offset  |
 212   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 213   //          [ y_hi ]                  | (in bytes)
 214   //            ....                    |
 215   //          [ x_lo ]                 /
 216   //          [ x_hi ]
 217   //            ....
 218   //
 219   // Basic idea: lo(result) = lo(x_lo * y_lo)
 220   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 221   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 222   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 223   Label quick;
 224   // load x_hi, y_hi and check if quick
 225   // multiplication is possible
 226   movl(rbx, x_hi);
 227   movl(rcx, y_hi);
 228   movl(rax, rbx);
 229   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 230   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 231   // do full multiplication
 232   // 1st step
 233   mull(y_lo);                                    // x_hi * y_lo
 234   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 235   // 2nd step
 236   movl(rax, x_lo);
 237   mull(rcx);                                     // x_lo * y_hi
 238   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 239   // 3rd step
 240   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 241   movl(rax, x_lo);
 242   mull(y_lo);                                    // x_lo * y_lo
 243   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 244 }
 245 
 246 void MacroAssembler::lneg(Register hi, Register lo) {
 247   negl(lo);
 248   adcl(hi, 0);
 249   negl(hi);
 250 }
 251 
 252 void MacroAssembler::lshl(Register hi, Register lo) {
 253   // Java shift left long support (semantics as described in JVM spec., p.305)
 254   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 255   // shift value is in rcx !
 256   assert(hi != rcx, "must not use rcx");
 257   assert(lo != rcx, "must not use rcx");
 258   const Register s = rcx;                        // shift count
 259   const int      n = BitsPerWord;
 260   Label L;
 261   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 262   cmpl(s, n);                                    // if (s < n)
 263   jcc(Assembler::less, L);                       // else (s >= n)
 264   movl(hi, lo);                                  // x := x << n
 265   xorl(lo, lo);
 266   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 267   bind(L);                                       // s (mod n) < n
 268   shldl(hi, lo);                                 // x := x << s
 269   shll(lo);
 270 }
 271 
 272 
 273 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 274   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 275   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 276   assert(hi != rcx, "must not use rcx");
 277   assert(lo != rcx, "must not use rcx");
 278   const Register s = rcx;                        // shift count
 279   const int      n = BitsPerWord;
 280   Label L;
 281   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 282   cmpl(s, n);                                    // if (s < n)
 283   jcc(Assembler::less, L);                       // else (s >= n)
 284   movl(lo, hi);                                  // x := x >> n
 285   if (sign_extension) sarl(hi, 31);
 286   else                xorl(hi, hi);
 287   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 288   bind(L);                                       // s (mod n) < n
 289   shrdl(lo, hi);                                 // x := x >> s
 290   if (sign_extension) sarl(hi);
 291   else                shrl(hi);
 292 }
 293 
 294 void MacroAssembler::movoop(Register dst, jobject obj) {
 295   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 296 }
 297 
 298 void MacroAssembler::movoop(Address dst, jobject obj) {
 299   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 300 }
 301 
 302 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 303   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 304 }
 305 
 306 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 307   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 308 }
 309 
 310 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 311   // scratch register is not used,
 312   // it is defined to match parameters of 64-bit version of this method.
 313   if (src.is_lval()) {
 314     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 315   } else {
 316     movl(dst, as_Address(src));
 317   }
 318 }
 319 
 320 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 321   movl(as_Address(dst), src);
 322 }
 323 
 324 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 325   movl(dst, as_Address(src));
 326 }
 327 
 328 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 329 void MacroAssembler::movptr(Address dst, intptr_t src) {
 330   movl(dst, src);
 331 }
 332 
 333 
 334 void MacroAssembler::pop_callee_saved_registers() {
 335   pop(rcx);
 336   pop(rdx);
 337   pop(rdi);
 338   pop(rsi);
 339 }
 340 
 341 void MacroAssembler::pop_fTOS() {
 342   fld_d(Address(rsp, 0));
 343   addl(rsp, 2 * wordSize);
 344 }
 345 
 346 void MacroAssembler::push_callee_saved_registers() {
 347   push(rsi);
 348   push(rdi);
 349   push(rdx);
 350   push(rcx);
 351 }
 352 
 353 void MacroAssembler::push_fTOS() {
 354   subl(rsp, 2 * wordSize);
 355   fstp_d(Address(rsp, 0));
 356 }
 357 
 358 
 359 void MacroAssembler::pushoop(jobject obj) {
 360   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 361 }
 362 
 363 void MacroAssembler::pushklass(Metadata* obj) {
 364   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 365 }
 366 
 367 void MacroAssembler::pushptr(AddressLiteral src) {
 368   if (src.is_lval()) {
 369     push_literal32((int32_t)src.target(), src.rspec());
 370   } else {
 371     pushl(as_Address(src));
 372   }
 373 }
 374 
 375 void MacroAssembler::set_word_if_not_zero(Register dst) {
 376   xorl(dst, dst);
 377   set_byte_if_not_zero(dst);
 378 }
 379 
 380 static void pass_arg0(MacroAssembler* masm, Register arg) {
 381   masm->push(arg);
 382 }
 383 
 384 static void pass_arg1(MacroAssembler* masm, Register arg) {
 385   masm->push(arg);
 386 }
 387 
 388 static void pass_arg2(MacroAssembler* masm, Register arg) {
 389   masm->push(arg);
 390 }
 391 
 392 static void pass_arg3(MacroAssembler* masm, Register arg) {
 393   masm->push(arg);
 394 }
 395 
 396 #ifndef PRODUCT
 397 extern "C" void findpc(intptr_t x);
 398 #endif
 399 
 400 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 401   // In order to get locks to work, we need to fake a in_VM state
 402   JavaThread* thread = JavaThread::current();
 403   JavaThreadState saved_state = thread->thread_state();
 404   thread->set_thread_state(_thread_in_vm);
 405   if (ShowMessageBoxOnError) {
 406     JavaThread* thread = JavaThread::current();
 407     JavaThreadState saved_state = thread->thread_state();
 408     thread->set_thread_state(_thread_in_vm);
 409     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 410       ttyLocker ttyl;
 411       BytecodeCounter::print();
 412     }
 413     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 414     // This is the value of eip which points to where verify_oop will return.
 415     if (os::message_box(msg, "Execution stopped, print registers?")) {
 416       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 417       BREAKPOINT;
 418     }
 419   } else {
 420     ttyLocker ttyl;
 421     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 422   }
 423   // Don't assert holding the ttyLock
 424     assert(false, "DEBUG MESSAGE: %s", msg);
 425   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 426 }
 427 
 428 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 429   ttyLocker ttyl;
 430   FlagSetting fs(Debugging, true);
 431   tty->print_cr("eip = 0x%08x", eip);
 432 #ifndef PRODUCT
 433   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 434     tty->cr();
 435     findpc(eip);
 436     tty->cr();
 437   }
 438 #endif
 439 #define PRINT_REG(rax) \
 440   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 441   PRINT_REG(rax);
 442   PRINT_REG(rbx);
 443   PRINT_REG(rcx);
 444   PRINT_REG(rdx);
 445   PRINT_REG(rdi);
 446   PRINT_REG(rsi);
 447   PRINT_REG(rbp);
 448   PRINT_REG(rsp);
 449 #undef PRINT_REG
 450   // Print some words near top of staack.
 451   int* dump_sp = (int*) rsp;
 452   for (int col1 = 0; col1 < 8; col1++) {
 453     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 454     os::print_location(tty, *dump_sp++);
 455   }
 456   for (int row = 0; row < 16; row++) {
 457     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 458     for (int col = 0; col < 8; col++) {
 459       tty->print(" 0x%08x", *dump_sp++);
 460     }
 461     tty->cr();
 462   }
 463   // Print some instructions around pc:
 464   Disassembler::decode((address)eip-64, (address)eip);
 465   tty->print_cr("--------");
 466   Disassembler::decode((address)eip, (address)eip+32);
 467 }
 468 
 469 void MacroAssembler::stop(const char* msg) {
 470   ExternalAddress message((address)msg);
 471   // push address of message
 472   pushptr(message.addr());
 473   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 474   pusha();                                            // push registers
 475   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 476   hlt();
 477 }
 478 
 479 void MacroAssembler::warn(const char* msg) {
 480   push_CPU_state();
 481 
 482   ExternalAddress message((address) msg);
 483   // push address of message
 484   pushptr(message.addr());
 485 
 486   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 487   addl(rsp, wordSize);       // discard argument
 488   pop_CPU_state();
 489 }
 490 
 491 void MacroAssembler::print_state() {
 492   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 493   pusha();                                            // push registers
 494 
 495   push_CPU_state();
 496   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 497   pop_CPU_state();
 498 
 499   popa();
 500   addl(rsp, wordSize);
 501 }
 502 
 503 #else // _LP64
 504 
 505 // 64 bit versions
 506 
 507 Address MacroAssembler::as_Address(AddressLiteral adr) {
 508   // amd64 always does this as a pc-rel
 509   // we can be absolute or disp based on the instruction type
 510   // jmp/call are displacements others are absolute
 511   assert(!adr.is_lval(), "must be rval");
 512   assert(reachable(adr), "must be");
 513   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 514 
 515 }
 516 
 517 Address MacroAssembler::as_Address(ArrayAddress adr) {
 518   AddressLiteral base = adr.base();
 519   lea(rscratch1, base);
 520   Address index = adr.index();
 521   assert(index._disp == 0, "must not have disp"); // maybe it can?
 522   Address array(rscratch1, index._index, index._scale, index._disp);
 523   return array;
 524 }
 525 
 526 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 527   Label L, E;
 528 
 529 #ifdef _WIN64
 530   // Windows always allocates space for it's register args
 531   assert(num_args <= 4, "only register arguments supported");
 532   subq(rsp,  frame::arg_reg_save_area_bytes);
 533 #endif
 534 
 535   // Align stack if necessary
 536   testl(rsp, 15);
 537   jcc(Assembler::zero, L);
 538 
 539   subq(rsp, 8);
 540   {
 541     call(RuntimeAddress(entry_point));
 542   }
 543   addq(rsp, 8);
 544   jmp(E);
 545 
 546   bind(L);
 547   {
 548     call(RuntimeAddress(entry_point));
 549   }
 550 
 551   bind(E);
 552 
 553 #ifdef _WIN64
 554   // restore stack pointer
 555   addq(rsp, frame::arg_reg_save_area_bytes);
 556 #endif
 557 
 558 }
 559 
 560 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 561   assert(!src2.is_lval(), "should use cmpptr");
 562 
 563   if (reachable(src2)) {
 564     cmpq(src1, as_Address(src2));
 565   } else {
 566     lea(rscratch1, src2);
 567     Assembler::cmpq(src1, Address(rscratch1, 0));
 568   }
 569 }
 570 
 571 int MacroAssembler::corrected_idivq(Register reg) {
 572   // Full implementation of Java ldiv and lrem; checks for special
 573   // case as described in JVM spec., p.243 & p.271.  The function
 574   // returns the (pc) offset of the idivl instruction - may be needed
 575   // for implicit exceptions.
 576   //
 577   //         normal case                           special case
 578   //
 579   // input : rax: dividend                         min_long
 580   //         reg: divisor   (may not be eax/edx)   -1
 581   //
 582   // output: rax: quotient  (= rax idiv reg)       min_long
 583   //         rdx: remainder (= rax irem reg)       0
 584   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 585   static const int64_t min_long = 0x8000000000000000;
 586   Label normal_case, special_case;
 587 
 588   // check for special case
 589   cmp64(rax, ExternalAddress((address) &min_long));
 590   jcc(Assembler::notEqual, normal_case);
 591   xorl(rdx, rdx); // prepare rdx for possible special case (where
 592                   // remainder = 0)
 593   cmpq(reg, -1);
 594   jcc(Assembler::equal, special_case);
 595 
 596   // handle normal case
 597   bind(normal_case);
 598   cdqq();
 599   int idivq_offset = offset();
 600   idivq(reg);
 601 
 602   // normal and special case exit
 603   bind(special_case);
 604 
 605   return idivq_offset;
 606 }
 607 
 608 void MacroAssembler::decrementq(Register reg, int value) {
 609   if (value == min_jint) { subq(reg, value); return; }
 610   if (value <  0) { incrementq(reg, -value); return; }
 611   if (value == 0) {                        ; return; }
 612   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 613   /* else */      { subq(reg, value)       ; return; }
 614 }
 615 
 616 void MacroAssembler::decrementq(Address dst, int value) {
 617   if (value == min_jint) { subq(dst, value); return; }
 618   if (value <  0) { incrementq(dst, -value); return; }
 619   if (value == 0) {                        ; return; }
 620   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 621   /* else */      { subq(dst, value)       ; return; }
 622 }
 623 
 624 void MacroAssembler::incrementq(AddressLiteral dst) {
 625   if (reachable(dst)) {
 626     incrementq(as_Address(dst));
 627   } else {
 628     lea(rscratch1, dst);
 629     incrementq(Address(rscratch1, 0));
 630   }
 631 }
 632 
 633 void MacroAssembler::incrementq(Register reg, int value) {
 634   if (value == min_jint) { addq(reg, value); return; }
 635   if (value <  0) { decrementq(reg, -value); return; }
 636   if (value == 0) {                        ; return; }
 637   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 638   /* else */      { addq(reg, value)       ; return; }
 639 }
 640 
 641 void MacroAssembler::incrementq(Address dst, int value) {
 642   if (value == min_jint) { addq(dst, value); return; }
 643   if (value <  0) { decrementq(dst, -value); return; }
 644   if (value == 0) {                        ; return; }
 645   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 646   /* else */      { addq(dst, value)       ; return; }
 647 }
 648 
 649 // 32bit can do a case table jump in one instruction but we no longer allow the base
 650 // to be installed in the Address class
 651 void MacroAssembler::jump(ArrayAddress entry) {
 652   lea(rscratch1, entry.base());
 653   Address dispatch = entry.index();
 654   assert(dispatch._base == noreg, "must be");
 655   dispatch._base = rscratch1;
 656   jmp(dispatch);
 657 }
 658 
 659 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 660   ShouldNotReachHere(); // 64bit doesn't use two regs
 661   cmpq(x_lo, y_lo);
 662 }
 663 
 664 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 665     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 666 }
 667 
 668 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 669   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 670   movptr(dst, rscratch1);
 671 }
 672 
 673 void MacroAssembler::leave() {
 674   // %%% is this really better? Why not on 32bit too?
 675   emit_int8((unsigned char)0xC9); // LEAVE
 676 }
 677 
 678 void MacroAssembler::lneg(Register hi, Register lo) {
 679   ShouldNotReachHere(); // 64bit doesn't use two regs
 680   negq(lo);
 681 }
 682 
 683 void MacroAssembler::movoop(Register dst, jobject obj) {
 684   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 685 }
 686 
 687 void MacroAssembler::movoop(Address dst, jobject obj) {
 688   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 689   movq(dst, rscratch1);
 690 }
 691 
 692 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 693   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 694 }
 695 
 696 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 697   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 698   movq(dst, rscratch1);
 699 }
 700 
 701 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 702   if (src.is_lval()) {
 703     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 704   } else {
 705     if (reachable(src)) {
 706       movq(dst, as_Address(src));
 707     } else {
 708       lea(scratch, src);
 709       movq(dst, Address(scratch, 0));
 710     }
 711   }
 712 }
 713 
 714 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 715   movq(as_Address(dst), src);
 716 }
 717 
 718 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 719   movq(dst, as_Address(src));
 720 }
 721 
 722 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 723 void MacroAssembler::movptr(Address dst, intptr_t src) {
 724   mov64(rscratch1, src);
 725   movq(dst, rscratch1);
 726 }
 727 
 728 // These are mostly for initializing NULL
 729 void MacroAssembler::movptr(Address dst, int32_t src) {
 730   movslq(dst, src);
 731 }
 732 
 733 void MacroAssembler::movptr(Register dst, int32_t src) {
 734   mov64(dst, (intptr_t)src);
 735 }
 736 
 737 void MacroAssembler::pushoop(jobject obj) {
 738   movoop(rscratch1, obj);
 739   push(rscratch1);
 740 }
 741 
 742 void MacroAssembler::pushklass(Metadata* obj) {
 743   mov_metadata(rscratch1, obj);
 744   push(rscratch1);
 745 }
 746 
 747 void MacroAssembler::pushptr(AddressLiteral src) {
 748   lea(rscratch1, src);
 749   if (src.is_lval()) {
 750     push(rscratch1);
 751   } else {
 752     pushq(Address(rscratch1, 0));
 753   }
 754 }
 755 
 756 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 757   // we must set sp to zero to clear frame
 758   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 759   // must clear fp, so that compiled frames are not confused; it is
 760   // possible that we need it only for debugging
 761   if (clear_fp) {
 762     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 763   }
 764 
 765   // Always clear the pc because it could have been set by make_walkable()
 766   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 767   vzeroupper();
 768 }
 769 
 770 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 771                                          Register last_java_fp,
 772                                          address  last_java_pc) {
 773   vzeroupper();
 774   // determine last_java_sp register
 775   if (!last_java_sp->is_valid()) {
 776     last_java_sp = rsp;
 777   }
 778 
 779   // last_java_fp is optional
 780   if (last_java_fp->is_valid()) {
 781     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 782            last_java_fp);
 783   }
 784 
 785   // last_java_pc is optional
 786   if (last_java_pc != NULL) {
 787     Address java_pc(r15_thread,
 788                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 789     lea(rscratch1, InternalAddress(last_java_pc));
 790     movptr(java_pc, rscratch1);
 791   }
 792 
 793   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 794 }
 795 
 796 static void pass_arg0(MacroAssembler* masm, Register arg) {
 797   if (c_rarg0 != arg ) {
 798     masm->mov(c_rarg0, arg);
 799   }
 800 }
 801 
 802 static void pass_arg1(MacroAssembler* masm, Register arg) {
 803   if (c_rarg1 != arg ) {
 804     masm->mov(c_rarg1, arg);
 805   }
 806 }
 807 
 808 static void pass_arg2(MacroAssembler* masm, Register arg) {
 809   if (c_rarg2 != arg ) {
 810     masm->mov(c_rarg2, arg);
 811   }
 812 }
 813 
 814 static void pass_arg3(MacroAssembler* masm, Register arg) {
 815   if (c_rarg3 != arg ) {
 816     masm->mov(c_rarg3, arg);
 817   }
 818 }
 819 
 820 void MacroAssembler::stop(const char* msg) {
 821   address rip = pc();
 822   pusha(); // get regs on stack
 823   lea(c_rarg0, ExternalAddress((address) msg));
 824   lea(c_rarg1, InternalAddress(rip));
 825   movq(c_rarg2, rsp); // pass pointer to regs array
 826   andq(rsp, -16); // align stack as required by ABI
 827   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 828   hlt();
 829 }
 830 
 831 void MacroAssembler::warn(const char* msg) {
 832   push(rbp);
 833   movq(rbp, rsp);
 834   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 835   push_CPU_state();   // keeps alignment at 16 bytes
 836   lea(c_rarg0, ExternalAddress((address) msg));
 837   lea(rax, ExternalAddress(CAST_FROM_FN_PTR(address, warning)));
 838   call(rax);
 839   pop_CPU_state();
 840   mov(rsp, rbp);
 841   pop(rbp);
 842 }
 843 
 844 void MacroAssembler::print_state() {
 845   address rip = pc();
 846   pusha();            // get regs on stack
 847   push(rbp);
 848   movq(rbp, rsp);
 849   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 850   push_CPU_state();   // keeps alignment at 16 bytes
 851 
 852   lea(c_rarg0, InternalAddress(rip));
 853   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 854   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 855 
 856   pop_CPU_state();
 857   mov(rsp, rbp);
 858   pop(rbp);
 859   popa();
 860 }
 861 
 862 #ifndef PRODUCT
 863 extern "C" void findpc(intptr_t x);
 864 #endif
 865 
 866 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 867   // In order to get locks to work, we need to fake a in_VM state
 868   if (ShowMessageBoxOnError) {
 869     JavaThread* thread = JavaThread::current();
 870     JavaThreadState saved_state = thread->thread_state();
 871     thread->set_thread_state(_thread_in_vm);
 872 #ifndef PRODUCT
 873     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 874       ttyLocker ttyl;
 875       BytecodeCounter::print();
 876     }
 877 #endif
 878     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 879     // XXX correct this offset for amd64
 880     // This is the value of eip which points to where verify_oop will return.
 881     if (os::message_box(msg, "Execution stopped, print registers?")) {
 882       print_state64(pc, regs);
 883       BREAKPOINT;
 884       assert(false, "start up GDB");
 885     }
 886     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 887   } else {
 888     ttyLocker ttyl;
 889     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 890                     msg);
 891     assert(false, "DEBUG MESSAGE: %s", msg);
 892   }
 893 }
 894 
 895 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 896   ttyLocker ttyl;
 897   FlagSetting fs(Debugging, true);
 898   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 899 #ifndef PRODUCT
 900   tty->cr();
 901   findpc(pc);
 902   tty->cr();
 903 #endif
 904 #define PRINT_REG(rax, value) \
 905   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 906   PRINT_REG(rax, regs[15]);
 907   PRINT_REG(rbx, regs[12]);
 908   PRINT_REG(rcx, regs[14]);
 909   PRINT_REG(rdx, regs[13]);
 910   PRINT_REG(rdi, regs[8]);
 911   PRINT_REG(rsi, regs[9]);
 912   PRINT_REG(rbp, regs[10]);
 913   PRINT_REG(rsp, regs[11]);
 914   PRINT_REG(r8 , regs[7]);
 915   PRINT_REG(r9 , regs[6]);
 916   PRINT_REG(r10, regs[5]);
 917   PRINT_REG(r11, regs[4]);
 918   PRINT_REG(r12, regs[3]);
 919   PRINT_REG(r13, regs[2]);
 920   PRINT_REG(r14, regs[1]);
 921   PRINT_REG(r15, regs[0]);
 922 #undef PRINT_REG
 923   // Print some words near top of staack.
 924   int64_t* rsp = (int64_t*) regs[11];
 925   int64_t* dump_sp = rsp;
 926   for (int col1 = 0; col1 < 8; col1++) {
 927     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 928     os::print_location(tty, *dump_sp++);
 929   }
 930   for (int row = 0; row < 25; row++) {
 931     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 932     for (int col = 0; col < 4; col++) {
 933       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 934     }
 935     tty->cr();
 936   }
 937   // Print some instructions around pc:
 938   Disassembler::decode((address)pc-64, (address)pc);
 939   tty->print_cr("--------");
 940   Disassembler::decode((address)pc, (address)pc+32);
 941 }
 942 
 943 #endif // _LP64
 944 
 945 // Now versions that are common to 32/64 bit
 946 
 947 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 948   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 949 }
 950 
 951 void MacroAssembler::addptr(Register dst, Register src) {
 952   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 953 }
 954 
 955 void MacroAssembler::addptr(Address dst, Register src) {
 956   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 957 }
 958 
 959 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 960   if (reachable(src)) {
 961     Assembler::addsd(dst, as_Address(src));
 962   } else {
 963     lea(rscratch1, src);
 964     Assembler::addsd(dst, Address(rscratch1, 0));
 965   }
 966 }
 967 
 968 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 969   if (reachable(src)) {
 970     addss(dst, as_Address(src));
 971   } else {
 972     lea(rscratch1, src);
 973     addss(dst, Address(rscratch1, 0));
 974   }
 975 }
 976 
 977 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 978   if (reachable(src)) {
 979     Assembler::addpd(dst, as_Address(src));
 980   } else {
 981     lea(rscratch1, src);
 982     Assembler::addpd(dst, Address(rscratch1, 0));
 983   }
 984 }
 985 
 986 void MacroAssembler::align(int modulus) {
 987   align(modulus, offset());
 988 }
 989 
 990 void MacroAssembler::align(int modulus, int target) {
 991   if (target % modulus != 0) {
 992     nop(modulus - (target % modulus));
 993   }
 994 }
 995 
 996 void MacroAssembler::push_f(XMMRegister r) {
 997   subptr(rsp, wordSize);
 998   movflt(Address(rsp, 0), r);
 999 }
1000 
1001 void MacroAssembler::pop_f(XMMRegister r) {
1002   movflt(r, Address(rsp, 0));
1003   addptr(rsp, wordSize);
1004 }
1005 
1006 void MacroAssembler::push_d(XMMRegister r) {
1007   subptr(rsp, 2 * wordSize);
1008   movdbl(Address(rsp, 0), r);
1009 }
1010 
1011 void MacroAssembler::pop_d(XMMRegister r) {
1012   movdbl(r, Address(rsp, 0));
1013   addptr(rsp, 2 * Interpreter::stackElementSize);
1014 }
1015 
1016 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
1017   // Used in sign-masking with aligned address.
1018   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1019   if (reachable(src)) {
1020     Assembler::andpd(dst, as_Address(src));
1021   } else {
1022     lea(rscratch1, src);
1023     Assembler::andpd(dst, Address(rscratch1, 0));
1024   }
1025 }
1026 
1027 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1028   // Used in sign-masking with aligned address.
1029   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1030   if (reachable(src)) {
1031     Assembler::andps(dst, as_Address(src));
1032   } else {
1033     lea(rscratch1, src);
1034     Assembler::andps(dst, Address(rscratch1, 0));
1035   }
1036 }
1037 
1038 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1039   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1040 }
1041 
1042 void MacroAssembler::atomic_incl(Address counter_addr) {
1043   if (os::is_MP())
1044     lock();
1045   incrementl(counter_addr);
1046 }
1047 
1048 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1049   if (reachable(counter_addr)) {
1050     atomic_incl(as_Address(counter_addr));
1051   } else {
1052     lea(scr, counter_addr);
1053     atomic_incl(Address(scr, 0));
1054   }
1055 }
1056 
1057 #ifdef _LP64
1058 void MacroAssembler::atomic_incq(Address counter_addr) {
1059   if (os::is_MP())
1060     lock();
1061   incrementq(counter_addr);
1062 }
1063 
1064 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1065   if (reachable(counter_addr)) {
1066     atomic_incq(as_Address(counter_addr));
1067   } else {
1068     lea(scr, counter_addr);
1069     atomic_incq(Address(scr, 0));
1070   }
1071 }
1072 #endif
1073 
1074 // Writes to stack successive pages until offset reached to check for
1075 // stack overflow + shadow pages.  This clobbers tmp.
1076 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1077   movptr(tmp, rsp);
1078   // Bang stack for total size given plus shadow page size.
1079   // Bang one page at a time because large size can bang beyond yellow and
1080   // red zones.
1081   Label loop;
1082   bind(loop);
1083   movl(Address(tmp, (-os::vm_page_size())), size );
1084   subptr(tmp, os::vm_page_size());
1085   subl(size, os::vm_page_size());
1086   jcc(Assembler::greater, loop);
1087 
1088   // Bang down shadow pages too.
1089   // At this point, (tmp-0) is the last address touched, so don't
1090   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1091   // was post-decremented.)  Skip this address by starting at i=1, and
1092   // touch a few more pages below.  N.B.  It is important to touch all
1093   // the way down including all pages in the shadow zone.
1094   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1095     // this could be any sized move but this is can be a debugging crumb
1096     // so the bigger the better.
1097     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1098   }
1099 }
1100 
1101 void MacroAssembler::reserved_stack_check() {
1102     // testing if reserved zone needs to be enabled
1103     Label no_reserved_zone_enabling;
1104     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1105     NOT_LP64(get_thread(rsi);)
1106 
1107     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1108     jcc(Assembler::below, no_reserved_zone_enabling);
1109 
1110     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1111     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1112     should_not_reach_here();
1113 
1114     bind(no_reserved_zone_enabling);
1115 }
1116 
1117 int MacroAssembler::biased_locking_enter(Register lock_reg,
1118                                          Register obj_reg,
1119                                          Register swap_reg,
1120                                          Register tmp_reg,
1121                                          bool swap_reg_contains_mark,
1122                                          Label& done,
1123                                          Label* slow_case,
1124                                          BiasedLockingCounters* counters) {
1125   assert(UseBiasedLocking, "why call this otherwise?");
1126   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1127   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1128   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1129   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1130   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1131   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1132 
1133   if (PrintBiasedLockingStatistics && counters == NULL) {
1134     counters = BiasedLocking::counters();
1135   }
1136   // Biased locking
1137   // See whether the lock is currently biased toward our thread and
1138   // whether the epoch is still valid
1139   // Note that the runtime guarantees sufficient alignment of JavaThread
1140   // pointers to allow age to be placed into low bits
1141   // First check to see whether biasing is even enabled for this object
1142   Label cas_label;
1143   int null_check_offset = -1;
1144   if (!swap_reg_contains_mark) {
1145     null_check_offset = offset();
1146     movptr(swap_reg, mark_addr);
1147   }
1148   movptr(tmp_reg, swap_reg);
1149   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1150   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1151   jcc(Assembler::notEqual, cas_label);
1152   // The bias pattern is present in the object's header. Need to check
1153   // whether the bias owner and the epoch are both still current.
1154 #ifndef _LP64
1155   // Note that because there is no current thread register on x86_32 we
1156   // need to store off the mark word we read out of the object to
1157   // avoid reloading it and needing to recheck invariants below. This
1158   // store is unfortunate but it makes the overall code shorter and
1159   // simpler.
1160   movptr(saved_mark_addr, swap_reg);
1161 #endif
1162   if (swap_reg_contains_mark) {
1163     null_check_offset = offset();
1164   }
1165   load_prototype_header(tmp_reg, obj_reg);
1166 #ifdef _LP64
1167   orptr(tmp_reg, r15_thread);
1168   xorptr(tmp_reg, swap_reg);
1169   Register header_reg = tmp_reg;
1170 #else
1171   xorptr(tmp_reg, swap_reg);
1172   get_thread(swap_reg);
1173   xorptr(swap_reg, tmp_reg);
1174   Register header_reg = swap_reg;
1175 #endif
1176   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1177   if (counters != NULL) {
1178     cond_inc32(Assembler::zero,
1179                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1180   }
1181   jcc(Assembler::equal, done);
1182 
1183   Label try_revoke_bias;
1184   Label try_rebias;
1185 
1186   // At this point we know that the header has the bias pattern and
1187   // that we are not the bias owner in the current epoch. We need to
1188   // figure out more details about the state of the header in order to
1189   // know what operations can be legally performed on the object's
1190   // header.
1191 
1192   // If the low three bits in the xor result aren't clear, that means
1193   // the prototype header is no longer biased and we have to revoke
1194   // the bias on this object.
1195   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1196   jccb(Assembler::notZero, try_revoke_bias);
1197 
1198   // Biasing is still enabled for this data type. See whether the
1199   // epoch of the current bias is still valid, meaning that the epoch
1200   // bits of the mark word are equal to the epoch bits of the
1201   // prototype header. (Note that the prototype header's epoch bits
1202   // only change at a safepoint.) If not, attempt to rebias the object
1203   // toward the current thread. Note that we must be absolutely sure
1204   // that the current epoch is invalid in order to do this because
1205   // otherwise the manipulations it performs on the mark word are
1206   // illegal.
1207   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1208   jccb(Assembler::notZero, try_rebias);
1209 
1210   // The epoch of the current bias is still valid but we know nothing
1211   // about the owner; it might be set or it might be clear. Try to
1212   // acquire the bias of the object using an atomic operation. If this
1213   // fails we will go in to the runtime to revoke the object's bias.
1214   // Note that we first construct the presumed unbiased header so we
1215   // don't accidentally blow away another thread's valid bias.
1216   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1217   andptr(swap_reg,
1218          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1219 #ifdef _LP64
1220   movptr(tmp_reg, swap_reg);
1221   orptr(tmp_reg, r15_thread);
1222 #else
1223   get_thread(tmp_reg);
1224   orptr(tmp_reg, swap_reg);
1225 #endif
1226   if (os::is_MP()) {
1227     lock();
1228   }
1229   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1230   // If the biasing toward our thread failed, this means that
1231   // another thread succeeded in biasing it toward itself and we
1232   // need to revoke that bias. The revocation will occur in the
1233   // interpreter runtime in the slow case.
1234   if (counters != NULL) {
1235     cond_inc32(Assembler::zero,
1236                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1237   }
1238   if (slow_case != NULL) {
1239     jcc(Assembler::notZero, *slow_case);
1240   }
1241   jmp(done);
1242 
1243   bind(try_rebias);
1244   // At this point we know the epoch has expired, meaning that the
1245   // current "bias owner", if any, is actually invalid. Under these
1246   // circumstances _only_, we are allowed to use the current header's
1247   // value as the comparison value when doing the cas to acquire the
1248   // bias in the current epoch. In other words, we allow transfer of
1249   // the bias from one thread to another directly in this situation.
1250   //
1251   // FIXME: due to a lack of registers we currently blow away the age
1252   // bits in this situation. Should attempt to preserve them.
1253   load_prototype_header(tmp_reg, obj_reg);
1254 #ifdef _LP64
1255   orptr(tmp_reg, r15_thread);
1256 #else
1257   get_thread(swap_reg);
1258   orptr(tmp_reg, swap_reg);
1259   movptr(swap_reg, saved_mark_addr);
1260 #endif
1261   if (os::is_MP()) {
1262     lock();
1263   }
1264   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1265   // If the biasing toward our thread failed, then another thread
1266   // succeeded in biasing it toward itself and we need to revoke that
1267   // bias. The revocation will occur in the runtime in the slow case.
1268   if (counters != NULL) {
1269     cond_inc32(Assembler::zero,
1270                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1271   }
1272   if (slow_case != NULL) {
1273     jcc(Assembler::notZero, *slow_case);
1274   }
1275   jmp(done);
1276 
1277   bind(try_revoke_bias);
1278   // The prototype mark in the klass doesn't have the bias bit set any
1279   // more, indicating that objects of this data type are not supposed
1280   // to be biased any more. We are going to try to reset the mark of
1281   // this object to the prototype value and fall through to the
1282   // CAS-based locking scheme. Note that if our CAS fails, it means
1283   // that another thread raced us for the privilege of revoking the
1284   // bias of this particular object, so it's okay to continue in the
1285   // normal locking code.
1286   //
1287   // FIXME: due to a lack of registers we currently blow away the age
1288   // bits in this situation. Should attempt to preserve them.
1289   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1290   load_prototype_header(tmp_reg, obj_reg);
1291   if (os::is_MP()) {
1292     lock();
1293   }
1294   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1295   // Fall through to the normal CAS-based lock, because no matter what
1296   // the result of the above CAS, some thread must have succeeded in
1297   // removing the bias bit from the object's header.
1298   if (counters != NULL) {
1299     cond_inc32(Assembler::zero,
1300                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1301   }
1302 
1303   bind(cas_label);
1304 
1305   return null_check_offset;
1306 }
1307 
1308 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1309   assert(UseBiasedLocking, "why call this otherwise?");
1310 
1311   // Check for biased locking unlock case, which is a no-op
1312   // Note: we do not have to check the thread ID for two reasons.
1313   // First, the interpreter checks for IllegalMonitorStateException at
1314   // a higher level. Second, if the bias was revoked while we held the
1315   // lock, the object could not be rebiased toward another thread, so
1316   // the bias bit would be clear.
1317   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1318   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1319   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1320   jcc(Assembler::equal, done);
1321 }
1322 
1323 #ifdef COMPILER2
1324 
1325 #if INCLUDE_RTM_OPT
1326 
1327 // Update rtm_counters based on abort status
1328 // input: abort_status
1329 //        rtm_counters (RTMLockingCounters*)
1330 // flags are killed
1331 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1332 
1333   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1334   if (PrintPreciseRTMLockingStatistics) {
1335     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1336       Label check_abort;
1337       testl(abort_status, (1<<i));
1338       jccb(Assembler::equal, check_abort);
1339       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1340       bind(check_abort);
1341     }
1342   }
1343 }
1344 
1345 // Branch if (random & (count-1) != 0), count is 2^n
1346 // tmp, scr and flags are killed
1347 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1348   assert(tmp == rax, "");
1349   assert(scr == rdx, "");
1350   rdtsc(); // modifies EDX:EAX
1351   andptr(tmp, count-1);
1352   jccb(Assembler::notZero, brLabel);
1353 }
1354 
1355 // Perform abort ratio calculation, set no_rtm bit if high ratio
1356 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1357 // tmpReg, rtm_counters_Reg and flags are killed
1358 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1359                                                  Register rtm_counters_Reg,
1360                                                  RTMLockingCounters* rtm_counters,
1361                                                  Metadata* method_data) {
1362   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1363 
1364   if (RTMLockingCalculationDelay > 0) {
1365     // Delay calculation
1366     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1367     testptr(tmpReg, tmpReg);
1368     jccb(Assembler::equal, L_done);
1369   }
1370   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1371   //   Aborted transactions = abort_count * 100
1372   //   All transactions = total_count *  RTMTotalCountIncrRate
1373   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1374 
1375   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1376   cmpptr(tmpReg, RTMAbortThreshold);
1377   jccb(Assembler::below, L_check_always_rtm2);
1378   imulptr(tmpReg, tmpReg, 100);
1379 
1380   Register scrReg = rtm_counters_Reg;
1381   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1382   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1383   imulptr(scrReg, scrReg, RTMAbortRatio);
1384   cmpptr(tmpReg, scrReg);
1385   jccb(Assembler::below, L_check_always_rtm1);
1386   if (method_data != NULL) {
1387     // set rtm_state to "no rtm" in MDO
1388     mov_metadata(tmpReg, method_data);
1389     if (os::is_MP()) {
1390       lock();
1391     }
1392     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1393   }
1394   jmpb(L_done);
1395   bind(L_check_always_rtm1);
1396   // Reload RTMLockingCounters* address
1397   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1398   bind(L_check_always_rtm2);
1399   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1400   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1401   jccb(Assembler::below, L_done);
1402   if (method_data != NULL) {
1403     // set rtm_state to "always rtm" in MDO
1404     mov_metadata(tmpReg, method_data);
1405     if (os::is_MP()) {
1406       lock();
1407     }
1408     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1409   }
1410   bind(L_done);
1411 }
1412 
1413 // Update counters and perform abort ratio calculation
1414 // input:  abort_status_Reg
1415 // rtm_counters_Reg, flags are killed
1416 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1417                                    Register rtm_counters_Reg,
1418                                    RTMLockingCounters* rtm_counters,
1419                                    Metadata* method_data,
1420                                    bool profile_rtm) {
1421 
1422   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1423   // update rtm counters based on rax value at abort
1424   // reads abort_status_Reg, updates flags
1425   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1426   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1427   if (profile_rtm) {
1428     // Save abort status because abort_status_Reg is used by following code.
1429     if (RTMRetryCount > 0) {
1430       push(abort_status_Reg);
1431     }
1432     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1433     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1434     // restore abort status
1435     if (RTMRetryCount > 0) {
1436       pop(abort_status_Reg);
1437     }
1438   }
1439 }
1440 
1441 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1442 // inputs: retry_count_Reg
1443 //       : abort_status_Reg
1444 // output: retry_count_Reg decremented by 1
1445 // flags are killed
1446 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1447   Label doneRetry;
1448   assert(abort_status_Reg == rax, "");
1449   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1450   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1451   // if reason is in 0x6 and retry count != 0 then retry
1452   andptr(abort_status_Reg, 0x6);
1453   jccb(Assembler::zero, doneRetry);
1454   testl(retry_count_Reg, retry_count_Reg);
1455   jccb(Assembler::zero, doneRetry);
1456   pause();
1457   decrementl(retry_count_Reg);
1458   jmp(retryLabel);
1459   bind(doneRetry);
1460 }
1461 
1462 // Spin and retry if lock is busy,
1463 // inputs: box_Reg (monitor address)
1464 //       : retry_count_Reg
1465 // output: retry_count_Reg decremented by 1
1466 //       : clear z flag if retry count exceeded
1467 // tmp_Reg, scr_Reg, flags are killed
1468 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1469                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1470   Label SpinLoop, SpinExit, doneRetry;
1471   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1472 
1473   testl(retry_count_Reg, retry_count_Reg);
1474   jccb(Assembler::zero, doneRetry);
1475   decrementl(retry_count_Reg);
1476   movptr(scr_Reg, RTMSpinLoopCount);
1477 
1478   bind(SpinLoop);
1479   pause();
1480   decrementl(scr_Reg);
1481   jccb(Assembler::lessEqual, SpinExit);
1482   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1483   testptr(tmp_Reg, tmp_Reg);
1484   jccb(Assembler::notZero, SpinLoop);
1485 
1486   bind(SpinExit);
1487   jmp(retryLabel);
1488   bind(doneRetry);
1489   incrementl(retry_count_Reg); // clear z flag
1490 }
1491 
1492 // Use RTM for normal stack locks
1493 // Input: objReg (object to lock)
1494 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1495                                        Register retry_on_abort_count_Reg,
1496                                        RTMLockingCounters* stack_rtm_counters,
1497                                        Metadata* method_data, bool profile_rtm,
1498                                        Label& DONE_LABEL, Label& IsInflated) {
1499   assert(UseRTMForStackLocks, "why call this otherwise?");
1500   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1501   assert(tmpReg == rax, "");
1502   assert(scrReg == rdx, "");
1503   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1504 
1505   if (RTMRetryCount > 0) {
1506     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1507     bind(L_rtm_retry);
1508   }
1509   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1510   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1511   jcc(Assembler::notZero, IsInflated);
1512 
1513   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1514     Label L_noincrement;
1515     if (RTMTotalCountIncrRate > 1) {
1516       // tmpReg, scrReg and flags are killed
1517       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1518     }
1519     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1520     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1521     bind(L_noincrement);
1522   }
1523   xbegin(L_on_abort);
1524   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1525   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1526   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1527   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1528 
1529   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1530   if (UseRTMXendForLockBusy) {
1531     xend();
1532     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1533     jmp(L_decrement_retry);
1534   }
1535   else {
1536     xabort(0);
1537   }
1538   bind(L_on_abort);
1539   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1540     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1541   }
1542   bind(L_decrement_retry);
1543   if (RTMRetryCount > 0) {
1544     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1545     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1546   }
1547 }
1548 
1549 // Use RTM for inflating locks
1550 // inputs: objReg (object to lock)
1551 //         boxReg (on-stack box address (displaced header location) - KILLED)
1552 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1553 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1554                                           Register scrReg, Register retry_on_busy_count_Reg,
1555                                           Register retry_on_abort_count_Reg,
1556                                           RTMLockingCounters* rtm_counters,
1557                                           Metadata* method_data, bool profile_rtm,
1558                                           Label& DONE_LABEL) {
1559   assert(UseRTMLocking, "why call this otherwise?");
1560   assert(tmpReg == rax, "");
1561   assert(scrReg == rdx, "");
1562   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1563   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1564 
1565   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1566   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1567   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1568 
1569   if (RTMRetryCount > 0) {
1570     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1571     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1572     bind(L_rtm_retry);
1573   }
1574   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1575     Label L_noincrement;
1576     if (RTMTotalCountIncrRate > 1) {
1577       // tmpReg, scrReg and flags are killed
1578       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1579     }
1580     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1581     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1582     bind(L_noincrement);
1583   }
1584   xbegin(L_on_abort);
1585   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1586   movptr(tmpReg, Address(tmpReg, owner_offset));
1587   testptr(tmpReg, tmpReg);
1588   jcc(Assembler::zero, DONE_LABEL);
1589   if (UseRTMXendForLockBusy) {
1590     xend();
1591     jmp(L_decrement_retry);
1592   }
1593   else {
1594     xabort(0);
1595   }
1596   bind(L_on_abort);
1597   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1598   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1599     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1600   }
1601   if (RTMRetryCount > 0) {
1602     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1603     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1604   }
1605 
1606   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1607   testptr(tmpReg, tmpReg) ;
1608   jccb(Assembler::notZero, L_decrement_retry) ;
1609 
1610   // Appears unlocked - try to swing _owner from null to non-null.
1611   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1612 #ifdef _LP64
1613   Register threadReg = r15_thread;
1614 #else
1615   get_thread(scrReg);
1616   Register threadReg = scrReg;
1617 #endif
1618   if (os::is_MP()) {
1619     lock();
1620   }
1621   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1622 
1623   if (RTMRetryCount > 0) {
1624     // success done else retry
1625     jccb(Assembler::equal, DONE_LABEL) ;
1626     bind(L_decrement_retry);
1627     // Spin and retry if lock is busy.
1628     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1629   }
1630   else {
1631     bind(L_decrement_retry);
1632   }
1633 }
1634 
1635 #endif //  INCLUDE_RTM_OPT
1636 
1637 // Fast_Lock and Fast_Unlock used by C2
1638 
1639 // Because the transitions from emitted code to the runtime
1640 // monitorenter/exit helper stubs are so slow it's critical that
1641 // we inline both the stack-locking fast-path and the inflated fast path.
1642 //
1643 // See also: cmpFastLock and cmpFastUnlock.
1644 //
1645 // What follows is a specialized inline transliteration of the code
1646 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1647 // another option would be to emit TrySlowEnter and TrySlowExit methods
1648 // at startup-time.  These methods would accept arguments as
1649 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1650 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1651 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1652 // In practice, however, the # of lock sites is bounded and is usually small.
1653 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1654 // if the processor uses simple bimodal branch predictors keyed by EIP
1655 // Since the helper routines would be called from multiple synchronization
1656 // sites.
1657 //
1658 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1659 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1660 // to those specialized methods.  That'd give us a mostly platform-independent
1661 // implementation that the JITs could optimize and inline at their pleasure.
1662 // Done correctly, the only time we'd need to cross to native could would be
1663 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1664 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1665 // (b) explicit barriers or fence operations.
1666 //
1667 // TODO:
1668 //
1669 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1670 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1671 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1672 //    the lock operators would typically be faster than reifying Self.
1673 //
1674 // *  Ideally I'd define the primitives as:
1675 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1676 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1677 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1678 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1679 //    Furthermore the register assignments are overconstrained, possibly resulting in
1680 //    sub-optimal code near the synchronization site.
1681 //
1682 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1683 //    Alternately, use a better sp-proximity test.
1684 //
1685 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1686 //    Either one is sufficient to uniquely identify a thread.
1687 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1688 //
1689 // *  Intrinsify notify() and notifyAll() for the common cases where the
1690 //    object is locked by the calling thread but the waitlist is empty.
1691 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1692 //
1693 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1694 //    But beware of excessive branch density on AMD Opterons.
1695 //
1696 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1697 //    or failure of the fast-path.  If the fast-path fails then we pass
1698 //    control to the slow-path, typically in C.  In Fast_Lock and
1699 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1700 //    will emit a conditional branch immediately after the node.
1701 //    So we have branches to branches and lots of ICC.ZF games.
1702 //    Instead, it might be better to have C2 pass a "FailureLabel"
1703 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1704 //    will drop through the node.  ICC.ZF is undefined at exit.
1705 //    In the case of failure, the node will branch directly to the
1706 //    FailureLabel
1707 
1708 
1709 // obj: object to lock
1710 // box: on-stack box address (displaced header location) - KILLED
1711 // rax,: tmp -- KILLED
1712 // scr: tmp -- KILLED
1713 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1714                                Register scrReg, Register cx1Reg, Register cx2Reg,
1715                                BiasedLockingCounters* counters,
1716                                RTMLockingCounters* rtm_counters,
1717                                RTMLockingCounters* stack_rtm_counters,
1718                                Metadata* method_data,
1719                                bool use_rtm, bool profile_rtm) {
1720   // Ensure the register assignments are disjoint
1721   assert(tmpReg == rax, "");
1722 
1723   if (use_rtm) {
1724     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1725   } else {
1726     assert(cx1Reg == noreg, "");
1727     assert(cx2Reg == noreg, "");
1728     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1729   }
1730 
1731   if (counters != NULL) {
1732     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1733   }
1734   if (EmitSync & 1) {
1735       // set box->dhw = markOopDesc::unused_mark()
1736       // Force all sync thru slow-path: slow_enter() and slow_exit()
1737       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1738       cmpptr (rsp, (int32_t)NULL_WORD);
1739   } else {
1740     // Possible cases that we'll encounter in fast_lock
1741     // ------------------------------------------------
1742     // * Inflated
1743     //    -- unlocked
1744     //    -- Locked
1745     //       = by self
1746     //       = by other
1747     // * biased
1748     //    -- by Self
1749     //    -- by other
1750     // * neutral
1751     // * stack-locked
1752     //    -- by self
1753     //       = sp-proximity test hits
1754     //       = sp-proximity test generates false-negative
1755     //    -- by other
1756     //
1757 
1758     Label IsInflated, DONE_LABEL;
1759 
1760     // it's stack-locked, biased or neutral
1761     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1762     // order to reduce the number of conditional branches in the most common cases.
1763     // Beware -- there's a subtle invariant that fetch of the markword
1764     // at [FETCH], below, will never observe a biased encoding (*101b).
1765     // If this invariant is not held we risk exclusion (safety) failure.
1766     if (UseBiasedLocking && !UseOptoBiasInlining) {
1767       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1768     }
1769 
1770 #if INCLUDE_RTM_OPT
1771     if (UseRTMForStackLocks && use_rtm) {
1772       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1773                         stack_rtm_counters, method_data, profile_rtm,
1774                         DONE_LABEL, IsInflated);
1775     }
1776 #endif // INCLUDE_RTM_OPT
1777 
1778     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1779     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1780     jccb(Assembler::notZero, IsInflated);
1781 
1782     // Attempt stack-locking ...
1783     orptr (tmpReg, markOopDesc::unlocked_value);
1784     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1785     if (os::is_MP()) {
1786       lock();
1787     }
1788     cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1789     if (counters != NULL) {
1790       cond_inc32(Assembler::equal,
1791                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1792     }
1793     jcc(Assembler::equal, DONE_LABEL);           // Success
1794 
1795     // Recursive locking.
1796     // The object is stack-locked: markword contains stack pointer to BasicLock.
1797     // Locked by current thread if difference with current SP is less than one page.
1798     subptr(tmpReg, rsp);
1799     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1800     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1801     movptr(Address(boxReg, 0), tmpReg);
1802     if (counters != NULL) {
1803       cond_inc32(Assembler::equal,
1804                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1805     }
1806     jmp(DONE_LABEL);
1807 
1808     bind(IsInflated);
1809     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1810 
1811 #if INCLUDE_RTM_OPT
1812     // Use the same RTM locking code in 32- and 64-bit VM.
1813     if (use_rtm) {
1814       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1815                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1816     } else {
1817 #endif // INCLUDE_RTM_OPT
1818 
1819 #ifndef _LP64
1820     // The object is inflated.
1821 
1822     // boxReg refers to the on-stack BasicLock in the current frame.
1823     // We'd like to write:
1824     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1825     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1826     // additional latency as we have another ST in the store buffer that must drain.
1827 
1828     if (EmitSync & 8192) {
1829        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1830        get_thread (scrReg);
1831        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1832        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1833        if (os::is_MP()) {
1834          lock();
1835        }
1836        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1837     } else
1838     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1839        // register juggle because we need tmpReg for cmpxchgptr below
1840        movptr(scrReg, boxReg);
1841        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1842 
1843        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1844        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1845           // prefetchw [eax + Offset(_owner)-2]
1846           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1847        }
1848 
1849        if ((EmitSync & 64) == 0) {
1850          // Optimistic form: consider XORL tmpReg,tmpReg
1851          movptr(tmpReg, NULL_WORD);
1852        } else {
1853          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1854          // Test-And-CAS instead of CAS
1855          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1856          testptr(tmpReg, tmpReg);                   // Locked ?
1857          jccb  (Assembler::notZero, DONE_LABEL);
1858        }
1859 
1860        // Appears unlocked - try to swing _owner from null to non-null.
1861        // Ideally, I'd manifest "Self" with get_thread and then attempt
1862        // to CAS the register containing Self into m->Owner.
1863        // But we don't have enough registers, so instead we can either try to CAS
1864        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1865        // we later store "Self" into m->Owner.  Transiently storing a stack address
1866        // (rsp or the address of the box) into  m->owner is harmless.
1867        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1868        if (os::is_MP()) {
1869          lock();
1870        }
1871        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1872        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1873        // If we weren't able to swing _owner from NULL to the BasicLock
1874        // then take the slow path.
1875        jccb  (Assembler::notZero, DONE_LABEL);
1876        // update _owner from BasicLock to thread
1877        get_thread (scrReg);                    // beware: clobbers ICCs
1878        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1879        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1880 
1881        // If the CAS fails we can either retry or pass control to the slow-path.
1882        // We use the latter tactic.
1883        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1884        // If the CAS was successful ...
1885        //   Self has acquired the lock
1886        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1887        // Intentional fall-through into DONE_LABEL ...
1888     } else {
1889        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1890        movptr(boxReg, tmpReg);
1891 
1892        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1893        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1894           // prefetchw [eax + Offset(_owner)-2]
1895           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1896        }
1897 
1898        if ((EmitSync & 64) == 0) {
1899          // Optimistic form
1900          xorptr  (tmpReg, tmpReg);
1901        } else {
1902          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1903          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1904          testptr(tmpReg, tmpReg);                   // Locked ?
1905          jccb  (Assembler::notZero, DONE_LABEL);
1906        }
1907 
1908        // Appears unlocked - try to swing _owner from null to non-null.
1909        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1910        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1911        get_thread (scrReg);
1912        if (os::is_MP()) {
1913          lock();
1914        }
1915        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1916 
1917        // If the CAS fails we can either retry or pass control to the slow-path.
1918        // We use the latter tactic.
1919        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1920        // If the CAS was successful ...
1921        //   Self has acquired the lock
1922        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1923        // Intentional fall-through into DONE_LABEL ...
1924     }
1925 #else // _LP64
1926     // It's inflated
1927     movq(scrReg, tmpReg);
1928     xorq(tmpReg, tmpReg);
1929 
1930     if (os::is_MP()) {
1931       lock();
1932     }
1933     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1934     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1935     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1936     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1937     // Intentional fall-through into DONE_LABEL ...
1938     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1939 #endif // _LP64
1940 #if INCLUDE_RTM_OPT
1941     } // use_rtm()
1942 #endif
1943     // DONE_LABEL is a hot target - we'd really like to place it at the
1944     // start of cache line by padding with NOPs.
1945     // See the AMD and Intel software optimization manuals for the
1946     // most efficient "long" NOP encodings.
1947     // Unfortunately none of our alignment mechanisms suffice.
1948     bind(DONE_LABEL);
1949 
1950     // At DONE_LABEL the icc ZFlag is set as follows ...
1951     // Fast_Unlock uses the same protocol.
1952     // ZFlag == 1 -> Success
1953     // ZFlag == 0 -> Failure - force control through the slow-path
1954   }
1955 }
1956 
1957 // obj: object to unlock
1958 // box: box address (displaced header location), killed.  Must be EAX.
1959 // tmp: killed, cannot be obj nor box.
1960 //
1961 // Some commentary on balanced locking:
1962 //
1963 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1964 // Methods that don't have provably balanced locking are forced to run in the
1965 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1966 // The interpreter provides two properties:
1967 // I1:  At return-time the interpreter automatically and quietly unlocks any
1968 //      objects acquired the current activation (frame).  Recall that the
1969 //      interpreter maintains an on-stack list of locks currently held by
1970 //      a frame.
1971 // I2:  If a method attempts to unlock an object that is not held by the
1972 //      the frame the interpreter throws IMSX.
1973 //
1974 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1975 // B() doesn't have provably balanced locking so it runs in the interpreter.
1976 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1977 // is still locked by A().
1978 //
1979 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1980 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1981 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1982 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1983 // Arguably given that the spec legislates the JNI case as undefined our implementation
1984 // could reasonably *avoid* checking owner in Fast_Unlock().
1985 // In the interest of performance we elide m->Owner==Self check in unlock.
1986 // A perfectly viable alternative is to elide the owner check except when
1987 // Xcheck:jni is enabled.
1988 
1989 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1990   assert(boxReg == rax, "");
1991   assert_different_registers(objReg, boxReg, tmpReg);
1992 
1993   if (EmitSync & 4) {
1994     // Disable - inhibit all inlining.  Force control through the slow-path
1995     cmpptr (rsp, 0);
1996   } else {
1997     Label DONE_LABEL, Stacked, CheckSucc;
1998 
1999     // Critically, the biased locking test must have precedence over
2000     // and appear before the (box->dhw == 0) recursive stack-lock test.
2001     if (UseBiasedLocking && !UseOptoBiasInlining) {
2002        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
2003     }
2004 
2005 #if INCLUDE_RTM_OPT
2006     if (UseRTMForStackLocks && use_rtm) {
2007       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
2008       Label L_regular_unlock;
2009       movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
2010       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
2011       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
2012       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
2013       xend();                                       // otherwise end...
2014       jmp(DONE_LABEL);                              // ... and we're done
2015       bind(L_regular_unlock);
2016     }
2017 #endif
2018 
2019     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
2020     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2021     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
2022     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2023     jccb  (Assembler::zero, Stacked);
2024 
2025     // It's inflated.
2026 #if INCLUDE_RTM_OPT
2027     if (use_rtm) {
2028       Label L_regular_inflated_unlock;
2029       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2030       movptr(boxReg, Address(tmpReg, owner_offset));
2031       testptr(boxReg, boxReg);
2032       jccb(Assembler::notZero, L_regular_inflated_unlock);
2033       xend();
2034       jmpb(DONE_LABEL);
2035       bind(L_regular_inflated_unlock);
2036     }
2037 #endif
2038 
2039     // Despite our balanced locking property we still check that m->_owner == Self
2040     // as java routines or native JNI code called by this thread might
2041     // have released the lock.
2042     // Refer to the comments in synchronizer.cpp for how we might encode extra
2043     // state in _succ so we can avoid fetching EntryList|cxq.
2044     //
2045     // I'd like to add more cases in fast_lock() and fast_unlock() --
2046     // such as recursive enter and exit -- but we have to be wary of
2047     // I$ bloat, T$ effects and BP$ effects.
2048     //
2049     // If there's no contention try a 1-0 exit.  That is, exit without
2050     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2051     // we detect and recover from the race that the 1-0 exit admits.
2052     //
2053     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2054     // before it STs null into _owner, releasing the lock.  Updates
2055     // to data protected by the critical section must be visible before
2056     // we drop the lock (and thus before any other thread could acquire
2057     // the lock and observe the fields protected by the lock).
2058     // IA32's memory-model is SPO, so STs are ordered with respect to
2059     // each other and there's no need for an explicit barrier (fence).
2060     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2061 #ifndef _LP64
2062     get_thread (boxReg);
2063     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2064       // prefetchw [ebx + Offset(_owner)-2]
2065       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2066     }
2067 
2068     // Note that we could employ various encoding schemes to reduce
2069     // the number of loads below (currently 4) to just 2 or 3.
2070     // Refer to the comments in synchronizer.cpp.
2071     // In practice the chain of fetches doesn't seem to impact performance, however.
2072     xorptr(boxReg, boxReg);
2073     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2074        // Attempt to reduce branch density - AMD's branch predictor.
2075        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2076        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2077        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2078        jccb  (Assembler::notZero, DONE_LABEL);
2079        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2080        jmpb  (DONE_LABEL);
2081     } else {
2082        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2083        jccb  (Assembler::notZero, DONE_LABEL);
2084        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2085        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2086        jccb  (Assembler::notZero, CheckSucc);
2087        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2088        jmpb  (DONE_LABEL);
2089     }
2090 
2091     // The Following code fragment (EmitSync & 65536) improves the performance of
2092     // contended applications and contended synchronization microbenchmarks.
2093     // Unfortunately the emission of the code - even though not executed - causes regressions
2094     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2095     // with an equal number of never-executed NOPs results in the same regression.
2096     // We leave it off by default.
2097 
2098     if ((EmitSync & 65536) != 0) {
2099        Label LSuccess, LGoSlowPath ;
2100 
2101        bind  (CheckSucc);
2102 
2103        // Optional pre-test ... it's safe to elide this
2104        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2105        jccb(Assembler::zero, LGoSlowPath);
2106 
2107        // We have a classic Dekker-style idiom:
2108        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2109        // There are a number of ways to implement the barrier:
2110        // (1) lock:andl &m->_owner, 0
2111        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2112        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2113        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2114        // (2) If supported, an explicit MFENCE is appealing.
2115        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2116        //     particularly if the write-buffer is full as might be the case if
2117        //     if stores closely precede the fence or fence-equivalent instruction.
2118        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2119        //     as the situation has changed with Nehalem and Shanghai.
2120        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2121        //     The $lines underlying the top-of-stack should be in M-state.
2122        //     The locked add instruction is serializing, of course.
2123        // (4) Use xchg, which is serializing
2124        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2125        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2126        //     The integer condition codes will tell us if succ was 0.
2127        //     Since _succ and _owner should reside in the same $line and
2128        //     we just stored into _owner, it's likely that the $line
2129        //     remains in M-state for the lock:orl.
2130        //
2131        // We currently use (3), although it's likely that switching to (2)
2132        // is correct for the future.
2133 
2134        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2135        if (os::is_MP()) {
2136          lock(); addptr(Address(rsp, 0), 0);
2137        }
2138        // Ratify _succ remains non-null
2139        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2140        jccb  (Assembler::notZero, LSuccess);
2141 
2142        xorptr(boxReg, boxReg);                  // box is really EAX
2143        if (os::is_MP()) { lock(); }
2144        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2145        // There's no successor so we tried to regrab the lock with the
2146        // placeholder value. If that didn't work, then another thread
2147        // grabbed the lock so we're done (and exit was a success).
2148        jccb  (Assembler::notEqual, LSuccess);
2149        // Since we're low on registers we installed rsp as a placeholding in _owner.
2150        // Now install Self over rsp.  This is safe as we're transitioning from
2151        // non-null to non=null
2152        get_thread (boxReg);
2153        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2154        // Intentional fall-through into LGoSlowPath ...
2155 
2156        bind  (LGoSlowPath);
2157        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2158        jmpb  (DONE_LABEL);
2159 
2160        bind  (LSuccess);
2161        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2162        jmpb  (DONE_LABEL);
2163     }
2164 
2165     bind (Stacked);
2166     // It's not inflated and it's not recursively stack-locked and it's not biased.
2167     // It must be stack-locked.
2168     // Try to reset the header to displaced header.
2169     // The "box" value on the stack is stable, so we can reload
2170     // and be assured we observe the same value as above.
2171     movptr(tmpReg, Address(boxReg, 0));
2172     if (os::is_MP()) {
2173       lock();
2174     }
2175     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2176     // Intention fall-thru into DONE_LABEL
2177 
2178     // DONE_LABEL is a hot target - we'd really like to place it at the
2179     // start of cache line by padding with NOPs.
2180     // See the AMD and Intel software optimization manuals for the
2181     // most efficient "long" NOP encodings.
2182     // Unfortunately none of our alignment mechanisms suffice.
2183     if ((EmitSync & 65536) == 0) {
2184        bind (CheckSucc);
2185     }
2186 #else // _LP64
2187     // It's inflated
2188     if (EmitSync & 1024) {
2189       // Emit code to check that _owner == Self
2190       // We could fold the _owner test into subsequent code more efficiently
2191       // than using a stand-alone check, but since _owner checking is off by
2192       // default we don't bother. We also might consider predicating the
2193       // _owner==Self check on Xcheck:jni or running on a debug build.
2194       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2195       xorptr(boxReg, r15_thread);
2196     } else {
2197       xorptr(boxReg, boxReg);
2198     }
2199     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2200     jccb  (Assembler::notZero, DONE_LABEL);
2201     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2202     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2203     jccb  (Assembler::notZero, CheckSucc);
2204     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2205     jmpb  (DONE_LABEL);
2206 
2207     if ((EmitSync & 65536) == 0) {
2208       // Try to avoid passing control into the slow_path ...
2209       Label LSuccess, LGoSlowPath ;
2210       bind  (CheckSucc);
2211 
2212       // The following optional optimization can be elided if necessary
2213       // Effectively: if (succ == null) goto SlowPath
2214       // The code reduces the window for a race, however,
2215       // and thus benefits performance.
2216       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2217       jccb  (Assembler::zero, LGoSlowPath);
2218 
2219       xorptr(boxReg, boxReg);
2220       if ((EmitSync & 16) && os::is_MP()) {
2221         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2222       } else {
2223         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2224         if (os::is_MP()) {
2225           // Memory barrier/fence
2226           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2227           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2228           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2229           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2230           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2231           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2232           lock(); addl(Address(rsp, 0), 0);
2233         }
2234       }
2235       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2236       jccb  (Assembler::notZero, LSuccess);
2237 
2238       // Rare inopportune interleaving - race.
2239       // The successor vanished in the small window above.
2240       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2241       // We need to ensure progress and succession.
2242       // Try to reacquire the lock.
2243       // If that fails then the new owner is responsible for succession and this
2244       // thread needs to take no further action and can exit via the fast path (success).
2245       // If the re-acquire succeeds then pass control into the slow path.
2246       // As implemented, this latter mode is horrible because we generated more
2247       // coherence traffic on the lock *and* artifically extended the critical section
2248       // length while by virtue of passing control into the slow path.
2249 
2250       // box is really RAX -- the following CMPXCHG depends on that binding
2251       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2252       if (os::is_MP()) { lock(); }
2253       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2254       // There's no successor so we tried to regrab the lock.
2255       // If that didn't work, then another thread grabbed the
2256       // lock so we're done (and exit was a success).
2257       jccb  (Assembler::notEqual, LSuccess);
2258       // Intentional fall-through into slow-path
2259 
2260       bind  (LGoSlowPath);
2261       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2262       jmpb  (DONE_LABEL);
2263 
2264       bind  (LSuccess);
2265       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2266       jmpb  (DONE_LABEL);
2267     }
2268 
2269     bind  (Stacked);
2270     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2271     if (os::is_MP()) { lock(); }
2272     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2273 
2274     if (EmitSync & 65536) {
2275        bind (CheckSucc);
2276     }
2277 #endif
2278     bind(DONE_LABEL);
2279   }
2280 }
2281 #endif // COMPILER2
2282 
2283 void MacroAssembler::c2bool(Register x) {
2284   // implements x == 0 ? 0 : 1
2285   // note: must only look at least-significant byte of x
2286   //       since C-style booleans are stored in one byte
2287   //       only! (was bug)
2288   andl(x, 0xFF);
2289   setb(Assembler::notZero, x);
2290 }
2291 
2292 // Wouldn't need if AddressLiteral version had new name
2293 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2294   Assembler::call(L, rtype);
2295 }
2296 
2297 void MacroAssembler::call(Register entry) {
2298   Assembler::call(entry);
2299 }
2300 
2301 void MacroAssembler::call(AddressLiteral entry) {
2302   if (reachable(entry)) {
2303     Assembler::call_literal(entry.target(), entry.rspec());
2304   } else {
2305     lea(rscratch1, entry);
2306     Assembler::call(rscratch1);
2307   }
2308 }
2309 
2310 void MacroAssembler::ic_call(address entry, jint method_index) {
2311   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2312   movptr(rax, (intptr_t)Universe::non_oop_word());
2313   call(AddressLiteral(entry, rh));
2314 }
2315 
2316 // Implementation of call_VM versions
2317 
2318 void MacroAssembler::call_VM(Register oop_result,
2319                              address entry_point,
2320                              bool check_exceptions) {
2321   Label C, E;
2322   call(C, relocInfo::none);
2323   jmp(E);
2324 
2325   bind(C);
2326   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2327   ret(0);
2328 
2329   bind(E);
2330 }
2331 
2332 void MacroAssembler::call_VM(Register oop_result,
2333                              address entry_point,
2334                              Register arg_1,
2335                              bool check_exceptions) {
2336   Label C, E;
2337   call(C, relocInfo::none);
2338   jmp(E);
2339 
2340   bind(C);
2341   pass_arg1(this, arg_1);
2342   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2343   ret(0);
2344 
2345   bind(E);
2346 }
2347 
2348 void MacroAssembler::call_VM(Register oop_result,
2349                              address entry_point,
2350                              Register arg_1,
2351                              Register arg_2,
2352                              bool check_exceptions) {
2353   Label C, E;
2354   call(C, relocInfo::none);
2355   jmp(E);
2356 
2357   bind(C);
2358 
2359   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2360 
2361   pass_arg2(this, arg_2);
2362   pass_arg1(this, arg_1);
2363   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2364   ret(0);
2365 
2366   bind(E);
2367 }
2368 
2369 void MacroAssembler::call_VM(Register oop_result,
2370                              address entry_point,
2371                              Register arg_1,
2372                              Register arg_2,
2373                              Register arg_3,
2374                              bool check_exceptions) {
2375   Label C, E;
2376   call(C, relocInfo::none);
2377   jmp(E);
2378 
2379   bind(C);
2380 
2381   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2382   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2383   pass_arg3(this, arg_3);
2384 
2385   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2386   pass_arg2(this, arg_2);
2387 
2388   pass_arg1(this, arg_1);
2389   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2390   ret(0);
2391 
2392   bind(E);
2393 }
2394 
2395 void MacroAssembler::call_VM(Register oop_result,
2396                              Register last_java_sp,
2397                              address entry_point,
2398                              int number_of_arguments,
2399                              bool check_exceptions) {
2400   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2401   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2402 }
2403 
2404 void MacroAssembler::call_VM(Register oop_result,
2405                              Register last_java_sp,
2406                              address entry_point,
2407                              Register arg_1,
2408                              bool check_exceptions) {
2409   pass_arg1(this, arg_1);
2410   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2411 }
2412 
2413 void MacroAssembler::call_VM(Register oop_result,
2414                              Register last_java_sp,
2415                              address entry_point,
2416                              Register arg_1,
2417                              Register arg_2,
2418                              bool check_exceptions) {
2419 
2420   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2421   pass_arg2(this, arg_2);
2422   pass_arg1(this, arg_1);
2423   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2424 }
2425 
2426 void MacroAssembler::call_VM(Register oop_result,
2427                              Register last_java_sp,
2428                              address entry_point,
2429                              Register arg_1,
2430                              Register arg_2,
2431                              Register arg_3,
2432                              bool check_exceptions) {
2433   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2434   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2435   pass_arg3(this, arg_3);
2436   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2437   pass_arg2(this, arg_2);
2438   pass_arg1(this, arg_1);
2439   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2440 }
2441 
2442 void MacroAssembler::super_call_VM(Register oop_result,
2443                                    Register last_java_sp,
2444                                    address entry_point,
2445                                    int number_of_arguments,
2446                                    bool check_exceptions) {
2447   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2448   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2449 }
2450 
2451 void MacroAssembler::super_call_VM(Register oop_result,
2452                                    Register last_java_sp,
2453                                    address entry_point,
2454                                    Register arg_1,
2455                                    bool check_exceptions) {
2456   pass_arg1(this, arg_1);
2457   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2458 }
2459 
2460 void MacroAssembler::super_call_VM(Register oop_result,
2461                                    Register last_java_sp,
2462                                    address entry_point,
2463                                    Register arg_1,
2464                                    Register arg_2,
2465                                    bool check_exceptions) {
2466 
2467   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2468   pass_arg2(this, arg_2);
2469   pass_arg1(this, arg_1);
2470   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2471 }
2472 
2473 void MacroAssembler::super_call_VM(Register oop_result,
2474                                    Register last_java_sp,
2475                                    address entry_point,
2476                                    Register arg_1,
2477                                    Register arg_2,
2478                                    Register arg_3,
2479                                    bool check_exceptions) {
2480   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2481   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2482   pass_arg3(this, arg_3);
2483   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2484   pass_arg2(this, arg_2);
2485   pass_arg1(this, arg_1);
2486   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2487 }
2488 
2489 void MacroAssembler::call_VM_base(Register oop_result,
2490                                   Register java_thread,
2491                                   Register last_java_sp,
2492                                   address  entry_point,
2493                                   int      number_of_arguments,
2494                                   bool     check_exceptions) {
2495   // determine java_thread register
2496   if (!java_thread->is_valid()) {
2497 #ifdef _LP64
2498     java_thread = r15_thread;
2499 #else
2500     java_thread = rdi;
2501     get_thread(java_thread);
2502 #endif // LP64
2503   }
2504   // determine last_java_sp register
2505   if (!last_java_sp->is_valid()) {
2506     last_java_sp = rsp;
2507   }
2508   // debugging support
2509   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2510   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2511 #ifdef ASSERT
2512   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2513   // r12 is the heapbase.
2514   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2515 #endif // ASSERT
2516 
2517   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2518   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2519 
2520   // push java thread (becomes first argument of C function)
2521 
2522   NOT_LP64(push(java_thread); number_of_arguments++);
2523   LP64_ONLY(mov(c_rarg0, r15_thread));
2524 
2525   // set last Java frame before call
2526   assert(last_java_sp != rbp, "can't use ebp/rbp");
2527 
2528   // Only interpreter should have to set fp
2529   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2530 
2531   // do the call, remove parameters
2532   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2533 
2534   // restore the thread (cannot use the pushed argument since arguments
2535   // may be overwritten by C code generated by an optimizing compiler);
2536   // however can use the register value directly if it is callee saved.
2537   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2538     // rdi & rsi (also r15) are callee saved -> nothing to do
2539 #ifdef ASSERT
2540     guarantee(java_thread != rax, "change this code");
2541     push(rax);
2542     { Label L;
2543       get_thread(rax);
2544       cmpptr(java_thread, rax);
2545       jcc(Assembler::equal, L);
2546       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2547       bind(L);
2548     }
2549     pop(rax);
2550 #endif
2551   } else {
2552     get_thread(java_thread);
2553   }
2554   // reset last Java frame
2555   // Only interpreter should have to clear fp
2556   reset_last_Java_frame(java_thread, true);
2557 
2558    // C++ interp handles this in the interpreter
2559   check_and_handle_popframe(java_thread);
2560   check_and_handle_earlyret(java_thread);
2561 
2562   if (check_exceptions) {
2563     // check for pending exceptions (java_thread is set upon return)
2564     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2565 #ifndef _LP64
2566     jump_cc(Assembler::notEqual,
2567             RuntimeAddress(StubRoutines::forward_exception_entry()));
2568 #else
2569     // This used to conditionally jump to forward_exception however it is
2570     // possible if we relocate that the branch will not reach. So we must jump
2571     // around so we can always reach
2572 
2573     Label ok;
2574     jcc(Assembler::equal, ok);
2575     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2576     bind(ok);
2577 #endif // LP64
2578   }
2579 
2580   // get oop result if there is one and reset the value in the thread
2581   if (oop_result->is_valid()) {
2582     get_vm_result(oop_result, java_thread);
2583   }
2584 }
2585 
2586 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2587 
2588   // Calculate the value for last_Java_sp
2589   // somewhat subtle. call_VM does an intermediate call
2590   // which places a return address on the stack just under the
2591   // stack pointer as the user finsihed with it. This allows
2592   // use to retrieve last_Java_pc from last_Java_sp[-1].
2593   // On 32bit we then have to push additional args on the stack to accomplish
2594   // the actual requested call. On 64bit call_VM only can use register args
2595   // so the only extra space is the return address that call_VM created.
2596   // This hopefully explains the calculations here.
2597 
2598 #ifdef _LP64
2599   // We've pushed one address, correct last_Java_sp
2600   lea(rax, Address(rsp, wordSize));
2601 #else
2602   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2603 #endif // LP64
2604 
2605   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2606 
2607 }
2608 
2609 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2610 void MacroAssembler::call_VM_leaf0(address entry_point) {
2611   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2612 }
2613 
2614 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2615   call_VM_leaf_base(entry_point, number_of_arguments);
2616 }
2617 
2618 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2619   pass_arg0(this, arg_0);
2620   call_VM_leaf(entry_point, 1);
2621 }
2622 
2623 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2624 
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, 2);
2629 }
2630 
2631 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2632   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2633   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2634   pass_arg2(this, arg_2);
2635   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2636   pass_arg1(this, arg_1);
2637   pass_arg0(this, arg_0);
2638   call_VM_leaf(entry_point, 3);
2639 }
2640 
2641 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2642   pass_arg0(this, arg_0);
2643   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2644 }
2645 
2646 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2647 
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, 2);
2652 }
2653 
2654 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2655   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2656   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2657   pass_arg2(this, arg_2);
2658   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2659   pass_arg1(this, arg_1);
2660   pass_arg0(this, arg_0);
2661   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2662 }
2663 
2664 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2665   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2666   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2667   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2668   pass_arg3(this, arg_3);
2669   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2670   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2671   pass_arg2(this, arg_2);
2672   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2673   pass_arg1(this, arg_1);
2674   pass_arg0(this, arg_0);
2675   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2676 }
2677 
2678 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2679   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2680   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2681   verify_oop(oop_result, "broken oop in call_VM_base");
2682 }
2683 
2684 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2685   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2686   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2687 }
2688 
2689 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2690 }
2691 
2692 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2693 }
2694 
2695 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2696   if (reachable(src1)) {
2697     cmpl(as_Address(src1), imm);
2698   } else {
2699     lea(rscratch1, src1);
2700     cmpl(Address(rscratch1, 0), imm);
2701   }
2702 }
2703 
2704 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2705   assert(!src2.is_lval(), "use cmpptr");
2706   if (reachable(src2)) {
2707     cmpl(src1, as_Address(src2));
2708   } else {
2709     lea(rscratch1, src2);
2710     cmpl(src1, Address(rscratch1, 0));
2711   }
2712 }
2713 
2714 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2715   Assembler::cmpl(src1, imm);
2716 }
2717 
2718 void MacroAssembler::cmp32(Register src1, Address src2) {
2719   Assembler::cmpl(src1, src2);
2720 }
2721 
2722 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2723   ucomisd(opr1, opr2);
2724 
2725   Label L;
2726   if (unordered_is_less) {
2727     movl(dst, -1);
2728     jcc(Assembler::parity, L);
2729     jcc(Assembler::below , L);
2730     movl(dst, 0);
2731     jcc(Assembler::equal , L);
2732     increment(dst);
2733   } else { // unordered is greater
2734     movl(dst, 1);
2735     jcc(Assembler::parity, L);
2736     jcc(Assembler::above , L);
2737     movl(dst, 0);
2738     jcc(Assembler::equal , L);
2739     decrementl(dst);
2740   }
2741   bind(L);
2742 }
2743 
2744 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2745   ucomiss(opr1, opr2);
2746 
2747   Label L;
2748   if (unordered_is_less) {
2749     movl(dst, -1);
2750     jcc(Assembler::parity, L);
2751     jcc(Assembler::below , L);
2752     movl(dst, 0);
2753     jcc(Assembler::equal , L);
2754     increment(dst);
2755   } else { // unordered is greater
2756     movl(dst, 1);
2757     jcc(Assembler::parity, L);
2758     jcc(Assembler::above , L);
2759     movl(dst, 0);
2760     jcc(Assembler::equal , L);
2761     decrementl(dst);
2762   }
2763   bind(L);
2764 }
2765 
2766 
2767 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2768   if (reachable(src1)) {
2769     cmpb(as_Address(src1), imm);
2770   } else {
2771     lea(rscratch1, src1);
2772     cmpb(Address(rscratch1, 0), imm);
2773   }
2774 }
2775 
2776 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2777 #ifdef _LP64
2778   if (src2.is_lval()) {
2779     movptr(rscratch1, src2);
2780     Assembler::cmpq(src1, rscratch1);
2781   } else if (reachable(src2)) {
2782     cmpq(src1, as_Address(src2));
2783   } else {
2784     lea(rscratch1, src2);
2785     Assembler::cmpq(src1, Address(rscratch1, 0));
2786   }
2787 #else
2788   if (src2.is_lval()) {
2789     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2790   } else {
2791     cmpl(src1, as_Address(src2));
2792   }
2793 #endif // _LP64
2794 }
2795 
2796 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2797   assert(src2.is_lval(), "not a mem-mem compare");
2798 #ifdef _LP64
2799   // moves src2's literal address
2800   movptr(rscratch1, src2);
2801   Assembler::cmpq(src1, rscratch1);
2802 #else
2803   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2804 #endif // _LP64
2805 }
2806 
2807 void MacroAssembler::cmpoop(Register src1, Register src2) {
2808   cmpptr(src1, src2);
2809 }
2810 
2811 void MacroAssembler::cmpoop(Register src1, Address src2) {
2812   cmpptr(src1, src2);
2813 }
2814 
2815 #ifdef _LP64
2816 void MacroAssembler::cmpoop(Register src1, jobject src2) {
2817   movoop(rscratch1, src2);
2818   cmpptr(src1, rscratch1);
2819 }
2820 #endif
2821 
2822 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2823   if (reachable(adr)) {
2824     if (os::is_MP())
2825       lock();
2826     cmpxchgptr(reg, as_Address(adr));
2827   } else {
2828     lea(rscratch1, adr);
2829     if (os::is_MP())
2830       lock();
2831     cmpxchgptr(reg, Address(rscratch1, 0));
2832   }
2833 }
2834 
2835 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2836   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2837 }
2838 
2839 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2840   if (reachable(src)) {
2841     Assembler::comisd(dst, as_Address(src));
2842   } else {
2843     lea(rscratch1, src);
2844     Assembler::comisd(dst, Address(rscratch1, 0));
2845   }
2846 }
2847 
2848 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2849   if (reachable(src)) {
2850     Assembler::comiss(dst, as_Address(src));
2851   } else {
2852     lea(rscratch1, src);
2853     Assembler::comiss(dst, Address(rscratch1, 0));
2854   }
2855 }
2856 
2857 
2858 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2859   Condition negated_cond = negate_condition(cond);
2860   Label L;
2861   jcc(negated_cond, L);
2862   pushf(); // Preserve flags
2863   atomic_incl(counter_addr);
2864   popf();
2865   bind(L);
2866 }
2867 
2868 int MacroAssembler::corrected_idivl(Register reg) {
2869   // Full implementation of Java idiv and irem; checks for
2870   // special case as described in JVM spec., p.243 & p.271.
2871   // The function returns the (pc) offset of the idivl
2872   // instruction - may be needed for implicit exceptions.
2873   //
2874   //         normal case                           special case
2875   //
2876   // input : rax,: dividend                         min_int
2877   //         reg: divisor   (may not be rax,/rdx)   -1
2878   //
2879   // output: rax,: quotient  (= rax, idiv reg)       min_int
2880   //         rdx: remainder (= rax, irem reg)       0
2881   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2882   const int min_int = 0x80000000;
2883   Label normal_case, special_case;
2884 
2885   // check for special case
2886   cmpl(rax, min_int);
2887   jcc(Assembler::notEqual, normal_case);
2888   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2889   cmpl(reg, -1);
2890   jcc(Assembler::equal, special_case);
2891 
2892   // handle normal case
2893   bind(normal_case);
2894   cdql();
2895   int idivl_offset = offset();
2896   idivl(reg);
2897 
2898   // normal and special case exit
2899   bind(special_case);
2900 
2901   return idivl_offset;
2902 }
2903 
2904 
2905 
2906 void MacroAssembler::decrementl(Register reg, int value) {
2907   if (value == min_jint) {subl(reg, value) ; return; }
2908   if (value <  0) { incrementl(reg, -value); return; }
2909   if (value == 0) {                        ; return; }
2910   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2911   /* else */      { subl(reg, value)       ; return; }
2912 }
2913 
2914 void MacroAssembler::decrementl(Address dst, int value) {
2915   if (value == min_jint) {subl(dst, value) ; return; }
2916   if (value <  0) { incrementl(dst, -value); return; }
2917   if (value == 0) {                        ; return; }
2918   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2919   /* else */      { subl(dst, value)       ; return; }
2920 }
2921 
2922 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2923   assert (shift_value > 0, "illegal shift value");
2924   Label _is_positive;
2925   testl (reg, reg);
2926   jcc (Assembler::positive, _is_positive);
2927   int offset = (1 << shift_value) - 1 ;
2928 
2929   if (offset == 1) {
2930     incrementl(reg);
2931   } else {
2932     addl(reg, offset);
2933   }
2934 
2935   bind (_is_positive);
2936   sarl(reg, shift_value);
2937 }
2938 
2939 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2940   if (reachable(src)) {
2941     Assembler::divsd(dst, as_Address(src));
2942   } else {
2943     lea(rscratch1, src);
2944     Assembler::divsd(dst, Address(rscratch1, 0));
2945   }
2946 }
2947 
2948 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2949   if (reachable(src)) {
2950     Assembler::divss(dst, as_Address(src));
2951   } else {
2952     lea(rscratch1, src);
2953     Assembler::divss(dst, Address(rscratch1, 0));
2954   }
2955 }
2956 
2957 // !defined(COMPILER2) is because of stupid core builds
2958 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2959 void MacroAssembler::empty_FPU_stack() {
2960   if (VM_Version::supports_mmx()) {
2961     emms();
2962   } else {
2963     for (int i = 8; i-- > 0; ) ffree(i);
2964   }
2965 }
2966 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2967 
2968 
2969 // Defines obj, preserves var_size_in_bytes
2970 void MacroAssembler::eden_allocate(Register obj,
2971                                    Register var_size_in_bytes,
2972                                    int con_size_in_bytes,
2973                                    Register t1,
2974                                    Label& slow_case) {
2975   assert(obj == rax, "obj must be in rax, for cmpxchg");
2976   assert_different_registers(obj, var_size_in_bytes, t1);
2977   if (!Universe::heap()->supports_inline_contig_alloc()) {
2978     jmp(slow_case);
2979   } else {
2980     Register end = t1;
2981     Label retry;
2982     bind(retry);
2983     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2984     movptr(obj, heap_top);
2985     if (var_size_in_bytes == noreg) {
2986       lea(end, Address(obj, con_size_in_bytes));
2987     } else {
2988       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2989     }
2990     // if end < obj then we wrapped around => object too long => slow case
2991     cmpptr(end, obj);
2992     jcc(Assembler::below, slow_case);
2993     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2994     jcc(Assembler::above, slow_case);
2995     // Compare obj with the top addr, and if still equal, store the new top addr in
2996     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2997     // it otherwise. Use lock prefix for atomicity on MPs.
2998     locked_cmpxchgptr(end, heap_top);
2999     jcc(Assembler::notEqual, retry);
3000   }
3001 }
3002 
3003 void MacroAssembler::enter() {
3004   push(rbp);
3005   mov(rbp, rsp);
3006 }
3007 
3008 // A 5 byte nop that is safe for patching (see patch_verified_entry)
3009 void MacroAssembler::fat_nop() {
3010   if (UseAddressNop) {
3011     addr_nop_5();
3012   } else {
3013     emit_int8(0x26); // es:
3014     emit_int8(0x2e); // cs:
3015     emit_int8(0x64); // fs:
3016     emit_int8(0x65); // gs:
3017     emit_int8((unsigned char)0x90);
3018   }
3019 }
3020 
3021 void MacroAssembler::fcmp(Register tmp) {
3022   fcmp(tmp, 1, true, true);
3023 }
3024 
3025 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
3026   assert(!pop_right || pop_left, "usage error");
3027   if (VM_Version::supports_cmov()) {
3028     assert(tmp == noreg, "unneeded temp");
3029     if (pop_left) {
3030       fucomip(index);
3031     } else {
3032       fucomi(index);
3033     }
3034     if (pop_right) {
3035       fpop();
3036     }
3037   } else {
3038     assert(tmp != noreg, "need temp");
3039     if (pop_left) {
3040       if (pop_right) {
3041         fcompp();
3042       } else {
3043         fcomp(index);
3044       }
3045     } else {
3046       fcom(index);
3047     }
3048     // convert FPU condition into eflags condition via rax,
3049     save_rax(tmp);
3050     fwait(); fnstsw_ax();
3051     sahf();
3052     restore_rax(tmp);
3053   }
3054   // condition codes set as follows:
3055   //
3056   // CF (corresponds to C0) if x < y
3057   // PF (corresponds to C2) if unordered
3058   // ZF (corresponds to C3) if x = y
3059 }
3060 
3061 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3062   fcmp2int(dst, unordered_is_less, 1, true, true);
3063 }
3064 
3065 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3066   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3067   Label L;
3068   if (unordered_is_less) {
3069     movl(dst, -1);
3070     jcc(Assembler::parity, L);
3071     jcc(Assembler::below , L);
3072     movl(dst, 0);
3073     jcc(Assembler::equal , L);
3074     increment(dst);
3075   } else { // unordered is greater
3076     movl(dst, 1);
3077     jcc(Assembler::parity, L);
3078     jcc(Assembler::above , L);
3079     movl(dst, 0);
3080     jcc(Assembler::equal , L);
3081     decrementl(dst);
3082   }
3083   bind(L);
3084 }
3085 
3086 void MacroAssembler::fld_d(AddressLiteral src) {
3087   fld_d(as_Address(src));
3088 }
3089 
3090 void MacroAssembler::fld_s(AddressLiteral src) {
3091   fld_s(as_Address(src));
3092 }
3093 
3094 void MacroAssembler::fld_x(AddressLiteral src) {
3095   Assembler::fld_x(as_Address(src));
3096 }
3097 
3098 void MacroAssembler::fldcw(AddressLiteral src) {
3099   Assembler::fldcw(as_Address(src));
3100 }
3101 
3102 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3103   if (reachable(src)) {
3104     Assembler::mulpd(dst, as_Address(src));
3105   } else {
3106     lea(rscratch1, src);
3107     Assembler::mulpd(dst, Address(rscratch1, 0));
3108   }
3109 }
3110 
3111 void MacroAssembler::increase_precision() {
3112   subptr(rsp, BytesPerWord);
3113   fnstcw(Address(rsp, 0));
3114   movl(rax, Address(rsp, 0));
3115   orl(rax, 0x300);
3116   push(rax);
3117   fldcw(Address(rsp, 0));
3118   pop(rax);
3119 }
3120 
3121 void MacroAssembler::restore_precision() {
3122   fldcw(Address(rsp, 0));
3123   addptr(rsp, BytesPerWord);
3124 }
3125 
3126 void MacroAssembler::fpop() {
3127   ffree();
3128   fincstp();
3129 }
3130 
3131 void MacroAssembler::load_float(Address src) {
3132   if (UseSSE >= 1) {
3133     movflt(xmm0, src);
3134   } else {
3135     LP64_ONLY(ShouldNotReachHere());
3136     NOT_LP64(fld_s(src));
3137   }
3138 }
3139 
3140 void MacroAssembler::store_float(Address dst) {
3141   if (UseSSE >= 1) {
3142     movflt(dst, xmm0);
3143   } else {
3144     LP64_ONLY(ShouldNotReachHere());
3145     NOT_LP64(fstp_s(dst));
3146   }
3147 }
3148 
3149 void MacroAssembler::load_double(Address src) {
3150   if (UseSSE >= 2) {
3151     movdbl(xmm0, src);
3152   } else {
3153     LP64_ONLY(ShouldNotReachHere());
3154     NOT_LP64(fld_d(src));
3155   }
3156 }
3157 
3158 void MacroAssembler::store_double(Address dst) {
3159   if (UseSSE >= 2) {
3160     movdbl(dst, xmm0);
3161   } else {
3162     LP64_ONLY(ShouldNotReachHere());
3163     NOT_LP64(fstp_d(dst));
3164   }
3165 }
3166 
3167 void MacroAssembler::fremr(Register tmp) {
3168   save_rax(tmp);
3169   { Label L;
3170     bind(L);
3171     fprem();
3172     fwait(); fnstsw_ax();
3173 #ifdef _LP64
3174     testl(rax, 0x400);
3175     jcc(Assembler::notEqual, L);
3176 #else
3177     sahf();
3178     jcc(Assembler::parity, L);
3179 #endif // _LP64
3180   }
3181   restore_rax(tmp);
3182   // Result is in ST0.
3183   // Note: fxch & fpop to get rid of ST1
3184   // (otherwise FPU stack could overflow eventually)
3185   fxch(1);
3186   fpop();
3187 }
3188 
3189 // dst = c = a * b + c
3190 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3191   Assembler::vfmadd231sd(c, a, b);
3192   if (dst != c) {
3193     movdbl(dst, c);
3194   }
3195 }
3196 
3197 // dst = c = a * b + c
3198 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3199   Assembler::vfmadd231ss(c, a, b);
3200   if (dst != c) {
3201     movflt(dst, c);
3202   }
3203 }
3204 
3205 // dst = c = a * b + c
3206 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3207   Assembler::vfmadd231pd(c, a, b, vector_len);
3208   if (dst != c) {
3209     vmovdqu(dst, c);
3210   }
3211 }
3212 
3213 // dst = c = a * b + c
3214 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3215   Assembler::vfmadd231ps(c, a, b, vector_len);
3216   if (dst != c) {
3217     vmovdqu(dst, c);
3218   }
3219 }
3220 
3221 // dst = c = a * b + c
3222 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3223   Assembler::vfmadd231pd(c, a, b, vector_len);
3224   if (dst != c) {
3225     vmovdqu(dst, c);
3226   }
3227 }
3228 
3229 // dst = c = a * b + c
3230 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3231   Assembler::vfmadd231ps(c, a, b, vector_len);
3232   if (dst != c) {
3233     vmovdqu(dst, c);
3234   }
3235 }
3236 
3237 void MacroAssembler::incrementl(AddressLiteral dst) {
3238   if (reachable(dst)) {
3239     incrementl(as_Address(dst));
3240   } else {
3241     lea(rscratch1, dst);
3242     incrementl(Address(rscratch1, 0));
3243   }
3244 }
3245 
3246 void MacroAssembler::incrementl(ArrayAddress dst) {
3247   incrementl(as_Address(dst));
3248 }
3249 
3250 void MacroAssembler::incrementl(Register reg, int value) {
3251   if (value == min_jint) {addl(reg, value) ; return; }
3252   if (value <  0) { decrementl(reg, -value); return; }
3253   if (value == 0) {                        ; return; }
3254   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3255   /* else */      { addl(reg, value)       ; return; }
3256 }
3257 
3258 void MacroAssembler::incrementl(Address dst, int value) {
3259   if (value == min_jint) {addl(dst, value) ; return; }
3260   if (value <  0) { decrementl(dst, -value); return; }
3261   if (value == 0) {                        ; return; }
3262   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3263   /* else */      { addl(dst, value)       ; return; }
3264 }
3265 
3266 void MacroAssembler::jump(AddressLiteral dst) {
3267   if (reachable(dst)) {
3268     jmp_literal(dst.target(), dst.rspec());
3269   } else {
3270     lea(rscratch1, dst);
3271     jmp(rscratch1);
3272   }
3273 }
3274 
3275 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3276   if (reachable(dst)) {
3277     InstructionMark im(this);
3278     relocate(dst.reloc());
3279     const int short_size = 2;
3280     const int long_size = 6;
3281     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3282     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3283       // 0111 tttn #8-bit disp
3284       emit_int8(0x70 | cc);
3285       emit_int8((offs - short_size) & 0xFF);
3286     } else {
3287       // 0000 1111 1000 tttn #32-bit disp
3288       emit_int8(0x0F);
3289       emit_int8((unsigned char)(0x80 | cc));
3290       emit_int32(offs - long_size);
3291     }
3292   } else {
3293 #ifdef ASSERT
3294     warning("reversing conditional branch");
3295 #endif /* ASSERT */
3296     Label skip;
3297     jccb(reverse[cc], skip);
3298     lea(rscratch1, dst);
3299     Assembler::jmp(rscratch1);
3300     bind(skip);
3301   }
3302 }
3303 
3304 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3305   if (reachable(src)) {
3306     Assembler::ldmxcsr(as_Address(src));
3307   } else {
3308     lea(rscratch1, src);
3309     Assembler::ldmxcsr(Address(rscratch1, 0));
3310   }
3311 }
3312 
3313 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3314   int off;
3315   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3316     off = offset();
3317     movsbl(dst, src); // movsxb
3318   } else {
3319     off = load_unsigned_byte(dst, src);
3320     shll(dst, 24);
3321     sarl(dst, 24);
3322   }
3323   return off;
3324 }
3325 
3326 // Note: load_signed_short used to be called load_signed_word.
3327 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3328 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3329 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3330 int MacroAssembler::load_signed_short(Register dst, Address src) {
3331   int off;
3332   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3333     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3334     // version but this is what 64bit has always done. This seems to imply
3335     // that users are only using 32bits worth.
3336     off = offset();
3337     movswl(dst, src); // movsxw
3338   } else {
3339     off = load_unsigned_short(dst, src);
3340     shll(dst, 16);
3341     sarl(dst, 16);
3342   }
3343   return off;
3344 }
3345 
3346 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3347   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3348   // and "3.9 Partial Register Penalties", p. 22).
3349   int off;
3350   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3351     off = offset();
3352     movzbl(dst, src); // movzxb
3353   } else {
3354     xorl(dst, dst);
3355     off = offset();
3356     movb(dst, src);
3357   }
3358   return off;
3359 }
3360 
3361 // Note: load_unsigned_short used to be called load_unsigned_word.
3362 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3363   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3364   // and "3.9 Partial Register Penalties", p. 22).
3365   int off;
3366   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3367     off = offset();
3368     movzwl(dst, src); // movzxw
3369   } else {
3370     xorl(dst, dst);
3371     off = offset();
3372     movw(dst, src);
3373   }
3374   return off;
3375 }
3376 
3377 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3378   switch (size_in_bytes) {
3379 #ifndef _LP64
3380   case  8:
3381     assert(dst2 != noreg, "second dest register required");
3382     movl(dst,  src);
3383     movl(dst2, src.plus_disp(BytesPerInt));
3384     break;
3385 #else
3386   case  8:  movq(dst, src); break;
3387 #endif
3388   case  4:  movl(dst, src); break;
3389   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3390   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3391   default:  ShouldNotReachHere();
3392   }
3393 }
3394 
3395 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3396   switch (size_in_bytes) {
3397 #ifndef _LP64
3398   case  8:
3399     assert(src2 != noreg, "second source register required");
3400     movl(dst,                        src);
3401     movl(dst.plus_disp(BytesPerInt), src2);
3402     break;
3403 #else
3404   case  8:  movq(dst, src); break;
3405 #endif
3406   case  4:  movl(dst, src); break;
3407   case  2:  movw(dst, src); break;
3408   case  1:  movb(dst, src); break;
3409   default:  ShouldNotReachHere();
3410   }
3411 }
3412 
3413 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3414   if (reachable(dst)) {
3415     movl(as_Address(dst), src);
3416   } else {
3417     lea(rscratch1, dst);
3418     movl(Address(rscratch1, 0), src);
3419   }
3420 }
3421 
3422 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3423   if (reachable(src)) {
3424     movl(dst, as_Address(src));
3425   } else {
3426     lea(rscratch1, src);
3427     movl(dst, Address(rscratch1, 0));
3428   }
3429 }
3430 
3431 // C++ bool manipulation
3432 
3433 void MacroAssembler::movbool(Register dst, Address src) {
3434   if(sizeof(bool) == 1)
3435     movb(dst, src);
3436   else if(sizeof(bool) == 2)
3437     movw(dst, src);
3438   else if(sizeof(bool) == 4)
3439     movl(dst, src);
3440   else
3441     // unsupported
3442     ShouldNotReachHere();
3443 }
3444 
3445 void MacroAssembler::movbool(Address dst, bool boolconst) {
3446   if(sizeof(bool) == 1)
3447     movb(dst, (int) boolconst);
3448   else if(sizeof(bool) == 2)
3449     movw(dst, (int) boolconst);
3450   else if(sizeof(bool) == 4)
3451     movl(dst, (int) boolconst);
3452   else
3453     // unsupported
3454     ShouldNotReachHere();
3455 }
3456 
3457 void MacroAssembler::movbool(Address dst, Register src) {
3458   if(sizeof(bool) == 1)
3459     movb(dst, src);
3460   else if(sizeof(bool) == 2)
3461     movw(dst, src);
3462   else if(sizeof(bool) == 4)
3463     movl(dst, src);
3464   else
3465     // unsupported
3466     ShouldNotReachHere();
3467 }
3468 
3469 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3470   movb(as_Address(dst), src);
3471 }
3472 
3473 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3474   if (reachable(src)) {
3475     movdl(dst, as_Address(src));
3476   } else {
3477     lea(rscratch1, src);
3478     movdl(dst, Address(rscratch1, 0));
3479   }
3480 }
3481 
3482 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3483   if (reachable(src)) {
3484     movq(dst, as_Address(src));
3485   } else {
3486     lea(rscratch1, src);
3487     movq(dst, Address(rscratch1, 0));
3488   }
3489 }
3490 
3491 void MacroAssembler::setvectmask(Register dst, Register src) {
3492   Assembler::movl(dst, 1);
3493   Assembler::shlxl(dst, dst, src);
3494   Assembler::decl(dst);
3495   Assembler::kmovdl(k1, dst);
3496   Assembler::movl(dst, src);
3497 }
3498 
3499 void MacroAssembler::restorevectmask() {
3500   Assembler::knotwl(k1, k0);
3501 }
3502 
3503 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3504   if (reachable(src)) {
3505     if (UseXmmLoadAndClearUpper) {
3506       movsd (dst, as_Address(src));
3507     } else {
3508       movlpd(dst, as_Address(src));
3509     }
3510   } else {
3511     lea(rscratch1, src);
3512     if (UseXmmLoadAndClearUpper) {
3513       movsd (dst, Address(rscratch1, 0));
3514     } else {
3515       movlpd(dst, Address(rscratch1, 0));
3516     }
3517   }
3518 }
3519 
3520 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3521   if (reachable(src)) {
3522     movss(dst, as_Address(src));
3523   } else {
3524     lea(rscratch1, src);
3525     movss(dst, Address(rscratch1, 0));
3526   }
3527 }
3528 
3529 void MacroAssembler::movptr(Register dst, Register src) {
3530   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3531 }
3532 
3533 void MacroAssembler::movptr(Register dst, Address src) {
3534   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3535 }
3536 
3537 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3538 void MacroAssembler::movptr(Register dst, intptr_t src) {
3539   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3540 }
3541 
3542 void MacroAssembler::movptr(Address dst, Register src) {
3543   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3544 }
3545 
3546 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3547   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3548     Assembler::vextractf32x4(dst, src, 0);
3549   } else {
3550     Assembler::movdqu(dst, src);
3551   }
3552 }
3553 
3554 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3555   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3556     Assembler::vinsertf32x4(dst, dst, src, 0);
3557   } else {
3558     Assembler::movdqu(dst, src);
3559   }
3560 }
3561 
3562 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3563   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3564     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3565   } else {
3566     Assembler::movdqu(dst, src);
3567   }
3568 }
3569 
3570 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3571   if (reachable(src)) {
3572     movdqu(dst, as_Address(src));
3573   } else {
3574     lea(scratchReg, src);
3575     movdqu(dst, Address(scratchReg, 0));
3576   }
3577 }
3578 
3579 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3580   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3581     vextractf64x4_low(dst, src);
3582   } else {
3583     Assembler::vmovdqu(dst, src);
3584   }
3585 }
3586 
3587 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3588   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3589     vinsertf64x4_low(dst, src);
3590   } else {
3591     Assembler::vmovdqu(dst, src);
3592   }
3593 }
3594 
3595 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3596   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3597     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3598   }
3599   else {
3600     Assembler::vmovdqu(dst, src);
3601   }
3602 }
3603 
3604 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3605   if (reachable(src)) {
3606     vmovdqu(dst, as_Address(src));
3607   }
3608   else {
3609     lea(rscratch1, src);
3610     vmovdqu(dst, Address(rscratch1, 0));
3611   }
3612 }
3613 
3614 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3615   if (reachable(src)) {
3616     Assembler::movdqa(dst, as_Address(src));
3617   } else {
3618     lea(rscratch1, src);
3619     Assembler::movdqa(dst, Address(rscratch1, 0));
3620   }
3621 }
3622 
3623 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3624   if (reachable(src)) {
3625     Assembler::movsd(dst, as_Address(src));
3626   } else {
3627     lea(rscratch1, src);
3628     Assembler::movsd(dst, Address(rscratch1, 0));
3629   }
3630 }
3631 
3632 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3633   if (reachable(src)) {
3634     Assembler::movss(dst, as_Address(src));
3635   } else {
3636     lea(rscratch1, src);
3637     Assembler::movss(dst, Address(rscratch1, 0));
3638   }
3639 }
3640 
3641 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3642   if (reachable(src)) {
3643     Assembler::mulsd(dst, as_Address(src));
3644   } else {
3645     lea(rscratch1, src);
3646     Assembler::mulsd(dst, Address(rscratch1, 0));
3647   }
3648 }
3649 
3650 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3651   if (reachable(src)) {
3652     Assembler::mulss(dst, as_Address(src));
3653   } else {
3654     lea(rscratch1, src);
3655     Assembler::mulss(dst, Address(rscratch1, 0));
3656   }
3657 }
3658 
3659 void MacroAssembler::null_check(Register reg, int offset) {
3660   if (needs_explicit_null_check(offset)) {
3661     // provoke OS NULL exception if reg = NULL by
3662     // accessing M[reg] w/o changing any (non-CC) registers
3663     // NOTE: cmpl is plenty here to provoke a segv
3664     cmpptr(rax, Address(reg, 0));
3665     // Note: should probably use testl(rax, Address(reg, 0));
3666     //       may be shorter code (however, this version of
3667     //       testl needs to be implemented first)
3668   } else {
3669     // nothing to do, (later) access of M[reg + offset]
3670     // will provoke OS NULL exception if reg = NULL
3671   }
3672 }
3673 
3674 void MacroAssembler::os_breakpoint() {
3675   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3676   // (e.g., MSVC can't call ps() otherwise)
3677   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3678 }
3679 
3680 void MacroAssembler::unimplemented(const char* what) {
3681   const char* buf = NULL;
3682   {
3683     ResourceMark rm;
3684     stringStream ss;
3685     ss.print("unimplemented: %s", what);
3686     buf = code_string(ss.as_string());
3687   }
3688   stop(buf);
3689 }
3690 
3691 #ifdef _LP64
3692 #define XSTATE_BV 0x200
3693 #endif
3694 
3695 void MacroAssembler::pop_CPU_state() {
3696   pop_FPU_state();
3697   pop_IU_state();
3698 }
3699 
3700 void MacroAssembler::pop_FPU_state() {
3701 #ifndef _LP64
3702   frstor(Address(rsp, 0));
3703 #else
3704   fxrstor(Address(rsp, 0));
3705 #endif
3706   addptr(rsp, FPUStateSizeInWords * wordSize);
3707 }
3708 
3709 #ifdef ASSERT
3710 void MacroAssembler::stop_if_in_cont(Register cont, const char* name) {
3711   Label no_cont;
3712   movptr(cont, Address(r15_thread, in_bytes(JavaThread::continuation_offset())));
3713   testl(cont, cont);
3714   jcc(Assembler::zero, no_cont);
3715   stop(name);
3716   bind(no_cont);
3717 }
3718 #endif
3719 
3720 void MacroAssembler::pop_IU_state() {
3721   popa();
3722   LP64_ONLY(addq(rsp, 8));
3723   popf();
3724 }
3725 
3726 // Save Integer and Float state
3727 // Warning: Stack must be 16 byte aligned (64bit)
3728 void MacroAssembler::push_CPU_state() {
3729   push_IU_state();
3730   push_FPU_state();
3731 }
3732 
3733 void MacroAssembler::push_FPU_state() {
3734   subptr(rsp, FPUStateSizeInWords * wordSize);
3735 #ifndef _LP64
3736   fnsave(Address(rsp, 0));
3737   fwait();
3738 #else
3739   fxsave(Address(rsp, 0));
3740 #endif // LP64
3741 }
3742 
3743 void MacroAssembler::push_IU_state() {
3744   // Push flags first because pusha kills them
3745   pushf();
3746   // Make sure rsp stays 16-byte aligned
3747   LP64_ONLY(subq(rsp, 8));
3748   pusha();
3749 }
3750 
3751 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3752   if (!java_thread->is_valid()) {
3753     java_thread = rdi;
3754     get_thread(java_thread);
3755   }
3756   // we must set sp to zero to clear frame
3757   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3758   if (clear_fp) {
3759     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3760   }
3761 
3762   // Always clear the pc because it could have been set by make_walkable()
3763   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3764 
3765   vzeroupper();
3766 }
3767 
3768 void MacroAssembler::restore_rax(Register tmp) {
3769   if (tmp == noreg) pop(rax);
3770   else if (tmp != rax) mov(rax, tmp);
3771 }
3772 
3773 void MacroAssembler::round_to(Register reg, int modulus) {
3774   addptr(reg, modulus - 1);
3775   andptr(reg, -modulus);
3776 }
3777 
3778 void MacroAssembler::save_rax(Register tmp) {
3779   if (tmp == noreg) push(rax);
3780   else if (tmp != rax) mov(tmp, rax);
3781 }
3782 
3783 // Write serialization page so VM thread can do a pseudo remote membar.
3784 // We use the current thread pointer to calculate a thread specific
3785 // offset to write to within the page. This minimizes bus traffic
3786 // due to cache line collision.
3787 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3788   movl(tmp, thread);
3789   shrl(tmp, os::get_serialize_page_shift_count());
3790   andl(tmp, (os::vm_page_size() - sizeof(int)));
3791 
3792   Address index(noreg, tmp, Address::times_1);
3793   ExternalAddress page(os::get_memory_serialize_page());
3794 
3795   // Size of store must match masking code above
3796   movl(as_Address(ArrayAddress(page, index)), tmp);
3797 }
3798 
3799 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, Register temp_reg) {
3800   if (SafepointMechanism::uses_thread_local_poll()) {
3801 #ifdef _LP64
3802     assert(thread_reg == r15_thread, "should be");
3803 #else
3804     if (thread_reg == noreg) {
3805       thread_reg = temp_reg;
3806       get_thread(thread_reg);
3807     }
3808 #endif
3809     testb(Address(thread_reg, Thread::polling_page_offset()), SafepointMechanism::poll_bit());
3810     jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
3811   } else {
3812     cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3813         SafepointSynchronize::_not_synchronized);
3814     jcc(Assembler::notEqual, slow_path);
3815   }
3816 }
3817 
3818 // Calls to C land
3819 //
3820 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3821 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3822 // has to be reset to 0. This is required to allow proper stack traversal.
3823 void MacroAssembler::set_last_Java_frame(Register java_thread,
3824                                          Register last_java_sp,
3825                                          Register last_java_fp,
3826                                          address  last_java_pc) {
3827   vzeroupper();
3828   // determine java_thread register
3829   if (!java_thread->is_valid()) {
3830     java_thread = rdi;
3831     get_thread(java_thread);
3832   }
3833   // determine last_java_sp register
3834   if (!last_java_sp->is_valid()) {
3835     last_java_sp = rsp;
3836   }
3837 
3838   // last_java_fp is optional
3839 
3840   if (last_java_fp->is_valid()) {
3841     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3842   }
3843 
3844   // last_java_pc is optional
3845 
3846   if (last_java_pc != NULL) {
3847     lea(Address(java_thread,
3848                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3849         InternalAddress(last_java_pc));
3850 
3851   }
3852   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3853 }
3854 
3855 void MacroAssembler::shlptr(Register dst, int imm8) {
3856   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3857 }
3858 
3859 void MacroAssembler::shrptr(Register dst, int imm8) {
3860   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3861 }
3862 
3863 void MacroAssembler::sign_extend_byte(Register reg) {
3864   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3865     movsbl(reg, reg); // movsxb
3866   } else {
3867     shll(reg, 24);
3868     sarl(reg, 24);
3869   }
3870 }
3871 
3872 void MacroAssembler::sign_extend_short(Register reg) {
3873   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3874     movswl(reg, reg); // movsxw
3875   } else {
3876     shll(reg, 16);
3877     sarl(reg, 16);
3878   }
3879 }
3880 
3881 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3882   assert(reachable(src), "Address should be reachable");
3883   testl(dst, as_Address(src));
3884 }
3885 
3886 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3887   int dst_enc = dst->encoding();
3888   int src_enc = src->encoding();
3889   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3890     Assembler::pcmpeqb(dst, src);
3891   } else if ((dst_enc < 16) && (src_enc < 16)) {
3892     Assembler::pcmpeqb(dst, src);
3893   } else if (src_enc < 16) {
3894     subptr(rsp, 64);
3895     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3896     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3897     Assembler::pcmpeqb(xmm0, src);
3898     movdqu(dst, xmm0);
3899     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3900     addptr(rsp, 64);
3901   } else if (dst_enc < 16) {
3902     subptr(rsp, 64);
3903     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3904     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3905     Assembler::pcmpeqb(dst, xmm0);
3906     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3907     addptr(rsp, 64);
3908   } else {
3909     subptr(rsp, 64);
3910     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3911     subptr(rsp, 64);
3912     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3913     movdqu(xmm0, src);
3914     movdqu(xmm1, dst);
3915     Assembler::pcmpeqb(xmm1, xmm0);
3916     movdqu(dst, xmm1);
3917     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3918     addptr(rsp, 64);
3919     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3920     addptr(rsp, 64);
3921   }
3922 }
3923 
3924 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3925   int dst_enc = dst->encoding();
3926   int src_enc = src->encoding();
3927   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3928     Assembler::pcmpeqw(dst, src);
3929   } else if ((dst_enc < 16) && (src_enc < 16)) {
3930     Assembler::pcmpeqw(dst, src);
3931   } else if (src_enc < 16) {
3932     subptr(rsp, 64);
3933     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3934     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3935     Assembler::pcmpeqw(xmm0, src);
3936     movdqu(dst, xmm0);
3937     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3938     addptr(rsp, 64);
3939   } else if (dst_enc < 16) {
3940     subptr(rsp, 64);
3941     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3942     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3943     Assembler::pcmpeqw(dst, xmm0);
3944     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3945     addptr(rsp, 64);
3946   } else {
3947     subptr(rsp, 64);
3948     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3949     subptr(rsp, 64);
3950     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3951     movdqu(xmm0, src);
3952     movdqu(xmm1, dst);
3953     Assembler::pcmpeqw(xmm1, xmm0);
3954     movdqu(dst, xmm1);
3955     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3956     addptr(rsp, 64);
3957     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3958     addptr(rsp, 64);
3959   }
3960 }
3961 
3962 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3963   int dst_enc = dst->encoding();
3964   if (dst_enc < 16) {
3965     Assembler::pcmpestri(dst, src, imm8);
3966   } else {
3967     subptr(rsp, 64);
3968     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3969     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3970     Assembler::pcmpestri(xmm0, src, imm8);
3971     movdqu(dst, xmm0);
3972     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3973     addptr(rsp, 64);
3974   }
3975 }
3976 
3977 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3978   int dst_enc = dst->encoding();
3979   int src_enc = src->encoding();
3980   if ((dst_enc < 16) && (src_enc < 16)) {
3981     Assembler::pcmpestri(dst, src, imm8);
3982   } else if (src_enc < 16) {
3983     subptr(rsp, 64);
3984     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3985     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3986     Assembler::pcmpestri(xmm0, src, imm8);
3987     movdqu(dst, xmm0);
3988     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3989     addptr(rsp, 64);
3990   } else if (dst_enc < 16) {
3991     subptr(rsp, 64);
3992     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3993     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3994     Assembler::pcmpestri(dst, xmm0, imm8);
3995     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3996     addptr(rsp, 64);
3997   } else {
3998     subptr(rsp, 64);
3999     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4000     subptr(rsp, 64);
4001     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4002     movdqu(xmm0, src);
4003     movdqu(xmm1, dst);
4004     Assembler::pcmpestri(xmm1, xmm0, imm8);
4005     movdqu(dst, xmm1);
4006     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4007     addptr(rsp, 64);
4008     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4009     addptr(rsp, 64);
4010   }
4011 }
4012 
4013 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
4014   int dst_enc = dst->encoding();
4015   int src_enc = src->encoding();
4016   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4017     Assembler::pmovzxbw(dst, src);
4018   } else if ((dst_enc < 16) && (src_enc < 16)) {
4019     Assembler::pmovzxbw(dst, src);
4020   } else if (src_enc < 16) {
4021     subptr(rsp, 64);
4022     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4023     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4024     Assembler::pmovzxbw(xmm0, src);
4025     movdqu(dst, xmm0);
4026     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4027     addptr(rsp, 64);
4028   } else if (dst_enc < 16) {
4029     subptr(rsp, 64);
4030     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4031     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4032     Assembler::pmovzxbw(dst, xmm0);
4033     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4034     addptr(rsp, 64);
4035   } else {
4036     subptr(rsp, 64);
4037     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4038     subptr(rsp, 64);
4039     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4040     movdqu(xmm0, src);
4041     movdqu(xmm1, dst);
4042     Assembler::pmovzxbw(xmm1, xmm0);
4043     movdqu(dst, xmm1);
4044     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4045     addptr(rsp, 64);
4046     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4047     addptr(rsp, 64);
4048   }
4049 }
4050 
4051 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4052   int dst_enc = dst->encoding();
4053   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4054     Assembler::pmovzxbw(dst, src);
4055   } else if (dst_enc < 16) {
4056     Assembler::pmovzxbw(dst, src);
4057   } else {
4058     subptr(rsp, 64);
4059     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4060     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4061     Assembler::pmovzxbw(xmm0, src);
4062     movdqu(dst, xmm0);
4063     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4064     addptr(rsp, 64);
4065   }
4066 }
4067 
4068 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4069   int src_enc = src->encoding();
4070   if (src_enc < 16) {
4071     Assembler::pmovmskb(dst, src);
4072   } else {
4073     subptr(rsp, 64);
4074     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4075     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4076     Assembler::pmovmskb(dst, xmm0);
4077     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4078     addptr(rsp, 64);
4079   }
4080 }
4081 
4082 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4083   int dst_enc = dst->encoding();
4084   int src_enc = src->encoding();
4085   if ((dst_enc < 16) && (src_enc < 16)) {
4086     Assembler::ptest(dst, src);
4087   } else if (src_enc < 16) {
4088     subptr(rsp, 64);
4089     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4090     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4091     Assembler::ptest(xmm0, src);
4092     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4093     addptr(rsp, 64);
4094   } else if (dst_enc < 16) {
4095     subptr(rsp, 64);
4096     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4097     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4098     Assembler::ptest(dst, xmm0);
4099     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4100     addptr(rsp, 64);
4101   } else {
4102     subptr(rsp, 64);
4103     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4104     subptr(rsp, 64);
4105     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4106     movdqu(xmm0, src);
4107     movdqu(xmm1, dst);
4108     Assembler::ptest(xmm1, xmm0);
4109     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4110     addptr(rsp, 64);
4111     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4112     addptr(rsp, 64);
4113   }
4114 }
4115 
4116 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4117   if (reachable(src)) {
4118     Assembler::sqrtsd(dst, as_Address(src));
4119   } else {
4120     lea(rscratch1, src);
4121     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4122   }
4123 }
4124 
4125 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4126   if (reachable(src)) {
4127     Assembler::sqrtss(dst, as_Address(src));
4128   } else {
4129     lea(rscratch1, src);
4130     Assembler::sqrtss(dst, Address(rscratch1, 0));
4131   }
4132 }
4133 
4134 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4135   if (reachable(src)) {
4136     Assembler::subsd(dst, as_Address(src));
4137   } else {
4138     lea(rscratch1, src);
4139     Assembler::subsd(dst, Address(rscratch1, 0));
4140   }
4141 }
4142 
4143 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4144   if (reachable(src)) {
4145     Assembler::subss(dst, as_Address(src));
4146   } else {
4147     lea(rscratch1, src);
4148     Assembler::subss(dst, Address(rscratch1, 0));
4149   }
4150 }
4151 
4152 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4153   if (reachable(src)) {
4154     Assembler::ucomisd(dst, as_Address(src));
4155   } else {
4156     lea(rscratch1, src);
4157     Assembler::ucomisd(dst, Address(rscratch1, 0));
4158   }
4159 }
4160 
4161 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4162   if (reachable(src)) {
4163     Assembler::ucomiss(dst, as_Address(src));
4164   } else {
4165     lea(rscratch1, src);
4166     Assembler::ucomiss(dst, Address(rscratch1, 0));
4167   }
4168 }
4169 
4170 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4171   // Used in sign-bit flipping with aligned address.
4172   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4173   if (reachable(src)) {
4174     Assembler::xorpd(dst, as_Address(src));
4175   } else {
4176     lea(rscratch1, src);
4177     Assembler::xorpd(dst, Address(rscratch1, 0));
4178   }
4179 }
4180 
4181 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4182   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4183     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4184   }
4185   else {
4186     Assembler::xorpd(dst, src);
4187   }
4188 }
4189 
4190 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4191   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4192     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4193   } else {
4194     Assembler::xorps(dst, src);
4195   }
4196 }
4197 
4198 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4199   // Used in sign-bit flipping with aligned address.
4200   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4201   if (reachable(src)) {
4202     Assembler::xorps(dst, as_Address(src));
4203   } else {
4204     lea(rscratch1, src);
4205     Assembler::xorps(dst, Address(rscratch1, 0));
4206   }
4207 }
4208 
4209 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4210   // Used in sign-bit flipping with aligned address.
4211   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4212   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4213   if (reachable(src)) {
4214     Assembler::pshufb(dst, as_Address(src));
4215   } else {
4216     lea(rscratch1, src);
4217     Assembler::pshufb(dst, Address(rscratch1, 0));
4218   }
4219 }
4220 
4221 // AVX 3-operands instructions
4222 
4223 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4224   if (reachable(src)) {
4225     vaddsd(dst, nds, as_Address(src));
4226   } else {
4227     lea(rscratch1, src);
4228     vaddsd(dst, nds, Address(rscratch1, 0));
4229   }
4230 }
4231 
4232 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4233   if (reachable(src)) {
4234     vaddss(dst, nds, as_Address(src));
4235   } else {
4236     lea(rscratch1, src);
4237     vaddss(dst, nds, Address(rscratch1, 0));
4238   }
4239 }
4240 
4241 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4242   int dst_enc = dst->encoding();
4243   int nds_enc = nds->encoding();
4244   int src_enc = src->encoding();
4245   if ((dst_enc < 16) && (nds_enc < 16)) {
4246     vandps(dst, nds, negate_field, vector_len);
4247   } else if ((src_enc < 16) && (dst_enc < 16)) {
4248     evmovdqul(src, nds, Assembler::AVX_512bit);
4249     vandps(dst, src, negate_field, vector_len);
4250   } else if (src_enc < 16) {
4251     evmovdqul(src, nds, Assembler::AVX_512bit);
4252     vandps(src, src, negate_field, vector_len);
4253     evmovdqul(dst, src, Assembler::AVX_512bit);
4254   } else if (dst_enc < 16) {
4255     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4256     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4257     vandps(dst, xmm0, negate_field, vector_len);
4258     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4259   } else {
4260     if (src_enc != dst_enc) {
4261       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4262       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4263       vandps(xmm0, xmm0, negate_field, vector_len);
4264       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4265       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4266     } else {
4267       subptr(rsp, 64);
4268       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4269       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4270       vandps(xmm0, xmm0, negate_field, vector_len);
4271       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4272       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4273       addptr(rsp, 64);
4274     }
4275   }
4276 }
4277 
4278 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4279   int dst_enc = dst->encoding();
4280   int nds_enc = nds->encoding();
4281   int src_enc = src->encoding();
4282   if ((dst_enc < 16) && (nds_enc < 16)) {
4283     vandpd(dst, nds, negate_field, vector_len);
4284   } else if ((src_enc < 16) && (dst_enc < 16)) {
4285     evmovdqul(src, nds, Assembler::AVX_512bit);
4286     vandpd(dst, src, negate_field, vector_len);
4287   } else if (src_enc < 16) {
4288     evmovdqul(src, nds, Assembler::AVX_512bit);
4289     vandpd(src, src, negate_field, vector_len);
4290     evmovdqul(dst, src, Assembler::AVX_512bit);
4291   } else if (dst_enc < 16) {
4292     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4293     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4294     vandpd(dst, xmm0, negate_field, vector_len);
4295     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4296   } else {
4297     if (src_enc != dst_enc) {
4298       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4299       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4300       vandpd(xmm0, xmm0, negate_field, vector_len);
4301       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4302       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4303     } else {
4304       subptr(rsp, 64);
4305       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4306       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4307       vandpd(xmm0, xmm0, negate_field, vector_len);
4308       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4309       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4310       addptr(rsp, 64);
4311     }
4312   }
4313 }
4314 
4315 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4316   int dst_enc = dst->encoding();
4317   int nds_enc = nds->encoding();
4318   int src_enc = src->encoding();
4319   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4320     Assembler::vpaddb(dst, nds, src, vector_len);
4321   } else if ((dst_enc < 16) && (src_enc < 16)) {
4322     Assembler::vpaddb(dst, dst, src, vector_len);
4323   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4324     // use nds as scratch for src
4325     evmovdqul(nds, src, Assembler::AVX_512bit);
4326     Assembler::vpaddb(dst, dst, nds, vector_len);
4327   } else if ((src_enc < 16) && (nds_enc < 16)) {
4328     // use nds as scratch for dst
4329     evmovdqul(nds, dst, Assembler::AVX_512bit);
4330     Assembler::vpaddb(nds, nds, src, vector_len);
4331     evmovdqul(dst, nds, Assembler::AVX_512bit);
4332   } else if (dst_enc < 16) {
4333     // use nds as scatch for xmm0 to hold src
4334     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4335     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4336     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4337     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4338   } else {
4339     // worse case scenario, all regs are in the upper bank
4340     subptr(rsp, 64);
4341     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4342     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4343     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4344     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4345     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4346     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4347     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4348     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4349     addptr(rsp, 64);
4350   }
4351 }
4352 
4353 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4354   int dst_enc = dst->encoding();
4355   int nds_enc = nds->encoding();
4356   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4357     Assembler::vpaddb(dst, nds, src, vector_len);
4358   } else if (dst_enc < 16) {
4359     Assembler::vpaddb(dst, dst, src, vector_len);
4360   } else if (nds_enc < 16) {
4361     // implies dst_enc in upper bank with src as scratch
4362     evmovdqul(nds, dst, Assembler::AVX_512bit);
4363     Assembler::vpaddb(nds, nds, src, vector_len);
4364     evmovdqul(dst, nds, Assembler::AVX_512bit);
4365   } else {
4366     // worse case scenario, all regs in upper bank
4367     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4368     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4369     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4370     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4371   }
4372 }
4373 
4374 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4375   int dst_enc = dst->encoding();
4376   int nds_enc = nds->encoding();
4377   int src_enc = src->encoding();
4378   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4379     Assembler::vpaddw(dst, nds, src, vector_len);
4380   } else if ((dst_enc < 16) && (src_enc < 16)) {
4381     Assembler::vpaddw(dst, dst, src, vector_len);
4382   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4383     // use nds as scratch for src
4384     evmovdqul(nds, src, Assembler::AVX_512bit);
4385     Assembler::vpaddw(dst, dst, nds, vector_len);
4386   } else if ((src_enc < 16) && (nds_enc < 16)) {
4387     // use nds as scratch for dst
4388     evmovdqul(nds, dst, Assembler::AVX_512bit);
4389     Assembler::vpaddw(nds, nds, src, vector_len);
4390     evmovdqul(dst, nds, Assembler::AVX_512bit);
4391   } else if (dst_enc < 16) {
4392     // use nds as scatch for xmm0 to hold src
4393     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4394     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4395     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4396     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4397   } else {
4398     // worse case scenario, all regs are in the upper bank
4399     subptr(rsp, 64);
4400     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4401     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4402     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4403     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4404     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4405     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4406     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4407     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4408     addptr(rsp, 64);
4409   }
4410 }
4411 
4412 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4413   int dst_enc = dst->encoding();
4414   int nds_enc = nds->encoding();
4415   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4416     Assembler::vpaddw(dst, nds, src, vector_len);
4417   } else if (dst_enc < 16) {
4418     Assembler::vpaddw(dst, dst, src, vector_len);
4419   } else if (nds_enc < 16) {
4420     // implies dst_enc in upper bank with src as scratch
4421     evmovdqul(nds, dst, Assembler::AVX_512bit);
4422     Assembler::vpaddw(nds, nds, src, vector_len);
4423     evmovdqul(dst, nds, Assembler::AVX_512bit);
4424   } else {
4425     // worse case scenario, all regs in upper bank
4426     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4427     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4428     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4429     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4430   }
4431 }
4432 
4433 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4434   if (reachable(src)) {
4435     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4436   } else {
4437     lea(rscratch1, src);
4438     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4439   }
4440 }
4441 
4442 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4443   int dst_enc = dst->encoding();
4444   int src_enc = src->encoding();
4445   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4446     Assembler::vpbroadcastw(dst, src);
4447   } else if ((dst_enc < 16) && (src_enc < 16)) {
4448     Assembler::vpbroadcastw(dst, src);
4449   } else if (src_enc < 16) {
4450     subptr(rsp, 64);
4451     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4452     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4453     Assembler::vpbroadcastw(xmm0, src);
4454     movdqu(dst, xmm0);
4455     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4456     addptr(rsp, 64);
4457   } else if (dst_enc < 16) {
4458     subptr(rsp, 64);
4459     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4460     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4461     Assembler::vpbroadcastw(dst, xmm0);
4462     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4463     addptr(rsp, 64);
4464   } else {
4465     subptr(rsp, 64);
4466     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4467     subptr(rsp, 64);
4468     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4469     movdqu(xmm0, src);
4470     movdqu(xmm1, dst);
4471     Assembler::vpbroadcastw(xmm1, xmm0);
4472     movdqu(dst, xmm1);
4473     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4474     addptr(rsp, 64);
4475     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4476     addptr(rsp, 64);
4477   }
4478 }
4479 
4480 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4481   int dst_enc = dst->encoding();
4482   int nds_enc = nds->encoding();
4483   int src_enc = src->encoding();
4484   assert(dst_enc == nds_enc, "");
4485   if ((dst_enc < 16) && (src_enc < 16)) {
4486     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4487   } else if (src_enc < 16) {
4488     subptr(rsp, 64);
4489     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4490     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4491     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4492     movdqu(dst, xmm0);
4493     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4494     addptr(rsp, 64);
4495   } else if (dst_enc < 16) {
4496     subptr(rsp, 64);
4497     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4498     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4499     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4500     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4501     addptr(rsp, 64);
4502   } else {
4503     subptr(rsp, 64);
4504     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4505     subptr(rsp, 64);
4506     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4507     movdqu(xmm0, src);
4508     movdqu(xmm1, dst);
4509     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4510     movdqu(dst, xmm1);
4511     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4512     addptr(rsp, 64);
4513     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4514     addptr(rsp, 64);
4515   }
4516 }
4517 
4518 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4519   int dst_enc = dst->encoding();
4520   int nds_enc = nds->encoding();
4521   int src_enc = src->encoding();
4522   assert(dst_enc == nds_enc, "");
4523   if ((dst_enc < 16) && (src_enc < 16)) {
4524     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4525   } else if (src_enc < 16) {
4526     subptr(rsp, 64);
4527     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4528     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4529     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4530     movdqu(dst, xmm0);
4531     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4532     addptr(rsp, 64);
4533   } else if (dst_enc < 16) {
4534     subptr(rsp, 64);
4535     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4536     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4537     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4538     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4539     addptr(rsp, 64);
4540   } else {
4541     subptr(rsp, 64);
4542     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4543     subptr(rsp, 64);
4544     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4545     movdqu(xmm0, src);
4546     movdqu(xmm1, dst);
4547     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4548     movdqu(dst, xmm1);
4549     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4550     addptr(rsp, 64);
4551     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4552     addptr(rsp, 64);
4553   }
4554 }
4555 
4556 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4557   int dst_enc = dst->encoding();
4558   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4559     Assembler::vpmovzxbw(dst, src, vector_len);
4560   } else if (dst_enc < 16) {
4561     Assembler::vpmovzxbw(dst, src, vector_len);
4562   } else {
4563     subptr(rsp, 64);
4564     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4565     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4566     Assembler::vpmovzxbw(xmm0, src, vector_len);
4567     movdqu(dst, xmm0);
4568     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4569     addptr(rsp, 64);
4570   }
4571 }
4572 
4573 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4574   int src_enc = src->encoding();
4575   if (src_enc < 16) {
4576     Assembler::vpmovmskb(dst, src);
4577   } else {
4578     subptr(rsp, 64);
4579     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4580     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4581     Assembler::vpmovmskb(dst, xmm0);
4582     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4583     addptr(rsp, 64);
4584   }
4585 }
4586 
4587 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4588   int dst_enc = dst->encoding();
4589   int nds_enc = nds->encoding();
4590   int src_enc = src->encoding();
4591   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4592     Assembler::vpmullw(dst, nds, src, vector_len);
4593   } else if ((dst_enc < 16) && (src_enc < 16)) {
4594     Assembler::vpmullw(dst, dst, src, vector_len);
4595   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4596     // use nds as scratch for src
4597     evmovdqul(nds, src, Assembler::AVX_512bit);
4598     Assembler::vpmullw(dst, dst, nds, vector_len);
4599   } else if ((src_enc < 16) && (nds_enc < 16)) {
4600     // use nds as scratch for dst
4601     evmovdqul(nds, dst, Assembler::AVX_512bit);
4602     Assembler::vpmullw(nds, nds, src, vector_len);
4603     evmovdqul(dst, nds, Assembler::AVX_512bit);
4604   } else if (dst_enc < 16) {
4605     // use nds as scatch for xmm0 to hold src
4606     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4607     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4608     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4609     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4610   } else {
4611     // worse case scenario, all regs are in the upper bank
4612     subptr(rsp, 64);
4613     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4614     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4615     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4616     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4617     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4618     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4619     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4620     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4621     addptr(rsp, 64);
4622   }
4623 }
4624 
4625 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4626   int dst_enc = dst->encoding();
4627   int nds_enc = nds->encoding();
4628   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4629     Assembler::vpmullw(dst, nds, src, vector_len);
4630   } else if (dst_enc < 16) {
4631     Assembler::vpmullw(dst, dst, src, vector_len);
4632   } else if (nds_enc < 16) {
4633     // implies dst_enc in upper bank with src as scratch
4634     evmovdqul(nds, dst, Assembler::AVX_512bit);
4635     Assembler::vpmullw(nds, nds, src, vector_len);
4636     evmovdqul(dst, nds, Assembler::AVX_512bit);
4637   } else {
4638     // worse case scenario, all regs in upper bank
4639     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4640     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4641     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4642     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4643   }
4644 }
4645 
4646 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4647   int dst_enc = dst->encoding();
4648   int nds_enc = nds->encoding();
4649   int src_enc = src->encoding();
4650   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4651     Assembler::vpsubb(dst, nds, src, vector_len);
4652   } else if ((dst_enc < 16) && (src_enc < 16)) {
4653     Assembler::vpsubb(dst, dst, src, vector_len);
4654   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4655     // use nds as scratch for src
4656     evmovdqul(nds, src, Assembler::AVX_512bit);
4657     Assembler::vpsubb(dst, dst, nds, vector_len);
4658   } else if ((src_enc < 16) && (nds_enc < 16)) {
4659     // use nds as scratch for dst
4660     evmovdqul(nds, dst, Assembler::AVX_512bit);
4661     Assembler::vpsubb(nds, nds, src, vector_len);
4662     evmovdqul(dst, nds, Assembler::AVX_512bit);
4663   } else if (dst_enc < 16) {
4664     // use nds as scatch for xmm0 to hold src
4665     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4666     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4667     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4668     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4669   } else {
4670     // worse case scenario, all regs are in the upper bank
4671     subptr(rsp, 64);
4672     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4673     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4674     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4675     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4676     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4677     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4678     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4679     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4680     addptr(rsp, 64);
4681   }
4682 }
4683 
4684 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4685   int dst_enc = dst->encoding();
4686   int nds_enc = nds->encoding();
4687   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4688     Assembler::vpsubb(dst, nds, src, vector_len);
4689   } else if (dst_enc < 16) {
4690     Assembler::vpsubb(dst, dst, src, vector_len);
4691   } else if (nds_enc < 16) {
4692     // implies dst_enc in upper bank with src as scratch
4693     evmovdqul(nds, dst, Assembler::AVX_512bit);
4694     Assembler::vpsubb(nds, nds, src, vector_len);
4695     evmovdqul(dst, nds, Assembler::AVX_512bit);
4696   } else {
4697     // worse case scenario, all regs in upper bank
4698     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4699     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4700     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4701     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4702   }
4703 }
4704 
4705 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4706   int dst_enc = dst->encoding();
4707   int nds_enc = nds->encoding();
4708   int src_enc = src->encoding();
4709   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4710     Assembler::vpsubw(dst, nds, src, vector_len);
4711   } else if ((dst_enc < 16) && (src_enc < 16)) {
4712     Assembler::vpsubw(dst, dst, src, vector_len);
4713   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4714     // use nds as scratch for src
4715     evmovdqul(nds, src, Assembler::AVX_512bit);
4716     Assembler::vpsubw(dst, dst, nds, vector_len);
4717   } else if ((src_enc < 16) && (nds_enc < 16)) {
4718     // use nds as scratch for dst
4719     evmovdqul(nds, dst, Assembler::AVX_512bit);
4720     Assembler::vpsubw(nds, nds, src, vector_len);
4721     evmovdqul(dst, nds, Assembler::AVX_512bit);
4722   } else if (dst_enc < 16) {
4723     // use nds as scatch for xmm0 to hold src
4724     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4725     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4726     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4727     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4728   } else {
4729     // worse case scenario, all regs are in the upper bank
4730     subptr(rsp, 64);
4731     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4732     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4733     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4734     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4735     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4736     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4737     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4738     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4739     addptr(rsp, 64);
4740   }
4741 }
4742 
4743 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4744   int dst_enc = dst->encoding();
4745   int nds_enc = nds->encoding();
4746   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4747     Assembler::vpsubw(dst, nds, src, vector_len);
4748   } else if (dst_enc < 16) {
4749     Assembler::vpsubw(dst, dst, src, vector_len);
4750   } else if (nds_enc < 16) {
4751     // implies dst_enc in upper bank with src as scratch
4752     evmovdqul(nds, dst, Assembler::AVX_512bit);
4753     Assembler::vpsubw(nds, nds, src, vector_len);
4754     evmovdqul(dst, nds, Assembler::AVX_512bit);
4755   } else {
4756     // worse case scenario, all regs in upper bank
4757     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4758     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4759     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4760     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4761   }
4762 }
4763 
4764 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4765   int dst_enc = dst->encoding();
4766   int nds_enc = nds->encoding();
4767   int shift_enc = shift->encoding();
4768   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4769     Assembler::vpsraw(dst, nds, shift, vector_len);
4770   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4771     Assembler::vpsraw(dst, dst, shift, vector_len);
4772   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4773     // use nds_enc as scratch with shift
4774     evmovdqul(nds, shift, Assembler::AVX_512bit);
4775     Assembler::vpsraw(dst, dst, nds, vector_len);
4776   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4777     // use nds as scratch with dst
4778     evmovdqul(nds, dst, Assembler::AVX_512bit);
4779     Assembler::vpsraw(nds, nds, shift, vector_len);
4780     evmovdqul(dst, nds, Assembler::AVX_512bit);
4781   } else if (dst_enc < 16) {
4782     // use nds to save a copy of xmm0 and hold shift
4783     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4784     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4785     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4786     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4787   } else if (nds_enc < 16) {
4788     // use nds as dest as temps
4789     evmovdqul(nds, dst, Assembler::AVX_512bit);
4790     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4791     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4792     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4793     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4794     evmovdqul(dst, nds, Assembler::AVX_512bit);
4795   } else {
4796     // worse case scenario, all regs are in the upper bank
4797     subptr(rsp, 64);
4798     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4799     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4800     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4801     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4802     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4803     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4804     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4805     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4806     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4807     addptr(rsp, 64);
4808   }
4809 }
4810 
4811 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4812   int dst_enc = dst->encoding();
4813   int nds_enc = nds->encoding();
4814   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4815     Assembler::vpsraw(dst, nds, shift, vector_len);
4816   } else if (dst_enc < 16) {
4817     Assembler::vpsraw(dst, dst, shift, vector_len);
4818   } else if (nds_enc < 16) {
4819     // use nds as scratch
4820     evmovdqul(nds, dst, Assembler::AVX_512bit);
4821     Assembler::vpsraw(nds, nds, shift, vector_len);
4822     evmovdqul(dst, nds, Assembler::AVX_512bit);
4823   } else {
4824     // use nds as scratch for xmm0
4825     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4826     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4827     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4828     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4829   }
4830 }
4831 
4832 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4833   int dst_enc = dst->encoding();
4834   int nds_enc = nds->encoding();
4835   int shift_enc = shift->encoding();
4836   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4837     Assembler::vpsrlw(dst, nds, shift, vector_len);
4838   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4839     Assembler::vpsrlw(dst, dst, shift, vector_len);
4840   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4841     // use nds_enc as scratch with shift
4842     evmovdqul(nds, shift, Assembler::AVX_512bit);
4843     Assembler::vpsrlw(dst, dst, nds, vector_len);
4844   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4845     // use nds as scratch with dst
4846     evmovdqul(nds, dst, Assembler::AVX_512bit);
4847     Assembler::vpsrlw(nds, nds, shift, vector_len);
4848     evmovdqul(dst, nds, Assembler::AVX_512bit);
4849   } else if (dst_enc < 16) {
4850     // use nds to save a copy of xmm0 and hold shift
4851     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4852     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4853     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4854     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4855   } else if (nds_enc < 16) {
4856     // use nds as dest as temps
4857     evmovdqul(nds, dst, Assembler::AVX_512bit);
4858     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4859     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4860     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4861     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4862     evmovdqul(dst, nds, Assembler::AVX_512bit);
4863   } else {
4864     // worse case scenario, all regs are in the upper bank
4865     subptr(rsp, 64);
4866     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4867     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4868     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4869     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4870     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4871     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4872     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4873     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4874     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4875     addptr(rsp, 64);
4876   }
4877 }
4878 
4879 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4880   int dst_enc = dst->encoding();
4881   int nds_enc = nds->encoding();
4882   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4883     Assembler::vpsrlw(dst, nds, shift, vector_len);
4884   } else if (dst_enc < 16) {
4885     Assembler::vpsrlw(dst, dst, shift, vector_len);
4886   } else if (nds_enc < 16) {
4887     // use nds as scratch
4888     evmovdqul(nds, dst, Assembler::AVX_512bit);
4889     Assembler::vpsrlw(nds, nds, shift, vector_len);
4890     evmovdqul(dst, nds, Assembler::AVX_512bit);
4891   } else {
4892     // use nds as scratch for xmm0
4893     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4894     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4895     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4896     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4897   }
4898 }
4899 
4900 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4901   int dst_enc = dst->encoding();
4902   int nds_enc = nds->encoding();
4903   int shift_enc = shift->encoding();
4904   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4905     Assembler::vpsllw(dst, nds, shift, vector_len);
4906   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4907     Assembler::vpsllw(dst, dst, shift, vector_len);
4908   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4909     // use nds_enc as scratch with shift
4910     evmovdqul(nds, shift, Assembler::AVX_512bit);
4911     Assembler::vpsllw(dst, dst, nds, vector_len);
4912   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4913     // use nds as scratch with dst
4914     evmovdqul(nds, dst, Assembler::AVX_512bit);
4915     Assembler::vpsllw(nds, nds, shift, vector_len);
4916     evmovdqul(dst, nds, Assembler::AVX_512bit);
4917   } else if (dst_enc < 16) {
4918     // use nds to save a copy of xmm0 and hold shift
4919     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4920     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4921     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4922     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4923   } else if (nds_enc < 16) {
4924     // use nds as dest as temps
4925     evmovdqul(nds, dst, Assembler::AVX_512bit);
4926     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4927     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4928     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4929     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4930     evmovdqul(dst, nds, Assembler::AVX_512bit);
4931   } else {
4932     // worse case scenario, all regs are in the upper bank
4933     subptr(rsp, 64);
4934     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4935     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4936     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4937     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4938     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4939     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4940     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4941     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4942     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4943     addptr(rsp, 64);
4944   }
4945 }
4946 
4947 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4948   int dst_enc = dst->encoding();
4949   int nds_enc = nds->encoding();
4950   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4951     Assembler::vpsllw(dst, nds, shift, vector_len);
4952   } else if (dst_enc < 16) {
4953     Assembler::vpsllw(dst, dst, shift, vector_len);
4954   } else if (nds_enc < 16) {
4955     // use nds as scratch
4956     evmovdqul(nds, dst, Assembler::AVX_512bit);
4957     Assembler::vpsllw(nds, nds, shift, vector_len);
4958     evmovdqul(dst, nds, Assembler::AVX_512bit);
4959   } else {
4960     // use nds as scratch for xmm0
4961     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4962     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4963     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4964     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4965   }
4966 }
4967 
4968 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4969   int dst_enc = dst->encoding();
4970   int src_enc = src->encoding();
4971   if ((dst_enc < 16) && (src_enc < 16)) {
4972     Assembler::vptest(dst, src);
4973   } else if (src_enc < 16) {
4974     subptr(rsp, 64);
4975     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4976     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4977     Assembler::vptest(xmm0, src);
4978     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4979     addptr(rsp, 64);
4980   } else if (dst_enc < 16) {
4981     subptr(rsp, 64);
4982     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4983     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4984     Assembler::vptest(dst, xmm0);
4985     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4986     addptr(rsp, 64);
4987   } else {
4988     subptr(rsp, 64);
4989     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4990     subptr(rsp, 64);
4991     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4992     movdqu(xmm0, src);
4993     movdqu(xmm1, dst);
4994     Assembler::vptest(xmm1, xmm0);
4995     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4996     addptr(rsp, 64);
4997     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4998     addptr(rsp, 64);
4999   }
5000 }
5001 
5002 // This instruction exists within macros, ergo we cannot control its input
5003 // when emitted through those patterns.
5004 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
5005   if (VM_Version::supports_avx512nobw()) {
5006     int dst_enc = dst->encoding();
5007     int src_enc = src->encoding();
5008     if (dst_enc == src_enc) {
5009       if (dst_enc < 16) {
5010         Assembler::punpcklbw(dst, src);
5011       } else {
5012         subptr(rsp, 64);
5013         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5014         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5015         Assembler::punpcklbw(xmm0, xmm0);
5016         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5017         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5018         addptr(rsp, 64);
5019       }
5020     } else {
5021       if ((src_enc < 16) && (dst_enc < 16)) {
5022         Assembler::punpcklbw(dst, src);
5023       } else if (src_enc < 16) {
5024         subptr(rsp, 64);
5025         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5026         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5027         Assembler::punpcklbw(xmm0, src);
5028         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5029         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5030         addptr(rsp, 64);
5031       } else if (dst_enc < 16) {
5032         subptr(rsp, 64);
5033         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5034         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5035         Assembler::punpcklbw(dst, xmm0);
5036         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5037         addptr(rsp, 64);
5038       } else {
5039         subptr(rsp, 64);
5040         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5041         subptr(rsp, 64);
5042         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5043         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5044         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5045         Assembler::punpcklbw(xmm0, xmm1);
5046         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5047         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5048         addptr(rsp, 64);
5049         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5050         addptr(rsp, 64);
5051       }
5052     }
5053   } else {
5054     Assembler::punpcklbw(dst, src);
5055   }
5056 }
5057 
5058 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
5059   if (VM_Version::supports_avx512vl()) {
5060     Assembler::pshufd(dst, src, mode);
5061   } else {
5062     int dst_enc = dst->encoding();
5063     if (dst_enc < 16) {
5064       Assembler::pshufd(dst, src, mode);
5065     } else {
5066       subptr(rsp, 64);
5067       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5068       Assembler::pshufd(xmm0, src, mode);
5069       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5070       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5071       addptr(rsp, 64);
5072     }
5073   }
5074 }
5075 
5076 // This instruction exists within macros, ergo we cannot control its input
5077 // when emitted through those patterns.
5078 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5079   if (VM_Version::supports_avx512nobw()) {
5080     int dst_enc = dst->encoding();
5081     int src_enc = src->encoding();
5082     if (dst_enc == src_enc) {
5083       if (dst_enc < 16) {
5084         Assembler::pshuflw(dst, src, mode);
5085       } else {
5086         subptr(rsp, 64);
5087         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5088         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5089         Assembler::pshuflw(xmm0, xmm0, mode);
5090         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5091         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5092         addptr(rsp, 64);
5093       }
5094     } else {
5095       if ((src_enc < 16) && (dst_enc < 16)) {
5096         Assembler::pshuflw(dst, src, mode);
5097       } else if (src_enc < 16) {
5098         subptr(rsp, 64);
5099         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5100         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5101         Assembler::pshuflw(xmm0, src, mode);
5102         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5103         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5104         addptr(rsp, 64);
5105       } else if (dst_enc < 16) {
5106         subptr(rsp, 64);
5107         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5108         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5109         Assembler::pshuflw(dst, xmm0, mode);
5110         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5111         addptr(rsp, 64);
5112       } else {
5113         subptr(rsp, 64);
5114         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5115         subptr(rsp, 64);
5116         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5117         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5118         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5119         Assembler::pshuflw(xmm0, xmm1, mode);
5120         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5121         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5122         addptr(rsp, 64);
5123         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5124         addptr(rsp, 64);
5125       }
5126     }
5127   } else {
5128     Assembler::pshuflw(dst, src, mode);
5129   }
5130 }
5131 
5132 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5133   if (reachable(src)) {
5134     vandpd(dst, nds, as_Address(src), vector_len);
5135   } else {
5136     lea(rscratch1, src);
5137     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5138   }
5139 }
5140 
5141 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5142   if (reachable(src)) {
5143     vandps(dst, nds, as_Address(src), vector_len);
5144   } else {
5145     lea(rscratch1, src);
5146     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5147   }
5148 }
5149 
5150 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5151   if (reachable(src)) {
5152     vdivsd(dst, nds, as_Address(src));
5153   } else {
5154     lea(rscratch1, src);
5155     vdivsd(dst, nds, Address(rscratch1, 0));
5156   }
5157 }
5158 
5159 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5160   if (reachable(src)) {
5161     vdivss(dst, nds, as_Address(src));
5162   } else {
5163     lea(rscratch1, src);
5164     vdivss(dst, nds, Address(rscratch1, 0));
5165   }
5166 }
5167 
5168 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5169   if (reachable(src)) {
5170     vmulsd(dst, nds, as_Address(src));
5171   } else {
5172     lea(rscratch1, src);
5173     vmulsd(dst, nds, Address(rscratch1, 0));
5174   }
5175 }
5176 
5177 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5178   if (reachable(src)) {
5179     vmulss(dst, nds, as_Address(src));
5180   } else {
5181     lea(rscratch1, src);
5182     vmulss(dst, nds, Address(rscratch1, 0));
5183   }
5184 }
5185 
5186 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5187   if (reachable(src)) {
5188     vsubsd(dst, nds, as_Address(src));
5189   } else {
5190     lea(rscratch1, src);
5191     vsubsd(dst, nds, Address(rscratch1, 0));
5192   }
5193 }
5194 
5195 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5196   if (reachable(src)) {
5197     vsubss(dst, nds, as_Address(src));
5198   } else {
5199     lea(rscratch1, src);
5200     vsubss(dst, nds, Address(rscratch1, 0));
5201   }
5202 }
5203 
5204 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5205   int nds_enc = nds->encoding();
5206   int dst_enc = dst->encoding();
5207   bool dst_upper_bank = (dst_enc > 15);
5208   bool nds_upper_bank = (nds_enc > 15);
5209   if (VM_Version::supports_avx512novl() &&
5210       (nds_upper_bank || dst_upper_bank)) {
5211     if (dst_upper_bank) {
5212       subptr(rsp, 64);
5213       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5214       movflt(xmm0, nds);
5215       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5216       movflt(dst, xmm0);
5217       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5218       addptr(rsp, 64);
5219     } else {
5220       movflt(dst, nds);
5221       vxorps(dst, dst, src, Assembler::AVX_128bit);
5222     }
5223   } else {
5224     vxorps(dst, nds, src, Assembler::AVX_128bit);
5225   }
5226 }
5227 
5228 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5229   int nds_enc = nds->encoding();
5230   int dst_enc = dst->encoding();
5231   bool dst_upper_bank = (dst_enc > 15);
5232   bool nds_upper_bank = (nds_enc > 15);
5233   if (VM_Version::supports_avx512novl() &&
5234       (nds_upper_bank || dst_upper_bank)) {
5235     if (dst_upper_bank) {
5236       subptr(rsp, 64);
5237       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5238       movdbl(xmm0, nds);
5239       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5240       movdbl(dst, xmm0);
5241       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5242       addptr(rsp, 64);
5243     } else {
5244       movdbl(dst, nds);
5245       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5246     }
5247   } else {
5248     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5249   }
5250 }
5251 
5252 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5253   if (reachable(src)) {
5254     vxorpd(dst, nds, as_Address(src), vector_len);
5255   } else {
5256     lea(rscratch1, src);
5257     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5258   }
5259 }
5260 
5261 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5262   if (reachable(src)) {
5263     vxorps(dst, nds, as_Address(src), vector_len);
5264   } else {
5265     lea(rscratch1, src);
5266     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5267   }
5268 }
5269 
5270 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5271   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5272   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5273   // The inverted mask is sign-extended
5274   andptr(possibly_jweak, inverted_jweak_mask);
5275 }
5276 
5277 void MacroAssembler::resolve_jobject(Register value,
5278                                      Register thread,
5279                                      Register tmp) {
5280   assert_different_registers(value, thread, tmp);
5281   Label done, not_weak;
5282   testptr(value, value);
5283   jcc(Assembler::zero, done);                // Use NULL as-is.
5284   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5285   jcc(Assembler::zero, not_weak);
5286   // Resolve jweak.
5287   access_load_at(T_OBJECT, IN_ROOT | ON_PHANTOM_OOP_REF,
5288                  value, Address(value, -JNIHandles::weak_tag_value), tmp, thread);
5289   verify_oop(value);
5290   jmp(done);
5291   bind(not_weak);
5292   // Resolve (untagged) jobject.
5293   access_load_at(T_OBJECT, IN_ROOT | IN_CONCURRENT_ROOT,
5294                  value, Address(value, 0), tmp, thread);
5295   verify_oop(value);
5296   bind(done);
5297 }
5298 
5299 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5300   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5301 }
5302 
5303 // Force generation of a 4 byte immediate value even if it fits into 8bit
5304 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5305   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5306 }
5307 
5308 void MacroAssembler::subptr(Register dst, Register src) {
5309   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5310 }
5311 
5312 // C++ bool manipulation
5313 void MacroAssembler::testbool(Register dst) {
5314   if(sizeof(bool) == 1)
5315     testb(dst, 0xff);
5316   else if(sizeof(bool) == 2) {
5317     // testw implementation needed for two byte bools
5318     ShouldNotReachHere();
5319   } else if(sizeof(bool) == 4)
5320     testl(dst, dst);
5321   else
5322     // unsupported
5323     ShouldNotReachHere();
5324 }
5325 
5326 void MacroAssembler::testptr(Register dst, Register src) {
5327   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5328 }
5329 
5330 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5331 void MacroAssembler::tlab_allocate(Register obj,
5332                                    Register var_size_in_bytes,
5333                                    int con_size_in_bytes,
5334                                    Register t1,
5335                                    Register t2,
5336                                    Label& slow_case) {
5337   assert_different_registers(obj, t1, t2);
5338   assert_different_registers(obj, var_size_in_bytes, t1);
5339   Register end = t2;
5340   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5341 
5342   verify_tlab();
5343 
5344   NOT_LP64(get_thread(thread));
5345 
5346   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5347   if (var_size_in_bytes == noreg) {
5348     lea(end, Address(obj, con_size_in_bytes));
5349   } else {
5350     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5351   }
5352   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5353   jcc(Assembler::above, slow_case);
5354 
5355   // update the tlab top pointer
5356   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5357 
5358   // recover var_size_in_bytes if necessary
5359   if (var_size_in_bytes == end) {
5360     subptr(var_size_in_bytes, obj);
5361   }
5362   verify_tlab();
5363 }
5364 
5365 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5366 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5367   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5368   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5369   Label done;
5370 
5371   testptr(length_in_bytes, length_in_bytes);
5372   jcc(Assembler::zero, done);
5373 
5374   // initialize topmost word, divide index by 2, check if odd and test if zero
5375   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5376 #ifdef ASSERT
5377   {
5378     Label L;
5379     testptr(length_in_bytes, BytesPerWord - 1);
5380     jcc(Assembler::zero, L);
5381     stop("length must be a multiple of BytesPerWord");
5382     bind(L);
5383   }
5384 #endif
5385   Register index = length_in_bytes;
5386   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5387   if (UseIncDec) {
5388     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5389   } else {
5390     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5391     shrptr(index, 1);
5392   }
5393 #ifndef _LP64
5394   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5395   {
5396     Label even;
5397     // note: if index was a multiple of 8, then it cannot
5398     //       be 0 now otherwise it must have been 0 before
5399     //       => if it is even, we don't need to check for 0 again
5400     jcc(Assembler::carryClear, even);
5401     // clear topmost word (no jump would be needed if conditional assignment worked here)
5402     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5403     // index could be 0 now, must check again
5404     jcc(Assembler::zero, done);
5405     bind(even);
5406   }
5407 #endif // !_LP64
5408   // initialize remaining object fields: index is a multiple of 2 now
5409   {
5410     Label loop;
5411     bind(loop);
5412     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5413     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5414     decrement(index);
5415     jcc(Assembler::notZero, loop);
5416   }
5417 
5418   bind(done);
5419 }
5420 
5421 void MacroAssembler::incr_allocated_bytes(Register thread,
5422                                           Register var_size_in_bytes,
5423                                           int con_size_in_bytes,
5424                                           Register t1) {
5425   if (!thread->is_valid()) {
5426 #ifdef _LP64
5427     thread = r15_thread;
5428 #else
5429     assert(t1->is_valid(), "need temp reg");
5430     thread = t1;
5431     get_thread(thread);
5432 #endif
5433   }
5434 
5435 #ifdef _LP64
5436   if (var_size_in_bytes->is_valid()) {
5437     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5438   } else {
5439     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5440   }
5441 #else
5442   if (var_size_in_bytes->is_valid()) {
5443     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5444   } else {
5445     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5446   }
5447   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5448 #endif
5449 }
5450 
5451 // Look up the method for a megamorphic invokeinterface call.
5452 // The target method is determined by <intf_klass, itable_index>.
5453 // The receiver klass is in recv_klass.
5454 // On success, the result will be in method_result, and execution falls through.
5455 // On failure, execution transfers to the given label.
5456 void MacroAssembler::lookup_interface_method(Register recv_klass,
5457                                              Register intf_klass,
5458                                              RegisterOrConstant itable_index,
5459                                              Register method_result,
5460                                              Register scan_temp,
5461                                              Label& L_no_such_interface,
5462                                              bool return_method) {
5463   assert_different_registers(recv_klass, intf_klass, scan_temp);
5464   assert_different_registers(method_result, intf_klass, scan_temp);
5465   assert(recv_klass != method_result || !return_method,
5466          "recv_klass can be destroyed when method isn't needed");
5467 
5468   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5469          "caller must use same register for non-constant itable index as for method");
5470 
5471   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5472   int vtable_base = in_bytes(Klass::vtable_start_offset());
5473   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5474   int scan_step   = itableOffsetEntry::size() * wordSize;
5475   int vte_size    = vtableEntry::size_in_bytes();
5476   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5477   assert(vte_size == wordSize, "else adjust times_vte_scale");
5478 
5479   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5480 
5481   // %%% Could store the aligned, prescaled offset in the klassoop.
5482   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5483 
5484   if (return_method) {
5485     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5486     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5487     lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5488   }
5489 
5490   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5491   //   if (scan->interface() == intf) {
5492   //     result = (klass + scan->offset() + itable_index);
5493   //   }
5494   // }
5495   Label search, found_method;
5496 
5497   for (int peel = 1; peel >= 0; peel--) {
5498     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5499     cmpptr(intf_klass, method_result);
5500 
5501     if (peel) {
5502       jccb(Assembler::equal, found_method);
5503     } else {
5504       jccb(Assembler::notEqual, search);
5505       // (invert the test to fall through to found_method...)
5506     }
5507 
5508     if (!peel)  break;
5509 
5510     bind(search);
5511 
5512     // Check that the previous entry is non-null.  A null entry means that
5513     // the receiver class doesn't implement the interface, and wasn't the
5514     // same as when the caller was compiled.
5515     testptr(method_result, method_result);
5516     jcc(Assembler::zero, L_no_such_interface);
5517     addptr(scan_temp, scan_step);
5518   }
5519 
5520   bind(found_method);
5521 
5522   if (return_method) {
5523     // Got a hit.
5524     movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5525     movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5526   }
5527 }
5528 
5529 
5530 // virtual method calling
5531 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5532                                            RegisterOrConstant vtable_index,
5533                                            Register method_result) {
5534   const int base = in_bytes(Klass::vtable_start_offset());
5535   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5536   Address vtable_entry_addr(recv_klass,
5537                             vtable_index, Address::times_ptr,
5538                             base + vtableEntry::method_offset_in_bytes());
5539   movptr(method_result, vtable_entry_addr);
5540 }
5541 
5542 
5543 void MacroAssembler::check_klass_subtype(Register sub_klass,
5544                            Register super_klass,
5545                            Register temp_reg,
5546                            Label& L_success) {
5547   Label L_failure;
5548   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5549   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5550   bind(L_failure);
5551 }
5552 
5553 
5554 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5555                                                    Register super_klass,
5556                                                    Register temp_reg,
5557                                                    Label* L_success,
5558                                                    Label* L_failure,
5559                                                    Label* L_slow_path,
5560                                         RegisterOrConstant super_check_offset) {
5561   assert_different_registers(sub_klass, super_klass, temp_reg);
5562   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5563   if (super_check_offset.is_register()) {
5564     assert_different_registers(sub_klass, super_klass,
5565                                super_check_offset.as_register());
5566   } else if (must_load_sco) {
5567     assert(temp_reg != noreg, "supply either a temp or a register offset");
5568   }
5569 
5570   Label L_fallthrough;
5571   int label_nulls = 0;
5572   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5573   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5574   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5575   assert(label_nulls <= 1, "at most one NULL in the batch");
5576 
5577   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5578   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5579   Address super_check_offset_addr(super_klass, sco_offset);
5580 
5581   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5582   // range of a jccb.  If this routine grows larger, reconsider at
5583   // least some of these.
5584 #define local_jcc(assembler_cond, label)                                \
5585   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5586   else                             jcc( assembler_cond, label) /*omit semi*/
5587 
5588   // Hacked jmp, which may only be used just before L_fallthrough.
5589 #define final_jmp(label)                                                \
5590   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5591   else                            jmp(label)                /*omit semi*/
5592 
5593   // If the pointers are equal, we are done (e.g., String[] elements).
5594   // This self-check enables sharing of secondary supertype arrays among
5595   // non-primary types such as array-of-interface.  Otherwise, each such
5596   // type would need its own customized SSA.
5597   // We move this check to the front of the fast path because many
5598   // type checks are in fact trivially successful in this manner,
5599   // so we get a nicely predicted branch right at the start of the check.
5600   cmpptr(sub_klass, super_klass);
5601   local_jcc(Assembler::equal, *L_success);
5602 
5603   // Check the supertype display:
5604   if (must_load_sco) {
5605     // Positive movl does right thing on LP64.
5606     movl(temp_reg, super_check_offset_addr);
5607     super_check_offset = RegisterOrConstant(temp_reg);
5608   }
5609   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5610   cmpptr(super_klass, super_check_addr); // load displayed supertype
5611 
5612   // This check has worked decisively for primary supers.
5613   // Secondary supers are sought in the super_cache ('super_cache_addr').
5614   // (Secondary supers are interfaces and very deeply nested subtypes.)
5615   // This works in the same check above because of a tricky aliasing
5616   // between the super_cache and the primary super display elements.
5617   // (The 'super_check_addr' can address either, as the case requires.)
5618   // Note that the cache is updated below if it does not help us find
5619   // what we need immediately.
5620   // So if it was a primary super, we can just fail immediately.
5621   // Otherwise, it's the slow path for us (no success at this point).
5622 
5623   if (super_check_offset.is_register()) {
5624     local_jcc(Assembler::equal, *L_success);
5625     cmpl(super_check_offset.as_register(), sc_offset);
5626     if (L_failure == &L_fallthrough) {
5627       local_jcc(Assembler::equal, *L_slow_path);
5628     } else {
5629       local_jcc(Assembler::notEqual, *L_failure);
5630       final_jmp(*L_slow_path);
5631     }
5632   } else if (super_check_offset.as_constant() == sc_offset) {
5633     // Need a slow path; fast failure is impossible.
5634     if (L_slow_path == &L_fallthrough) {
5635       local_jcc(Assembler::equal, *L_success);
5636     } else {
5637       local_jcc(Assembler::notEqual, *L_slow_path);
5638       final_jmp(*L_success);
5639     }
5640   } else {
5641     // No slow path; it's a fast decision.
5642     if (L_failure == &L_fallthrough) {
5643       local_jcc(Assembler::equal, *L_success);
5644     } else {
5645       local_jcc(Assembler::notEqual, *L_failure);
5646       final_jmp(*L_success);
5647     }
5648   }
5649 
5650   bind(L_fallthrough);
5651 
5652 #undef local_jcc
5653 #undef final_jmp
5654 }
5655 
5656 
5657 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5658                                                    Register super_klass,
5659                                                    Register temp_reg,
5660                                                    Register temp2_reg,
5661                                                    Label* L_success,
5662                                                    Label* L_failure,
5663                                                    bool set_cond_codes) {
5664   assert_different_registers(sub_klass, super_klass, temp_reg);
5665   if (temp2_reg != noreg)
5666     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5667 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5668 
5669   Label L_fallthrough;
5670   int label_nulls = 0;
5671   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5672   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5673   assert(label_nulls <= 1, "at most one NULL in the batch");
5674 
5675   // a couple of useful fields in sub_klass:
5676   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5677   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5678   Address secondary_supers_addr(sub_klass, ss_offset);
5679   Address super_cache_addr(     sub_klass, sc_offset);
5680 
5681   // Do a linear scan of the secondary super-klass chain.
5682   // This code is rarely used, so simplicity is a virtue here.
5683   // The repne_scan instruction uses fixed registers, which we must spill.
5684   // Don't worry too much about pre-existing connections with the input regs.
5685 
5686   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5687   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5688 
5689   // Get super_klass value into rax (even if it was in rdi or rcx).
5690   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5691   if (super_klass != rax || UseCompressedOops) {
5692     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5693     mov(rax, super_klass);
5694   }
5695   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5696   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5697 
5698 #ifndef PRODUCT
5699   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5700   ExternalAddress pst_counter_addr((address) pst_counter);
5701   NOT_LP64(  incrementl(pst_counter_addr) );
5702   LP64_ONLY( lea(rcx, pst_counter_addr) );
5703   LP64_ONLY( incrementl(Address(rcx, 0)) );
5704 #endif //PRODUCT
5705 
5706   // We will consult the secondary-super array.
5707   movptr(rdi, secondary_supers_addr);
5708   // Load the array length.  (Positive movl does right thing on LP64.)
5709   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
5710   // Skip to start of data.
5711   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
5712 
5713   // Scan RCX words at [RDI] for an occurrence of RAX.
5714   // Set NZ/Z based on last compare.
5715   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
5716   // not change flags (only scas instruction which is repeated sets flags).
5717   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
5718 
5719     testptr(rax,rax); // Set Z = 0
5720     repne_scan();
5721 
5722   // Unspill the temp. registers:
5723   if (pushed_rdi)  pop(rdi);
5724   if (pushed_rcx)  pop(rcx);
5725   if (pushed_rax)  pop(rax);
5726 
5727   if (set_cond_codes) {
5728     // Special hack for the AD files:  rdi is guaranteed non-zero.
5729     assert(!pushed_rdi, "rdi must be left non-NULL");
5730     // Also, the condition codes are properly set Z/NZ on succeed/failure.
5731   }
5732 
5733   if (L_failure == &L_fallthrough)
5734         jccb(Assembler::notEqual, *L_failure);
5735   else  jcc(Assembler::notEqual, *L_failure);
5736 
5737   // Success.  Cache the super we found and proceed in triumph.
5738   movptr(super_cache_addr, super_klass);
5739 
5740   if (L_success != &L_fallthrough) {
5741     jmp(*L_success);
5742   }
5743 
5744 #undef IS_A_TEMP
5745 
5746   bind(L_fallthrough);
5747 }
5748 
5749 
5750 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
5751   if (VM_Version::supports_cmov()) {
5752     cmovl(cc, dst, src);
5753   } else {
5754     Label L;
5755     jccb(negate_condition(cc), L);
5756     movl(dst, src);
5757     bind(L);
5758   }
5759 }
5760 
5761 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
5762   if (VM_Version::supports_cmov()) {
5763     cmovl(cc, dst, src);
5764   } else {
5765     Label L;
5766     jccb(negate_condition(cc), L);
5767     movl(dst, src);
5768     bind(L);
5769   }
5770 }
5771 
5772 void MacroAssembler::verify_oop(Register reg, const char* s) {
5773   if (!VerifyOops) return;
5774 
5775   // Pass register number to verify_oop_subroutine
5776   const char* b = NULL;
5777   {
5778     ResourceMark rm;
5779     stringStream ss;
5780     ss.print("verify_oop: %s: %s", reg->name(), s);
5781     b = code_string(ss.as_string());
5782   }
5783   BLOCK_COMMENT("verify_oop {");
5784 #ifdef _LP64
5785   push(rscratch1);                    // save r10, trashed by movptr()
5786 #endif
5787   push(rax);                          // save rax,
5788   push(reg);                          // pass register argument
5789   ExternalAddress buffer((address) b);
5790   // avoid using pushptr, as it modifies scratch registers
5791   // and our contract is not to modify anything
5792   movptr(rax, buffer.addr());
5793   push(rax);
5794   // call indirectly to solve generation ordering problem
5795   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5796   call(rax);
5797   // Caller pops the arguments (oop, message) and restores rax, r10
5798   BLOCK_COMMENT("} verify_oop");
5799 }
5800 
5801 
5802 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
5803                                                       Register tmp,
5804                                                       int offset) {
5805   intptr_t value = *delayed_value_addr;
5806   if (value != 0)
5807     return RegisterOrConstant(value + offset);
5808 
5809   // load indirectly to solve generation ordering problem
5810   movptr(tmp, ExternalAddress((address) delayed_value_addr));
5811 
5812 #ifdef ASSERT
5813   { Label L;
5814     testptr(tmp, tmp);
5815     if (WizardMode) {
5816       const char* buf = NULL;
5817       {
5818         ResourceMark rm;
5819         stringStream ss;
5820         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
5821         buf = code_string(ss.as_string());
5822       }
5823       jcc(Assembler::notZero, L);
5824       STOP(buf);
5825     } else {
5826       jccb(Assembler::notZero, L);
5827       hlt();
5828     }
5829     bind(L);
5830   }
5831 #endif
5832 
5833   if (offset != 0)
5834     addptr(tmp, offset);
5835 
5836   return RegisterOrConstant(tmp);
5837 }
5838 
5839 
5840 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
5841                                          int extra_slot_offset) {
5842   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
5843   int stackElementSize = Interpreter::stackElementSize;
5844   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
5845 #ifdef ASSERT
5846   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
5847   assert(offset1 - offset == stackElementSize, "correct arithmetic");
5848 #endif
5849   Register             scale_reg    = noreg;
5850   Address::ScaleFactor scale_factor = Address::no_scale;
5851   if (arg_slot.is_constant()) {
5852     offset += arg_slot.as_constant() * stackElementSize;
5853   } else {
5854     scale_reg    = arg_slot.as_register();
5855     scale_factor = Address::times(stackElementSize);
5856   }
5857   offset += wordSize;           // return PC is on stack
5858   return Address(rsp, scale_reg, scale_factor, offset);
5859 }
5860 
5861 
5862 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
5863   if (!VerifyOops) return;
5864 
5865   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
5866   // Pass register number to verify_oop_subroutine
5867   const char* b = NULL;
5868   {
5869     ResourceMark rm;
5870     stringStream ss;
5871     ss.print("verify_oop_addr: %s", s);
5872     b = code_string(ss.as_string());
5873   }
5874 #ifdef _LP64
5875   push(rscratch1);                    // save r10, trashed by movptr()
5876 #endif
5877   push(rax);                          // save rax,
5878   // addr may contain rsp so we will have to adjust it based on the push
5879   // we just did (and on 64 bit we do two pushes)
5880   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
5881   // stores rax into addr which is backwards of what was intended.
5882   if (addr.uses(rsp)) {
5883     lea(rax, addr);
5884     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
5885   } else {
5886     pushptr(addr);
5887   }
5888 
5889   ExternalAddress buffer((address) b);
5890   // pass msg argument
5891   // avoid using pushptr, as it modifies scratch registers
5892   // and our contract is not to modify anything
5893   movptr(rax, buffer.addr());
5894   push(rax);
5895 
5896   // call indirectly to solve generation ordering problem
5897   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5898   call(rax);
5899   // Caller pops the arguments (addr, message) and restores rax, r10.
5900 }
5901 
5902 void MacroAssembler::verify_tlab() {
5903 #ifdef ASSERT
5904   if (UseTLAB && VerifyOops) {
5905     Label next, ok;
5906     Register t1 = rsi;
5907     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
5908 
5909     push(t1);
5910     NOT_LP64(push(thread_reg));
5911     NOT_LP64(get_thread(thread_reg));
5912 
5913     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5914     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5915     jcc(Assembler::aboveEqual, next);
5916     STOP("assert(top >= start)");
5917     should_not_reach_here();
5918 
5919     bind(next);
5920     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5921     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5922     jcc(Assembler::aboveEqual, ok);
5923     STOP("assert(top <= end)");
5924     should_not_reach_here();
5925 
5926     bind(ok);
5927     NOT_LP64(pop(thread_reg));
5928     pop(t1);
5929   }
5930 #endif
5931 }
5932 
5933 class ControlWord {
5934  public:
5935   int32_t _value;
5936 
5937   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
5938   int  precision_control() const       { return  (_value >>  8) & 3      ; }
5939   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5940   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5941   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5942   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5943   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5944   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5945 
5946   void print() const {
5947     // rounding control
5948     const char* rc;
5949     switch (rounding_control()) {
5950       case 0: rc = "round near"; break;
5951       case 1: rc = "round down"; break;
5952       case 2: rc = "round up  "; break;
5953       case 3: rc = "chop      "; break;
5954     };
5955     // precision control
5956     const char* pc;
5957     switch (precision_control()) {
5958       case 0: pc = "24 bits "; break;
5959       case 1: pc = "reserved"; break;
5960       case 2: pc = "53 bits "; break;
5961       case 3: pc = "64 bits "; break;
5962     };
5963     // flags
5964     char f[9];
5965     f[0] = ' ';
5966     f[1] = ' ';
5967     f[2] = (precision   ()) ? 'P' : 'p';
5968     f[3] = (underflow   ()) ? 'U' : 'u';
5969     f[4] = (overflow    ()) ? 'O' : 'o';
5970     f[5] = (zero_divide ()) ? 'Z' : 'z';
5971     f[6] = (denormalized()) ? 'D' : 'd';
5972     f[7] = (invalid     ()) ? 'I' : 'i';
5973     f[8] = '\x0';
5974     // output
5975     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
5976   }
5977 
5978 };
5979 
5980 class StatusWord {
5981  public:
5982   int32_t _value;
5983 
5984   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
5985   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
5986   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
5987   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
5988   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
5989   int  top() const                     { return  (_value >> 11) & 7      ; }
5990   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
5991   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
5992   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5993   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5994   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5995   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5996   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5997   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5998 
5999   void print() const {
6000     // condition codes
6001     char c[5];
6002     c[0] = (C3()) ? '3' : '-';
6003     c[1] = (C2()) ? '2' : '-';
6004     c[2] = (C1()) ? '1' : '-';
6005     c[3] = (C0()) ? '0' : '-';
6006     c[4] = '\x0';
6007     // flags
6008     char f[9];
6009     f[0] = (error_status()) ? 'E' : '-';
6010     f[1] = (stack_fault ()) ? 'S' : '-';
6011     f[2] = (precision   ()) ? 'P' : '-';
6012     f[3] = (underflow   ()) ? 'U' : '-';
6013     f[4] = (overflow    ()) ? 'O' : '-';
6014     f[5] = (zero_divide ()) ? 'Z' : '-';
6015     f[6] = (denormalized()) ? 'D' : '-';
6016     f[7] = (invalid     ()) ? 'I' : '-';
6017     f[8] = '\x0';
6018     // output
6019     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6020   }
6021 
6022 };
6023 
6024 class TagWord {
6025  public:
6026   int32_t _value;
6027 
6028   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6029 
6030   void print() const {
6031     printf("%04x", _value & 0xFFFF);
6032   }
6033 
6034 };
6035 
6036 class FPU_Register {
6037  public:
6038   int32_t _m0;
6039   int32_t _m1;
6040   int16_t _ex;
6041 
6042   bool is_indefinite() const           {
6043     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6044   }
6045 
6046   void print() const {
6047     char  sign = (_ex < 0) ? '-' : '+';
6048     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6049     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6050   };
6051 
6052 };
6053 
6054 class FPU_State {
6055  public:
6056   enum {
6057     register_size       = 10,
6058     number_of_registers =  8,
6059     register_mask       =  7
6060   };
6061 
6062   ControlWord  _control_word;
6063   StatusWord   _status_word;
6064   TagWord      _tag_word;
6065   int32_t      _error_offset;
6066   int32_t      _error_selector;
6067   int32_t      _data_offset;
6068   int32_t      _data_selector;
6069   int8_t       _register[register_size * number_of_registers];
6070 
6071   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6072   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6073 
6074   const char* tag_as_string(int tag) const {
6075     switch (tag) {
6076       case 0: return "valid";
6077       case 1: return "zero";
6078       case 2: return "special";
6079       case 3: return "empty";
6080     }
6081     ShouldNotReachHere();
6082     return NULL;
6083   }
6084 
6085   void print() const {
6086     // print computation registers
6087     { int t = _status_word.top();
6088       for (int i = 0; i < number_of_registers; i++) {
6089         int j = (i - t) & register_mask;
6090         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6091         st(j)->print();
6092         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6093       }
6094     }
6095     printf("\n");
6096     // print control registers
6097     printf("ctrl = "); _control_word.print(); printf("\n");
6098     printf("stat = "); _status_word .print(); printf("\n");
6099     printf("tags = "); _tag_word    .print(); printf("\n");
6100   }
6101 
6102 };
6103 
6104 class Flag_Register {
6105  public:
6106   int32_t _value;
6107 
6108   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6109   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6110   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6111   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6112   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6113   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6114   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6115 
6116   void print() const {
6117     // flags
6118     char f[8];
6119     f[0] = (overflow       ()) ? 'O' : '-';
6120     f[1] = (direction      ()) ? 'D' : '-';
6121     f[2] = (sign           ()) ? 'S' : '-';
6122     f[3] = (zero           ()) ? 'Z' : '-';
6123     f[4] = (auxiliary_carry()) ? 'A' : '-';
6124     f[5] = (parity         ()) ? 'P' : '-';
6125     f[6] = (carry          ()) ? 'C' : '-';
6126     f[7] = '\x0';
6127     // output
6128     printf("%08x  flags = %s", _value, f);
6129   }
6130 
6131 };
6132 
6133 class IU_Register {
6134  public:
6135   int32_t _value;
6136 
6137   void print() const {
6138     printf("%08x  %11d", _value, _value);
6139   }
6140 
6141 };
6142 
6143 class IU_State {
6144  public:
6145   Flag_Register _eflags;
6146   IU_Register   _rdi;
6147   IU_Register   _rsi;
6148   IU_Register   _rbp;
6149   IU_Register   _rsp;
6150   IU_Register   _rbx;
6151   IU_Register   _rdx;
6152   IU_Register   _rcx;
6153   IU_Register   _rax;
6154 
6155   void print() const {
6156     // computation registers
6157     printf("rax,  = "); _rax.print(); printf("\n");
6158     printf("rbx,  = "); _rbx.print(); printf("\n");
6159     printf("rcx  = "); _rcx.print(); printf("\n");
6160     printf("rdx  = "); _rdx.print(); printf("\n");
6161     printf("rdi  = "); _rdi.print(); printf("\n");
6162     printf("rsi  = "); _rsi.print(); printf("\n");
6163     printf("rbp,  = "); _rbp.print(); printf("\n");
6164     printf("rsp  = "); _rsp.print(); printf("\n");
6165     printf("\n");
6166     // control registers
6167     printf("flgs = "); _eflags.print(); printf("\n");
6168   }
6169 };
6170 
6171 
6172 class CPU_State {
6173  public:
6174   FPU_State _fpu_state;
6175   IU_State  _iu_state;
6176 
6177   void print() const {
6178     printf("--------------------------------------------------\n");
6179     _iu_state .print();
6180     printf("\n");
6181     _fpu_state.print();
6182     printf("--------------------------------------------------\n");
6183   }
6184 
6185 };
6186 
6187 
6188 static void _print_CPU_state(CPU_State* state) {
6189   state->print();
6190 };
6191 
6192 
6193 void MacroAssembler::print_CPU_state() {
6194   push_CPU_state();
6195   push(rsp);                // pass CPU state
6196   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6197   addptr(rsp, wordSize);       // discard argument
6198   pop_CPU_state();
6199 }
6200 
6201 
6202 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6203   static int counter = 0;
6204   FPU_State* fs = &state->_fpu_state;
6205   counter++;
6206   // For leaf calls, only verify that the top few elements remain empty.
6207   // We only need 1 empty at the top for C2 code.
6208   if( stack_depth < 0 ) {
6209     if( fs->tag_for_st(7) != 3 ) {
6210       printf("FPR7 not empty\n");
6211       state->print();
6212       assert(false, "error");
6213       return false;
6214     }
6215     return true;                // All other stack states do not matter
6216   }
6217 
6218   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6219          "bad FPU control word");
6220 
6221   // compute stack depth
6222   int i = 0;
6223   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6224   int d = i;
6225   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6226   // verify findings
6227   if (i != FPU_State::number_of_registers) {
6228     // stack not contiguous
6229     printf("%s: stack not contiguous at ST%d\n", s, i);
6230     state->print();
6231     assert(false, "error");
6232     return false;
6233   }
6234   // check if computed stack depth corresponds to expected stack depth
6235   if (stack_depth < 0) {
6236     // expected stack depth is -stack_depth or less
6237     if (d > -stack_depth) {
6238       // too many elements on the stack
6239       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6240       state->print();
6241       assert(false, "error");
6242       return false;
6243     }
6244   } else {
6245     // expected stack depth is stack_depth
6246     if (d != stack_depth) {
6247       // wrong stack depth
6248       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6249       state->print();
6250       assert(false, "error");
6251       return false;
6252     }
6253   }
6254   // everything is cool
6255   return true;
6256 }
6257 
6258 
6259 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6260   if (!VerifyFPU) return;
6261   push_CPU_state();
6262   push(rsp);                // pass CPU state
6263   ExternalAddress msg((address) s);
6264   // pass message string s
6265   pushptr(msg.addr());
6266   push(stack_depth);        // pass stack depth
6267   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6268   addptr(rsp, 3 * wordSize);   // discard arguments
6269   // check for error
6270   { Label L;
6271     testl(rax, rax);
6272     jcc(Assembler::notZero, L);
6273     int3();                  // break if error condition
6274     bind(L);
6275   }
6276   pop_CPU_state();
6277 }
6278 
6279 void MacroAssembler::restore_cpu_control_state_after_jni() {
6280   // Either restore the MXCSR register after returning from the JNI Call
6281   // or verify that it wasn't changed (with -Xcheck:jni flag).
6282   if (VM_Version::supports_sse()) {
6283     if (RestoreMXCSROnJNICalls) {
6284       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6285     } else if (CheckJNICalls) {
6286       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6287     }
6288   }
6289   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6290   vzeroupper();
6291   // Reset k1 to 0xffff.
6292   if (VM_Version::supports_evex()) {
6293     push(rcx);
6294     movl(rcx, 0xffff);
6295     kmovwl(k1, rcx);
6296     pop(rcx);
6297   }
6298 
6299 #ifndef _LP64
6300   // Either restore the x87 floating pointer control word after returning
6301   // from the JNI call or verify that it wasn't changed.
6302   if (CheckJNICalls) {
6303     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6304   }
6305 #endif // _LP64
6306 }
6307 
6308 // ((OopHandle)result).resolve();
6309 void MacroAssembler::resolve_oop_handle(Register result, Register tmp) {
6310   assert_different_registers(result, tmp);
6311 
6312   // Only 64 bit platforms support GCs that require a tmp register
6313   // Only IN_HEAP loads require a thread_tmp register
6314   // OopHandle::resolve is an indirection like jobject.
6315   access_load_at(T_OBJECT, IN_ROOT | IN_CONCURRENT_ROOT,
6316                  result, Address(result, 0), tmp, /*tmp_thread*/noreg);
6317 }
6318 
6319 void MacroAssembler::load_mirror(Register mirror, Register method, Register tmp) {
6320   // get mirror
6321   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6322   movptr(mirror, Address(method, Method::const_offset()));
6323   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6324   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6325   movptr(mirror, Address(mirror, mirror_offset));
6326   resolve_oop_handle(mirror, tmp);
6327 }
6328 
6329 void MacroAssembler::load_klass(Register dst, Register src) {
6330 #ifdef _LP64
6331   if (UseCompressedClassPointers) {
6332     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6333     decode_klass_not_null(dst);
6334   } else
6335 #endif
6336     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6337 }
6338 
6339 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6340   load_klass(dst, src);
6341   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6342 }
6343 
6344 void MacroAssembler::store_klass(Register dst, Register src) {
6345 #ifdef _LP64
6346   if (UseCompressedClassPointers) {
6347     encode_klass_not_null(src);
6348     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6349   } else
6350 #endif
6351     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6352 }
6353 
6354 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators, Register dst, Address src,
6355                                     Register tmp1, Register thread_tmp) {
6356   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6357   bool as_raw = (decorators & AS_RAW) != 0;
6358   if (as_raw) {
6359     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
6360   } else {
6361     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
6362   }
6363 }
6364 
6365 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators, Address dst, Register src,
6366                                      Register tmp1, Register tmp2) {
6367   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6368   bool as_raw = (decorators & AS_RAW) != 0;
6369   if (as_raw) {
6370     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, tmp2);
6371   } else {
6372     bs->store_at(this, decorators, type, dst, src, tmp1, tmp2);
6373   }
6374 }
6375 
6376 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
6377                                    Register thread_tmp, DecoratorSet decorators) {
6378   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
6379 }
6380 
6381 // Doesn't do verfication, generates fixed size code
6382 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
6383                                             Register thread_tmp, DecoratorSet decorators) {
6384   access_load_at(T_OBJECT, IN_HEAP | OOP_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
6385 }
6386 
6387 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
6388                                     Register tmp2, DecoratorSet decorators) {
6389   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
6390 }
6391 
6392 // Used for storing NULLs.
6393 void MacroAssembler::store_heap_oop_null(Address dst) {
6394   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg);
6395 }
6396 
6397 #ifdef _LP64
6398 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6399   if (UseCompressedClassPointers) {
6400     // Store to klass gap in destination
6401     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6402   }
6403 }
6404 
6405 #ifdef ASSERT
6406 void MacroAssembler::verify_heapbase(const char* msg) {
6407   assert (UseCompressedOops, "should be compressed");
6408   assert (Universe::heap() != NULL, "java heap should be initialized");
6409   if (CheckCompressedOops) {
6410     Label ok;
6411     push(rscratch1); // cmpptr trashes rscratch1
6412     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6413     jcc(Assembler::equal, ok);
6414     STOP(msg);
6415     bind(ok);
6416     pop(rscratch1);
6417   }
6418 }
6419 #endif
6420 
6421 // Algorithm must match oop.inline.hpp encode_heap_oop.
6422 void MacroAssembler::encode_heap_oop(Register r) {
6423 #ifdef ASSERT
6424   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6425 #endif
6426   verify_oop(r, "broken oop in encode_heap_oop");
6427   if (Universe::narrow_oop_base() == NULL) {
6428     if (Universe::narrow_oop_shift() != 0) {
6429       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6430       shrq(r, LogMinObjAlignmentInBytes);
6431     }
6432     return;
6433   }
6434   testq(r, r);
6435   cmovq(Assembler::equal, r, r12_heapbase);
6436   subq(r, r12_heapbase);
6437   shrq(r, LogMinObjAlignmentInBytes);
6438 }
6439 
6440 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6441 #ifdef ASSERT
6442   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6443   if (CheckCompressedOops) {
6444     Label ok;
6445     testq(r, r);
6446     jcc(Assembler::notEqual, ok);
6447     STOP("null oop passed to encode_heap_oop_not_null");
6448     bind(ok);
6449   }
6450 #endif
6451   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6452   if (Universe::narrow_oop_base() != NULL) {
6453     subq(r, r12_heapbase);
6454   }
6455   if (Universe::narrow_oop_shift() != 0) {
6456     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6457     shrq(r, LogMinObjAlignmentInBytes);
6458   }
6459 }
6460 
6461 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6462 #ifdef ASSERT
6463   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6464   if (CheckCompressedOops) {
6465     Label ok;
6466     testq(src, src);
6467     jcc(Assembler::notEqual, ok);
6468     STOP("null oop passed to encode_heap_oop_not_null2");
6469     bind(ok);
6470   }
6471 #endif
6472   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6473   if (dst != src) {
6474     movq(dst, src);
6475   }
6476   if (Universe::narrow_oop_base() != NULL) {
6477     subq(dst, r12_heapbase);
6478   }
6479   if (Universe::narrow_oop_shift() != 0) {
6480     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6481     shrq(dst, LogMinObjAlignmentInBytes);
6482   }
6483 }
6484 
6485 void  MacroAssembler::decode_heap_oop(Register r) {
6486 #ifdef ASSERT
6487   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6488 #endif
6489   if (Universe::narrow_oop_base() == NULL) {
6490     if (Universe::narrow_oop_shift() != 0) {
6491       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6492       shlq(r, LogMinObjAlignmentInBytes);
6493     }
6494   } else {
6495     Label done;
6496     shlq(r, LogMinObjAlignmentInBytes);
6497     jccb(Assembler::equal, done);
6498     addq(r, r12_heapbase);
6499     bind(done);
6500   }
6501   verify_oop(r, "broken oop in decode_heap_oop");
6502 }
6503 
6504 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6505   // Note: it will change flags
6506   assert (UseCompressedOops, "should only be used for compressed headers");
6507   assert (Universe::heap() != NULL, "java heap should be initialized");
6508   // Cannot assert, unverified entry point counts instructions (see .ad file)
6509   // vtableStubs also counts instructions in pd_code_size_limit.
6510   // Also do not verify_oop as this is called by verify_oop.
6511   if (Universe::narrow_oop_shift() != 0) {
6512     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6513     shlq(r, LogMinObjAlignmentInBytes);
6514     if (Universe::narrow_oop_base() != NULL) {
6515       addq(r, r12_heapbase);
6516     }
6517   } else {
6518     assert (Universe::narrow_oop_base() == NULL, "sanity");
6519   }
6520 }
6521 
6522 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6523   // Note: it will change flags
6524   assert (UseCompressedOops, "should only be used for compressed headers");
6525   assert (Universe::heap() != NULL, "java heap should be initialized");
6526   // Cannot assert, unverified entry point counts instructions (see .ad file)
6527   // vtableStubs also counts instructions in pd_code_size_limit.
6528   // Also do not verify_oop as this is called by verify_oop.
6529   if (Universe::narrow_oop_shift() != 0) {
6530     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6531     if (LogMinObjAlignmentInBytes == Address::times_8) {
6532       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6533     } else {
6534       if (dst != src) {
6535         movq(dst, src);
6536       }
6537       shlq(dst, LogMinObjAlignmentInBytes);
6538       if (Universe::narrow_oop_base() != NULL) {
6539         addq(dst, r12_heapbase);
6540       }
6541     }
6542   } else {
6543     assert (Universe::narrow_oop_base() == NULL, "sanity");
6544     if (dst != src) {
6545       movq(dst, src);
6546     }
6547   }
6548 }
6549 
6550 void MacroAssembler::encode_klass_not_null(Register r) {
6551   if (Universe::narrow_klass_base() != NULL) {
6552     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6553     assert(r != r12_heapbase, "Encoding a klass in r12");
6554     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6555     subq(r, r12_heapbase);
6556   }
6557   if (Universe::narrow_klass_shift() != 0) {
6558     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6559     shrq(r, LogKlassAlignmentInBytes);
6560   }
6561   if (Universe::narrow_klass_base() != NULL) {
6562     reinit_heapbase();
6563   }
6564 }
6565 
6566 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6567   if (dst == src) {
6568     encode_klass_not_null(src);
6569   } else {
6570     if (Universe::narrow_klass_base() != NULL) {
6571       mov64(dst, (int64_t)Universe::narrow_klass_base());
6572       negq(dst);
6573       addq(dst, src);
6574     } else {
6575       movptr(dst, src);
6576     }
6577     if (Universe::narrow_klass_shift() != 0) {
6578       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6579       shrq(dst, LogKlassAlignmentInBytes);
6580     }
6581   }
6582 }
6583 
6584 // Function instr_size_for_decode_klass_not_null() counts the instructions
6585 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6586 // when (Universe::heap() != NULL).  Hence, if the instructions they
6587 // generate change, then this method needs to be updated.
6588 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6589   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6590   if (Universe::narrow_klass_base() != NULL) {
6591     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6592     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6593   } else {
6594     // longest load decode klass function, mov64, leaq
6595     return 16;
6596   }
6597 }
6598 
6599 // !!! If the instructions that get generated here change then function
6600 // instr_size_for_decode_klass_not_null() needs to get updated.
6601 void  MacroAssembler::decode_klass_not_null(Register r) {
6602   // Note: it will change flags
6603   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6604   assert(r != r12_heapbase, "Decoding a klass in r12");
6605   // Cannot assert, unverified entry point counts instructions (see .ad file)
6606   // vtableStubs also counts instructions in pd_code_size_limit.
6607   // Also do not verify_oop as this is called by verify_oop.
6608   if (Universe::narrow_klass_shift() != 0) {
6609     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6610     shlq(r, LogKlassAlignmentInBytes);
6611   }
6612   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6613   if (Universe::narrow_klass_base() != NULL) {
6614     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6615     addq(r, r12_heapbase);
6616     reinit_heapbase();
6617   }
6618 }
6619 
6620 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6621   // Note: it will change flags
6622   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6623   if (dst == src) {
6624     decode_klass_not_null(dst);
6625   } else {
6626     // Cannot assert, unverified entry point counts instructions (see .ad file)
6627     // vtableStubs also counts instructions in pd_code_size_limit.
6628     // Also do not verify_oop as this is called by verify_oop.
6629     mov64(dst, (int64_t)Universe::narrow_klass_base());
6630     if (Universe::narrow_klass_shift() != 0) {
6631       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6632       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6633       leaq(dst, Address(dst, src, Address::times_8, 0));
6634     } else {
6635       addq(dst, src);
6636     }
6637   }
6638 }
6639 
6640 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6641   assert (UseCompressedOops, "should only be used for compressed headers");
6642   assert (Universe::heap() != NULL, "java heap should be initialized");
6643   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6644   int oop_index = oop_recorder()->find_index(obj);
6645   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6646   mov_narrow_oop(dst, oop_index, rspec);
6647 }
6648 
6649 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6650   assert (UseCompressedOops, "should only be used for compressed headers");
6651   assert (Universe::heap() != NULL, "java heap should be initialized");
6652   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6653   int oop_index = oop_recorder()->find_index(obj);
6654   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6655   mov_narrow_oop(dst, oop_index, rspec);
6656 }
6657 
6658 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6659   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6660   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6661   int klass_index = oop_recorder()->find_index(k);
6662   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6663   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6664 }
6665 
6666 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
6667   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6668   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6669   int klass_index = oop_recorder()->find_index(k);
6670   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6671   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6672 }
6673 
6674 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
6675   assert (UseCompressedOops, "should only be used for compressed headers");
6676   assert (Universe::heap() != NULL, "java heap should be initialized");
6677   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6678   int oop_index = oop_recorder()->find_index(obj);
6679   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6680   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6681 }
6682 
6683 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
6684   assert (UseCompressedOops, "should only be used for compressed headers");
6685   assert (Universe::heap() != NULL, "java heap should be initialized");
6686   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6687   int oop_index = oop_recorder()->find_index(obj);
6688   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6689   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6690 }
6691 
6692 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
6693   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6694   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6695   int klass_index = oop_recorder()->find_index(k);
6696   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6697   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6698 }
6699 
6700 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
6701   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6702   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6703   int klass_index = oop_recorder()->find_index(k);
6704   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6705   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6706 }
6707 
6708 void MacroAssembler::reinit_heapbase() {
6709   if (UseCompressedOops || UseCompressedClassPointers) {
6710     if (Universe::heap() != NULL) {
6711       if (Universe::narrow_oop_base() == NULL) {
6712         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
6713       } else {
6714         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
6715       }
6716     } else {
6717       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6718     }
6719   }
6720 }
6721 
6722 #endif // _LP64
6723 
6724 // C2 compiled method's prolog code.
6725 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
6726 
6727   // WARNING: Initial instruction MUST be 5 bytes or longer so that
6728   // NativeJump::patch_verified_entry will be able to patch out the entry
6729   // code safely. The push to verify stack depth is ok at 5 bytes,
6730   // the frame allocation can be either 3 or 6 bytes. So if we don't do
6731   // stack bang then we must use the 6 byte frame allocation even if
6732   // we have no frame. :-(
6733   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
6734 
6735   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6736   // Remove word for return addr
6737   framesize -= wordSize;
6738   stack_bang_size -= wordSize;
6739 
6740   // Calls to C2R adapters often do not accept exceptional returns.
6741   // We require that their callers must bang for them.  But be careful, because
6742   // some VM calls (such as call site linkage) can use several kilobytes of
6743   // stack.  But the stack safety zone should account for that.
6744   // See bugs 4446381, 4468289, 4497237.
6745   if (stack_bang_size > 0) {
6746     generate_stack_overflow_check(stack_bang_size);
6747 
6748     // We always push rbp, so that on return to interpreter rbp, will be
6749     // restored correctly and we can correct the stack.
6750     push(rbp);
6751     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6752     if (PreserveFramePointer) {
6753       mov(rbp, rsp);
6754     }
6755     // Remove word for ebp
6756     framesize -= wordSize;
6757 
6758     // Create frame
6759     if (framesize) {
6760       subptr(rsp, framesize);
6761     }
6762   } else {
6763     // Create frame (force generation of a 4 byte immediate value)
6764     subptr_imm32(rsp, framesize);
6765 
6766     // Save RBP register now.
6767     framesize -= wordSize;
6768     movptr(Address(rsp, framesize), rbp);
6769     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6770     if (PreserveFramePointer) {
6771       movptr(rbp, rsp);
6772       if (framesize > 0) {
6773         addptr(rbp, framesize);
6774       }
6775     }
6776   }
6777 
6778   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
6779     framesize -= wordSize;
6780     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
6781   }
6782 
6783 #ifndef _LP64
6784   // If method sets FPU control word do it now
6785   if (fp_mode_24b) {
6786     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
6787   }
6788   if (UseSSE >= 2 && VerifyFPU) {
6789     verify_FPU(0, "FPU stack must be clean on entry");
6790   }
6791 #endif
6792 
6793 #ifdef ASSERT
6794   if (VerifyStackAtCalls) {
6795     Label L;
6796     push(rax);
6797     mov(rax, rsp);
6798     andptr(rax, StackAlignmentInBytes-1);
6799     cmpptr(rax, StackAlignmentInBytes-wordSize);
6800     pop(rax);
6801     jcc(Assembler::equal, L);
6802     STOP("Stack is not properly aligned!");
6803     bind(L);
6804   }
6805 #endif
6806 
6807 }
6808 
6809 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
6810   // cnt - number of qwords (8-byte words).
6811   // base - start address, qword aligned.
6812   // is_large - if optimizers know cnt is larger than InitArrayShortSize
6813   assert(base==rdi, "base register must be edi for rep stos");
6814   assert(tmp==rax,   "tmp register must be eax for rep stos");
6815   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
6816   assert(InitArrayShortSize % BytesPerLong == 0,
6817     "InitArrayShortSize should be the multiple of BytesPerLong");
6818 
6819   Label DONE;
6820 
6821   xorptr(tmp, tmp);
6822 
6823   if (!is_large) {
6824     Label LOOP, LONG;
6825     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
6826     jccb(Assembler::greater, LONG);
6827 
6828     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6829 
6830     decrement(cnt);
6831     jccb(Assembler::negative, DONE); // Zero length
6832 
6833     // Use individual pointer-sized stores for small counts:
6834     BIND(LOOP);
6835     movptr(Address(base, cnt, Address::times_ptr), tmp);
6836     decrement(cnt);
6837     jccb(Assembler::greaterEqual, LOOP);
6838     jmpb(DONE);
6839 
6840     BIND(LONG);
6841   }
6842 
6843   // Use longer rep-prefixed ops for non-small counts:
6844   if (UseFastStosb) {
6845     shlptr(cnt, 3); // convert to number of bytes
6846     rep_stosb();
6847   } else {
6848     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6849     rep_stos();
6850   }
6851 
6852   BIND(DONE);
6853 }
6854 
6855 #ifdef COMPILER2
6856 
6857 // IndexOf for constant substrings with size >= 8 chars
6858 // which don't need to be loaded through stack.
6859 void MacroAssembler::string_indexofC8(Register str1, Register str2,
6860                                       Register cnt1, Register cnt2,
6861                                       int int_cnt2,  Register result,
6862                                       XMMRegister vec, Register tmp,
6863                                       int ae) {
6864   ShortBranchVerifier sbv(this);
6865   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6866   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6867 
6868   // This method uses the pcmpestri instruction with bound registers
6869   //   inputs:
6870   //     xmm - substring
6871   //     rax - substring length (elements count)
6872   //     mem - scanned string
6873   //     rdx - string length (elements count)
6874   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6875   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6876   //   outputs:
6877   //     rcx - matched index in string
6878   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6879   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
6880   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
6881   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
6882   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
6883 
6884   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
6885         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
6886         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
6887 
6888   // Note, inline_string_indexOf() generates checks:
6889   // if (substr.count > string.count) return -1;
6890   // if (substr.count == 0) return 0;
6891   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
6892 
6893   // Load substring.
6894   if (ae == StrIntrinsicNode::UL) {
6895     pmovzxbw(vec, Address(str2, 0));
6896   } else {
6897     movdqu(vec, Address(str2, 0));
6898   }
6899   movl(cnt2, int_cnt2);
6900   movptr(result, str1); // string addr
6901 
6902   if (int_cnt2 > stride) {
6903     jmpb(SCAN_TO_SUBSTR);
6904 
6905     // Reload substr for rescan, this code
6906     // is executed only for large substrings (> 8 chars)
6907     bind(RELOAD_SUBSTR);
6908     if (ae == StrIntrinsicNode::UL) {
6909       pmovzxbw(vec, Address(str2, 0));
6910     } else {
6911       movdqu(vec, Address(str2, 0));
6912     }
6913     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
6914 
6915     bind(RELOAD_STR);
6916     // We came here after the beginning of the substring was
6917     // matched but the rest of it was not so we need to search
6918     // again. Start from the next element after the previous match.
6919 
6920     // cnt2 is number of substring reminding elements and
6921     // cnt1 is number of string reminding elements when cmp failed.
6922     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
6923     subl(cnt1, cnt2);
6924     addl(cnt1, int_cnt2);
6925     movl(cnt2, int_cnt2); // Now restore cnt2
6926 
6927     decrementl(cnt1);     // Shift to next element
6928     cmpl(cnt1, cnt2);
6929     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6930 
6931     addptr(result, (1<<scale1));
6932 
6933   } // (int_cnt2 > 8)
6934 
6935   // Scan string for start of substr in 16-byte vectors
6936   bind(SCAN_TO_SUBSTR);
6937   pcmpestri(vec, Address(result, 0), mode);
6938   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6939   subl(cnt1, stride);
6940   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6941   cmpl(cnt1, cnt2);
6942   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6943   addptr(result, 16);
6944   jmpb(SCAN_TO_SUBSTR);
6945 
6946   // Found a potential substr
6947   bind(FOUND_CANDIDATE);
6948   // Matched whole vector if first element matched (tmp(rcx) == 0).
6949   if (int_cnt2 == stride) {
6950     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
6951   } else { // int_cnt2 > 8
6952     jccb(Assembler::overflow, FOUND_SUBSTR);
6953   }
6954   // After pcmpestri tmp(rcx) contains matched element index
6955   // Compute start addr of substr
6956   lea(result, Address(result, tmp, scale1));
6957 
6958   // Make sure string is still long enough
6959   subl(cnt1, tmp);
6960   cmpl(cnt1, cnt2);
6961   if (int_cnt2 == stride) {
6962     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6963   } else { // int_cnt2 > 8
6964     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
6965   }
6966   // Left less then substring.
6967 
6968   bind(RET_NOT_FOUND);
6969   movl(result, -1);
6970   jmp(EXIT);
6971 
6972   if (int_cnt2 > stride) {
6973     // This code is optimized for the case when whole substring
6974     // is matched if its head is matched.
6975     bind(MATCH_SUBSTR_HEAD);
6976     pcmpestri(vec, Address(result, 0), mode);
6977     // Reload only string if does not match
6978     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
6979 
6980     Label CONT_SCAN_SUBSTR;
6981     // Compare the rest of substring (> 8 chars).
6982     bind(FOUND_SUBSTR);
6983     // First 8 chars are already matched.
6984     negptr(cnt2);
6985     addptr(cnt2, stride);
6986 
6987     bind(SCAN_SUBSTR);
6988     subl(cnt1, stride);
6989     cmpl(cnt2, -stride); // Do not read beyond substring
6990     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
6991     // Back-up strings to avoid reading beyond substring:
6992     // cnt1 = cnt1 - cnt2 + 8
6993     addl(cnt1, cnt2); // cnt2 is negative
6994     addl(cnt1, stride);
6995     movl(cnt2, stride); negptr(cnt2);
6996     bind(CONT_SCAN_SUBSTR);
6997     if (int_cnt2 < (int)G) {
6998       int tail_off1 = int_cnt2<<scale1;
6999       int tail_off2 = int_cnt2<<scale2;
7000       if (ae == StrIntrinsicNode::UL) {
7001         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7002       } else {
7003         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7004       }
7005       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7006     } else {
7007       // calculate index in register to avoid integer overflow (int_cnt2*2)
7008       movl(tmp, int_cnt2);
7009       addptr(tmp, cnt2);
7010       if (ae == StrIntrinsicNode::UL) {
7011         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7012       } else {
7013         movdqu(vec, Address(str2, tmp, scale2, 0));
7014       }
7015       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7016     }
7017     // Need to reload strings pointers if not matched whole vector
7018     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7019     addptr(cnt2, stride);
7020     jcc(Assembler::negative, SCAN_SUBSTR);
7021     // Fall through if found full substring
7022 
7023   } // (int_cnt2 > 8)
7024 
7025   bind(RET_FOUND);
7026   // Found result if we matched full small substring.
7027   // Compute substr offset
7028   subptr(result, str1);
7029   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7030     shrl(result, 1); // index
7031   }
7032   bind(EXIT);
7033 
7034 } // string_indexofC8
7035 
7036 // Small strings are loaded through stack if they cross page boundary.
7037 void MacroAssembler::string_indexof(Register str1, Register str2,
7038                                     Register cnt1, Register cnt2,
7039                                     int int_cnt2,  Register result,
7040                                     XMMRegister vec, Register tmp,
7041                                     int ae) {
7042   ShortBranchVerifier sbv(this);
7043   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7044   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7045 
7046   //
7047   // int_cnt2 is length of small (< 8 chars) constant substring
7048   // or (-1) for non constant substring in which case its length
7049   // is in cnt2 register.
7050   //
7051   // Note, inline_string_indexOf() generates checks:
7052   // if (substr.count > string.count) return -1;
7053   // if (substr.count == 0) return 0;
7054   //
7055   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7056   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7057   // This method uses the pcmpestri instruction with bound registers
7058   //   inputs:
7059   //     xmm - substring
7060   //     rax - substring length (elements count)
7061   //     mem - scanned string
7062   //     rdx - string length (elements count)
7063   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7064   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7065   //   outputs:
7066   //     rcx - matched index in string
7067   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7068   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7069   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7070   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7071 
7072   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7073         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7074         FOUND_CANDIDATE;
7075 
7076   { //========================================================
7077     // We don't know where these strings are located
7078     // and we can't read beyond them. Load them through stack.
7079     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7080 
7081     movptr(tmp, rsp); // save old SP
7082 
7083     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7084       if (int_cnt2 == (1>>scale2)) { // One byte
7085         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7086         load_unsigned_byte(result, Address(str2, 0));
7087         movdl(vec, result); // move 32 bits
7088       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7089         // Not enough header space in 32-bit VM: 12+3 = 15.
7090         movl(result, Address(str2, -1));
7091         shrl(result, 8);
7092         movdl(vec, result); // move 32 bits
7093       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7094         load_unsigned_short(result, Address(str2, 0));
7095         movdl(vec, result); // move 32 bits
7096       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7097         movdl(vec, Address(str2, 0)); // move 32 bits
7098       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7099         movq(vec, Address(str2, 0));  // move 64 bits
7100       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7101         // Array header size is 12 bytes in 32-bit VM
7102         // + 6 bytes for 3 chars == 18 bytes,
7103         // enough space to load vec and shift.
7104         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7105         if (ae == StrIntrinsicNode::UL) {
7106           int tail_off = int_cnt2-8;
7107           pmovzxbw(vec, Address(str2, tail_off));
7108           psrldq(vec, -2*tail_off);
7109         }
7110         else {
7111           int tail_off = int_cnt2*(1<<scale2);
7112           movdqu(vec, Address(str2, tail_off-16));
7113           psrldq(vec, 16-tail_off);
7114         }
7115       }
7116     } else { // not constant substring
7117       cmpl(cnt2, stride);
7118       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7119 
7120       // We can read beyond string if srt+16 does not cross page boundary
7121       // since heaps are aligned and mapped by pages.
7122       assert(os::vm_page_size() < (int)G, "default page should be small");
7123       movl(result, str2); // We need only low 32 bits
7124       andl(result, (os::vm_page_size()-1));
7125       cmpl(result, (os::vm_page_size()-16));
7126       jccb(Assembler::belowEqual, CHECK_STR);
7127 
7128       // Move small strings to stack to allow load 16 bytes into vec.
7129       subptr(rsp, 16);
7130       int stk_offset = wordSize-(1<<scale2);
7131       push(cnt2);
7132 
7133       bind(COPY_SUBSTR);
7134       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7135         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7136         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7137       } else if (ae == StrIntrinsicNode::UU) {
7138         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7139         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7140       }
7141       decrement(cnt2);
7142       jccb(Assembler::notZero, COPY_SUBSTR);
7143 
7144       pop(cnt2);
7145       movptr(str2, rsp);  // New substring address
7146     } // non constant
7147 
7148     bind(CHECK_STR);
7149     cmpl(cnt1, stride);
7150     jccb(Assembler::aboveEqual, BIG_STRINGS);
7151 
7152     // Check cross page boundary.
7153     movl(result, str1); // We need only low 32 bits
7154     andl(result, (os::vm_page_size()-1));
7155     cmpl(result, (os::vm_page_size()-16));
7156     jccb(Assembler::belowEqual, BIG_STRINGS);
7157 
7158     subptr(rsp, 16);
7159     int stk_offset = -(1<<scale1);
7160     if (int_cnt2 < 0) { // not constant
7161       push(cnt2);
7162       stk_offset += wordSize;
7163     }
7164     movl(cnt2, cnt1);
7165 
7166     bind(COPY_STR);
7167     if (ae == StrIntrinsicNode::LL) {
7168       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7169       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7170     } else {
7171       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7172       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7173     }
7174     decrement(cnt2);
7175     jccb(Assembler::notZero, COPY_STR);
7176 
7177     if (int_cnt2 < 0) { // not constant
7178       pop(cnt2);
7179     }
7180     movptr(str1, rsp);  // New string address
7181 
7182     bind(BIG_STRINGS);
7183     // Load substring.
7184     if (int_cnt2 < 0) { // -1
7185       if (ae == StrIntrinsicNode::UL) {
7186         pmovzxbw(vec, Address(str2, 0));
7187       } else {
7188         movdqu(vec, Address(str2, 0));
7189       }
7190       push(cnt2);       // substr count
7191       push(str2);       // substr addr
7192       push(str1);       // string addr
7193     } else {
7194       // Small (< 8 chars) constant substrings are loaded already.
7195       movl(cnt2, int_cnt2);
7196     }
7197     push(tmp);  // original SP
7198 
7199   } // Finished loading
7200 
7201   //========================================================
7202   // Start search
7203   //
7204 
7205   movptr(result, str1); // string addr
7206 
7207   if (int_cnt2  < 0) {  // Only for non constant substring
7208     jmpb(SCAN_TO_SUBSTR);
7209 
7210     // SP saved at sp+0
7211     // String saved at sp+1*wordSize
7212     // Substr saved at sp+2*wordSize
7213     // Substr count saved at sp+3*wordSize
7214 
7215     // Reload substr for rescan, this code
7216     // is executed only for large substrings (> 8 chars)
7217     bind(RELOAD_SUBSTR);
7218     movptr(str2, Address(rsp, 2*wordSize));
7219     movl(cnt2, Address(rsp, 3*wordSize));
7220     if (ae == StrIntrinsicNode::UL) {
7221       pmovzxbw(vec, Address(str2, 0));
7222     } else {
7223       movdqu(vec, Address(str2, 0));
7224     }
7225     // We came here after the beginning of the substring was
7226     // matched but the rest of it was not so we need to search
7227     // again. Start from the next element after the previous match.
7228     subptr(str1, result); // Restore counter
7229     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7230       shrl(str1, 1);
7231     }
7232     addl(cnt1, str1);
7233     decrementl(cnt1);   // Shift to next element
7234     cmpl(cnt1, cnt2);
7235     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7236 
7237     addptr(result, (1<<scale1));
7238   } // non constant
7239 
7240   // Scan string for start of substr in 16-byte vectors
7241   bind(SCAN_TO_SUBSTR);
7242   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7243   pcmpestri(vec, Address(result, 0), mode);
7244   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7245   subl(cnt1, stride);
7246   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7247   cmpl(cnt1, cnt2);
7248   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7249   addptr(result, 16);
7250 
7251   bind(ADJUST_STR);
7252   cmpl(cnt1, stride); // Do not read beyond string
7253   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7254   // Back-up string to avoid reading beyond string.
7255   lea(result, Address(result, cnt1, scale1, -16));
7256   movl(cnt1, stride);
7257   jmpb(SCAN_TO_SUBSTR);
7258 
7259   // Found a potential substr
7260   bind(FOUND_CANDIDATE);
7261   // After pcmpestri tmp(rcx) contains matched element index
7262 
7263   // Make sure string is still long enough
7264   subl(cnt1, tmp);
7265   cmpl(cnt1, cnt2);
7266   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7267   // Left less then substring.
7268 
7269   bind(RET_NOT_FOUND);
7270   movl(result, -1);
7271   jmpb(CLEANUP);
7272 
7273   bind(FOUND_SUBSTR);
7274   // Compute start addr of substr
7275   lea(result, Address(result, tmp, scale1));
7276   if (int_cnt2 > 0) { // Constant substring
7277     // Repeat search for small substring (< 8 chars)
7278     // from new point without reloading substring.
7279     // Have to check that we don't read beyond string.
7280     cmpl(tmp, stride-int_cnt2);
7281     jccb(Assembler::greater, ADJUST_STR);
7282     // Fall through if matched whole substring.
7283   } else { // non constant
7284     assert(int_cnt2 == -1, "should be != 0");
7285 
7286     addl(tmp, cnt2);
7287     // Found result if we matched whole substring.
7288     cmpl(tmp, stride);
7289     jccb(Assembler::lessEqual, RET_FOUND);
7290 
7291     // Repeat search for small substring (<= 8 chars)
7292     // from new point 'str1' without reloading substring.
7293     cmpl(cnt2, stride);
7294     // Have to check that we don't read beyond string.
7295     jccb(Assembler::lessEqual, ADJUST_STR);
7296 
7297     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7298     // Compare the rest of substring (> 8 chars).
7299     movptr(str1, result);
7300 
7301     cmpl(tmp, cnt2);
7302     // First 8 chars are already matched.
7303     jccb(Assembler::equal, CHECK_NEXT);
7304 
7305     bind(SCAN_SUBSTR);
7306     pcmpestri(vec, Address(str1, 0), mode);
7307     // Need to reload strings pointers if not matched whole vector
7308     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7309 
7310     bind(CHECK_NEXT);
7311     subl(cnt2, stride);
7312     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7313     addptr(str1, 16);
7314     if (ae == StrIntrinsicNode::UL) {
7315       addptr(str2, 8);
7316     } else {
7317       addptr(str2, 16);
7318     }
7319     subl(cnt1, stride);
7320     cmpl(cnt2, stride); // Do not read beyond substring
7321     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7322     // Back-up strings to avoid reading beyond substring.
7323 
7324     if (ae == StrIntrinsicNode::UL) {
7325       lea(str2, Address(str2, cnt2, scale2, -8));
7326       lea(str1, Address(str1, cnt2, scale1, -16));
7327     } else {
7328       lea(str2, Address(str2, cnt2, scale2, -16));
7329       lea(str1, Address(str1, cnt2, scale1, -16));
7330     }
7331     subl(cnt1, cnt2);
7332     movl(cnt2, stride);
7333     addl(cnt1, stride);
7334     bind(CONT_SCAN_SUBSTR);
7335     if (ae == StrIntrinsicNode::UL) {
7336       pmovzxbw(vec, Address(str2, 0));
7337     } else {
7338       movdqu(vec, Address(str2, 0));
7339     }
7340     jmp(SCAN_SUBSTR);
7341 
7342     bind(RET_FOUND_LONG);
7343     movptr(str1, Address(rsp, wordSize));
7344   } // non constant
7345 
7346   bind(RET_FOUND);
7347   // Compute substr offset
7348   subptr(result, str1);
7349   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7350     shrl(result, 1); // index
7351   }
7352   bind(CLEANUP);
7353   pop(rsp); // restore SP
7354 
7355 } // string_indexof
7356 
7357 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7358                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7359   ShortBranchVerifier sbv(this);
7360   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7361 
7362   int stride = 8;
7363 
7364   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7365         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7366         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7367         FOUND_SEQ_CHAR, DONE_LABEL;
7368 
7369   movptr(result, str1);
7370   if (UseAVX >= 2) {
7371     cmpl(cnt1, stride);
7372     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7373     cmpl(cnt1, 2*stride);
7374     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7375     movdl(vec1, ch);
7376     vpbroadcastw(vec1, vec1);
7377     vpxor(vec2, vec2);
7378     movl(tmp, cnt1);
7379     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7380     andl(cnt1,0x0000000F);  //tail count (in chars)
7381 
7382     bind(SCAN_TO_16_CHAR_LOOP);
7383     vmovdqu(vec3, Address(result, 0));
7384     vpcmpeqw(vec3, vec3, vec1, 1);
7385     vptest(vec2, vec3);
7386     jcc(Assembler::carryClear, FOUND_CHAR);
7387     addptr(result, 32);
7388     subl(tmp, 2*stride);
7389     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7390     jmp(SCAN_TO_8_CHAR);
7391     bind(SCAN_TO_8_CHAR_INIT);
7392     movdl(vec1, ch);
7393     pshuflw(vec1, vec1, 0x00);
7394     pshufd(vec1, vec1, 0);
7395     pxor(vec2, vec2);
7396   }
7397   bind(SCAN_TO_8_CHAR);
7398   cmpl(cnt1, stride);
7399   if (UseAVX >= 2) {
7400     jcc(Assembler::less, SCAN_TO_CHAR);
7401   } else {
7402     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7403     movdl(vec1, ch);
7404     pshuflw(vec1, vec1, 0x00);
7405     pshufd(vec1, vec1, 0);
7406     pxor(vec2, vec2);
7407   }
7408   movl(tmp, cnt1);
7409   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7410   andl(cnt1,0x00000007);  //tail count (in chars)
7411 
7412   bind(SCAN_TO_8_CHAR_LOOP);
7413   movdqu(vec3, Address(result, 0));
7414   pcmpeqw(vec3, vec1);
7415   ptest(vec2, vec3);
7416   jcc(Assembler::carryClear, FOUND_CHAR);
7417   addptr(result, 16);
7418   subl(tmp, stride);
7419   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7420   bind(SCAN_TO_CHAR);
7421   testl(cnt1, cnt1);
7422   jcc(Assembler::zero, RET_NOT_FOUND);
7423   bind(SCAN_TO_CHAR_LOOP);
7424   load_unsigned_short(tmp, Address(result, 0));
7425   cmpl(ch, tmp);
7426   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7427   addptr(result, 2);
7428   subl(cnt1, 1);
7429   jccb(Assembler::zero, RET_NOT_FOUND);
7430   jmp(SCAN_TO_CHAR_LOOP);
7431 
7432   bind(RET_NOT_FOUND);
7433   movl(result, -1);
7434   jmpb(DONE_LABEL);
7435 
7436   bind(FOUND_CHAR);
7437   if (UseAVX >= 2) {
7438     vpmovmskb(tmp, vec3);
7439   } else {
7440     pmovmskb(tmp, vec3);
7441   }
7442   bsfl(ch, tmp);
7443   addl(result, ch);
7444 
7445   bind(FOUND_SEQ_CHAR);
7446   subptr(result, str1);
7447   shrl(result, 1);
7448 
7449   bind(DONE_LABEL);
7450 } // string_indexof_char
7451 
7452 // helper function for string_compare
7453 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7454                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7455                                         Address::ScaleFactor scale2, Register index, int ae) {
7456   if (ae == StrIntrinsicNode::LL) {
7457     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7458     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7459   } else if (ae == StrIntrinsicNode::UU) {
7460     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7461     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7462   } else {
7463     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7464     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7465   }
7466 }
7467 
7468 // Compare strings, used for char[] and byte[].
7469 void MacroAssembler::string_compare(Register str1, Register str2,
7470                                     Register cnt1, Register cnt2, Register result,
7471                                     XMMRegister vec1, int ae) {
7472   ShortBranchVerifier sbv(this);
7473   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7474   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7475   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7476   int stride2x2 = 0x40;
7477   Address::ScaleFactor scale = Address::no_scale;
7478   Address::ScaleFactor scale1 = Address::no_scale;
7479   Address::ScaleFactor scale2 = Address::no_scale;
7480 
7481   if (ae != StrIntrinsicNode::LL) {
7482     stride2x2 = 0x20;
7483   }
7484 
7485   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7486     shrl(cnt2, 1);
7487   }
7488   // Compute the minimum of the string lengths and the
7489   // difference of the string lengths (stack).
7490   // Do the conditional move stuff
7491   movl(result, cnt1);
7492   subl(cnt1, cnt2);
7493   push(cnt1);
7494   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7495 
7496   // Is the minimum length zero?
7497   testl(cnt2, cnt2);
7498   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7499   if (ae == StrIntrinsicNode::LL) {
7500     // Load first bytes
7501     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7502     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7503   } else if (ae == StrIntrinsicNode::UU) {
7504     // Load first characters
7505     load_unsigned_short(result, Address(str1, 0));
7506     load_unsigned_short(cnt1, Address(str2, 0));
7507   } else {
7508     load_unsigned_byte(result, Address(str1, 0));
7509     load_unsigned_short(cnt1, Address(str2, 0));
7510   }
7511   subl(result, cnt1);
7512   jcc(Assembler::notZero,  POP_LABEL);
7513 
7514   if (ae == StrIntrinsicNode::UU) {
7515     // Divide length by 2 to get number of chars
7516     shrl(cnt2, 1);
7517   }
7518   cmpl(cnt2, 1);
7519   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7520 
7521   // Check if the strings start at the same location and setup scale and stride
7522   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7523     cmpptr(str1, str2);
7524     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7525     if (ae == StrIntrinsicNode::LL) {
7526       scale = Address::times_1;
7527       stride = 16;
7528     } else {
7529       scale = Address::times_2;
7530       stride = 8;
7531     }
7532   } else {
7533     scale1 = Address::times_1;
7534     scale2 = Address::times_2;
7535     // scale not used
7536     stride = 8;
7537   }
7538 
7539   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7540     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7541     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7542     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7543     Label COMPARE_TAIL_LONG;
7544     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7545 
7546     int pcmpmask = 0x19;
7547     if (ae == StrIntrinsicNode::LL) {
7548       pcmpmask &= ~0x01;
7549     }
7550 
7551     // Setup to compare 16-chars (32-bytes) vectors,
7552     // start from first character again because it has aligned address.
7553     if (ae == StrIntrinsicNode::LL) {
7554       stride2 = 32;
7555     } else {
7556       stride2 = 16;
7557     }
7558     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7559       adr_stride = stride << scale;
7560     } else {
7561       adr_stride1 = 8;  //stride << scale1;
7562       adr_stride2 = 16; //stride << scale2;
7563     }
7564 
7565     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7566     // rax and rdx are used by pcmpestri as elements counters
7567     movl(result, cnt2);
7568     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7569     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7570 
7571     // fast path : compare first 2 8-char vectors.
7572     bind(COMPARE_16_CHARS);
7573     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7574       movdqu(vec1, Address(str1, 0));
7575     } else {
7576       pmovzxbw(vec1, Address(str1, 0));
7577     }
7578     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7579     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7580 
7581     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7582       movdqu(vec1, Address(str1, adr_stride));
7583       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7584     } else {
7585       pmovzxbw(vec1, Address(str1, adr_stride1));
7586       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7587     }
7588     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7589     addl(cnt1, stride);
7590 
7591     // Compare the characters at index in cnt1
7592     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7593     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7594     subl(result, cnt2);
7595     jmp(POP_LABEL);
7596 
7597     // Setup the registers to start vector comparison loop
7598     bind(COMPARE_WIDE_VECTORS);
7599     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7600       lea(str1, Address(str1, result, scale));
7601       lea(str2, Address(str2, result, scale));
7602     } else {
7603       lea(str1, Address(str1, result, scale1));
7604       lea(str2, Address(str2, result, scale2));
7605     }
7606     subl(result, stride2);
7607     subl(cnt2, stride2);
7608     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7609     negptr(result);
7610 
7611     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7612     bind(COMPARE_WIDE_VECTORS_LOOP);
7613 
7614 #ifdef _LP64
7615     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7616       cmpl(cnt2, stride2x2);
7617       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7618       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7619       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7620 
7621       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7622       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7623         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7624         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7625       } else {
7626         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7627         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7628       }
7629       kortestql(k7, k7);
7630       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7631       addptr(result, stride2x2);  // update since we already compared at this addr
7632       subl(cnt2, stride2x2);      // and sub the size too
7633       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7634 
7635       vpxor(vec1, vec1);
7636       jmpb(COMPARE_WIDE_TAIL);
7637     }//if (VM_Version::supports_avx512vlbw())
7638 #endif // _LP64
7639 
7640 
7641     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7642     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7643       vmovdqu(vec1, Address(str1, result, scale));
7644       vpxor(vec1, Address(str2, result, scale));
7645     } else {
7646       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7647       vpxor(vec1, Address(str2, result, scale2));
7648     }
7649     vptest(vec1, vec1);
7650     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7651     addptr(result, stride2);
7652     subl(cnt2, stride2);
7653     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7654     // clean upper bits of YMM registers
7655     vpxor(vec1, vec1);
7656 
7657     // compare wide vectors tail
7658     bind(COMPARE_WIDE_TAIL);
7659     testptr(result, result);
7660     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7661 
7662     movl(result, stride2);
7663     movl(cnt2, result);
7664     negptr(result);
7665     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7666 
7667     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7668     bind(VECTOR_NOT_EQUAL);
7669     // clean upper bits of YMM registers
7670     vpxor(vec1, vec1);
7671     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7672       lea(str1, Address(str1, result, scale));
7673       lea(str2, Address(str2, result, scale));
7674     } else {
7675       lea(str1, Address(str1, result, scale1));
7676       lea(str2, Address(str2, result, scale2));
7677     }
7678     jmp(COMPARE_16_CHARS);
7679 
7680     // Compare tail chars, length between 1 to 15 chars
7681     bind(COMPARE_TAIL_LONG);
7682     movl(cnt2, result);
7683     cmpl(cnt2, stride);
7684     jcc(Assembler::less, COMPARE_SMALL_STR);
7685 
7686     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7687       movdqu(vec1, Address(str1, 0));
7688     } else {
7689       pmovzxbw(vec1, Address(str1, 0));
7690     }
7691     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7692     jcc(Assembler::below, COMPARE_INDEX_CHAR);
7693     subptr(cnt2, stride);
7694     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7695     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7696       lea(str1, Address(str1, result, scale));
7697       lea(str2, Address(str2, result, scale));
7698     } else {
7699       lea(str1, Address(str1, result, scale1));
7700       lea(str2, Address(str2, result, scale2));
7701     }
7702     negptr(cnt2);
7703     jmpb(WHILE_HEAD_LABEL);
7704 
7705     bind(COMPARE_SMALL_STR);
7706   } else if (UseSSE42Intrinsics) {
7707     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
7708     int pcmpmask = 0x19;
7709     // Setup to compare 8-char (16-byte) vectors,
7710     // start from first character again because it has aligned address.
7711     movl(result, cnt2);
7712     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
7713     if (ae == StrIntrinsicNode::LL) {
7714       pcmpmask &= ~0x01;
7715     }
7716     jcc(Assembler::zero, COMPARE_TAIL);
7717     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7718       lea(str1, Address(str1, result, scale));
7719       lea(str2, Address(str2, result, scale));
7720     } else {
7721       lea(str1, Address(str1, result, scale1));
7722       lea(str2, Address(str2, result, scale2));
7723     }
7724     negptr(result);
7725 
7726     // pcmpestri
7727     //   inputs:
7728     //     vec1- substring
7729     //     rax - negative string length (elements count)
7730     //     mem - scanned string
7731     //     rdx - string length (elements count)
7732     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
7733     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
7734     //   outputs:
7735     //     rcx - first mismatched element index
7736     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7737 
7738     bind(COMPARE_WIDE_VECTORS);
7739     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7740       movdqu(vec1, Address(str1, result, scale));
7741       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7742     } else {
7743       pmovzxbw(vec1, Address(str1, result, scale1));
7744       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7745     }
7746     // After pcmpestri cnt1(rcx) contains mismatched element index
7747 
7748     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
7749     addptr(result, stride);
7750     subptr(cnt2, stride);
7751     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
7752 
7753     // compare wide vectors tail
7754     testptr(result, result);
7755     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7756 
7757     movl(cnt2, stride);
7758     movl(result, stride);
7759     negptr(result);
7760     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7761       movdqu(vec1, Address(str1, result, scale));
7762       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7763     } else {
7764       pmovzxbw(vec1, Address(str1, result, scale1));
7765       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7766     }
7767     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
7768 
7769     // Mismatched characters in the vectors
7770     bind(VECTOR_NOT_EQUAL);
7771     addptr(cnt1, result);
7772     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7773     subl(result, cnt2);
7774     jmpb(POP_LABEL);
7775 
7776     bind(COMPARE_TAIL); // limit is zero
7777     movl(cnt2, result);
7778     // Fallthru to tail compare
7779   }
7780   // Shift str2 and str1 to the end of the arrays, negate min
7781   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7782     lea(str1, Address(str1, cnt2, scale));
7783     lea(str2, Address(str2, cnt2, scale));
7784   } else {
7785     lea(str1, Address(str1, cnt2, scale1));
7786     lea(str2, Address(str2, cnt2, scale2));
7787   }
7788   decrementl(cnt2);  // first character was compared already
7789   negptr(cnt2);
7790 
7791   // Compare the rest of the elements
7792   bind(WHILE_HEAD_LABEL);
7793   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
7794   subl(result, cnt1);
7795   jccb(Assembler::notZero, POP_LABEL);
7796   increment(cnt2);
7797   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
7798 
7799   // Strings are equal up to min length.  Return the length difference.
7800   bind(LENGTH_DIFF_LABEL);
7801   pop(result);
7802   if (ae == StrIntrinsicNode::UU) {
7803     // Divide diff by 2 to get number of chars
7804     sarl(result, 1);
7805   }
7806   jmpb(DONE_LABEL);
7807 
7808 #ifdef _LP64
7809   if (VM_Version::supports_avx512vlbw()) {
7810 
7811     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
7812 
7813     kmovql(cnt1, k7);
7814     notq(cnt1);
7815     bsfq(cnt2, cnt1);
7816     if (ae != StrIntrinsicNode::LL) {
7817       // Divide diff by 2 to get number of chars
7818       sarl(cnt2, 1);
7819     }
7820     addq(result, cnt2);
7821     if (ae == StrIntrinsicNode::LL) {
7822       load_unsigned_byte(cnt1, Address(str2, result));
7823       load_unsigned_byte(result, Address(str1, result));
7824     } else if (ae == StrIntrinsicNode::UU) {
7825       load_unsigned_short(cnt1, Address(str2, result, scale));
7826       load_unsigned_short(result, Address(str1, result, scale));
7827     } else {
7828       load_unsigned_short(cnt1, Address(str2, result, scale2));
7829       load_unsigned_byte(result, Address(str1, result, scale1));
7830     }
7831     subl(result, cnt1);
7832     jmpb(POP_LABEL);
7833   }//if (VM_Version::supports_avx512vlbw())
7834 #endif // _LP64
7835 
7836   // Discard the stored length difference
7837   bind(POP_LABEL);
7838   pop(cnt1);
7839 
7840   // That's it
7841   bind(DONE_LABEL);
7842   if(ae == StrIntrinsicNode::UL) {
7843     negl(result);
7844   }
7845 
7846 }
7847 
7848 // Search for Non-ASCII character (Negative byte value) in a byte array,
7849 // return true if it has any and false otherwise.
7850 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
7851 //   @HotSpotIntrinsicCandidate
7852 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
7853 //     for (int i = off; i < off + len; i++) {
7854 //       if (ba[i] < 0) {
7855 //         return true;
7856 //       }
7857 //     }
7858 //     return false;
7859 //   }
7860 void MacroAssembler::has_negatives(Register ary1, Register len,
7861   Register result, Register tmp1,
7862   XMMRegister vec1, XMMRegister vec2) {
7863   // rsi: byte array
7864   // rcx: len
7865   // rax: result
7866   ShortBranchVerifier sbv(this);
7867   assert_different_registers(ary1, len, result, tmp1);
7868   assert_different_registers(vec1, vec2);
7869   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
7870 
7871   // len == 0
7872   testl(len, len);
7873   jcc(Assembler::zero, FALSE_LABEL);
7874 
7875   if ((UseAVX > 2) && // AVX512
7876     VM_Version::supports_avx512vlbw() &&
7877     VM_Version::supports_bmi2()) {
7878 
7879     set_vector_masking();  // opening of the stub context for programming mask registers
7880 
7881     Label test_64_loop, test_tail;
7882     Register tmp3_aliased = len;
7883 
7884     movl(tmp1, len);
7885     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
7886 
7887     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
7888     andl(len, ~(64 - 1));    // vector count (in chars)
7889     jccb(Assembler::zero, test_tail);
7890 
7891     lea(ary1, Address(ary1, len, Address::times_1));
7892     negptr(len);
7893 
7894     bind(test_64_loop);
7895     // Check whether our 64 elements of size byte contain negatives
7896     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
7897     kortestql(k2, k2);
7898     jcc(Assembler::notZero, TRUE_LABEL);
7899 
7900     addptr(len, 64);
7901     jccb(Assembler::notZero, test_64_loop);
7902 
7903 
7904     bind(test_tail);
7905     // bail out when there is nothing to be done
7906     testl(tmp1, -1);
7907     jcc(Assembler::zero, FALSE_LABEL);
7908 
7909     // Save k1
7910     kmovql(k3, k1);
7911 
7912     // ~(~0 << len) applied up to two times (for 32-bit scenario)
7913 #ifdef _LP64
7914     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
7915     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
7916     notq(tmp3_aliased);
7917     kmovql(k1, tmp3_aliased);
7918 #else
7919     Label k_init;
7920     jmp(k_init);
7921 
7922     // We could not read 64-bits from a general purpose register thus we move
7923     // data required to compose 64 1's to the instruction stream
7924     // We emit 64 byte wide series of elements from 0..63 which later on would
7925     // be used as a compare targets with tail count contained in tmp1 register.
7926     // Result would be a k1 register having tmp1 consecutive number or 1
7927     // counting from least significant bit.
7928     address tmp = pc();
7929     emit_int64(0x0706050403020100);
7930     emit_int64(0x0F0E0D0C0B0A0908);
7931     emit_int64(0x1716151413121110);
7932     emit_int64(0x1F1E1D1C1B1A1918);
7933     emit_int64(0x2726252423222120);
7934     emit_int64(0x2F2E2D2C2B2A2928);
7935     emit_int64(0x3736353433323130);
7936     emit_int64(0x3F3E3D3C3B3A3938);
7937 
7938     bind(k_init);
7939     lea(len, InternalAddress(tmp));
7940     // create mask to test for negative byte inside a vector
7941     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
7942     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
7943 
7944 #endif
7945     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
7946     ktestq(k2, k1);
7947     // Restore k1
7948     kmovql(k1, k3);
7949     jcc(Assembler::notZero, TRUE_LABEL);
7950 
7951     jmp(FALSE_LABEL);
7952 
7953     clear_vector_masking();   // closing of the stub context for programming mask registers
7954   } else {
7955     movl(result, len); // copy
7956 
7957     if (UseAVX == 2 && UseSSE >= 2) {
7958       // With AVX2, use 32-byte vector compare
7959       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7960 
7961       // Compare 32-byte vectors
7962       andl(result, 0x0000001f);  //   tail count (in bytes)
7963       andl(len, 0xffffffe0);   // vector count (in bytes)
7964       jccb(Assembler::zero, COMPARE_TAIL);
7965 
7966       lea(ary1, Address(ary1, len, Address::times_1));
7967       negptr(len);
7968 
7969       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
7970       movdl(vec2, tmp1);
7971       vpbroadcastd(vec2, vec2);
7972 
7973       bind(COMPARE_WIDE_VECTORS);
7974       vmovdqu(vec1, Address(ary1, len, Address::times_1));
7975       vptest(vec1, vec2);
7976       jccb(Assembler::notZero, TRUE_LABEL);
7977       addptr(len, 32);
7978       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7979 
7980       testl(result, result);
7981       jccb(Assembler::zero, FALSE_LABEL);
7982 
7983       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7984       vptest(vec1, vec2);
7985       jccb(Assembler::notZero, TRUE_LABEL);
7986       jmpb(FALSE_LABEL);
7987 
7988       bind(COMPARE_TAIL); // len is zero
7989       movl(len, result);
7990       // Fallthru to tail compare
7991     } else if (UseSSE42Intrinsics) {
7992       // With SSE4.2, use double quad vector compare
7993       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7994 
7995       // Compare 16-byte vectors
7996       andl(result, 0x0000000f);  //   tail count (in bytes)
7997       andl(len, 0xfffffff0);   // vector count (in bytes)
7998       jccb(Assembler::zero, COMPARE_TAIL);
7999 
8000       lea(ary1, Address(ary1, len, Address::times_1));
8001       negptr(len);
8002 
8003       movl(tmp1, 0x80808080);
8004       movdl(vec2, tmp1);
8005       pshufd(vec2, vec2, 0);
8006 
8007       bind(COMPARE_WIDE_VECTORS);
8008       movdqu(vec1, Address(ary1, len, Address::times_1));
8009       ptest(vec1, vec2);
8010       jccb(Assembler::notZero, TRUE_LABEL);
8011       addptr(len, 16);
8012       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8013 
8014       testl(result, result);
8015       jccb(Assembler::zero, FALSE_LABEL);
8016 
8017       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8018       ptest(vec1, vec2);
8019       jccb(Assembler::notZero, TRUE_LABEL);
8020       jmpb(FALSE_LABEL);
8021 
8022       bind(COMPARE_TAIL); // len is zero
8023       movl(len, result);
8024       // Fallthru to tail compare
8025     }
8026   }
8027   // Compare 4-byte vectors
8028   andl(len, 0xfffffffc); // vector count (in bytes)
8029   jccb(Assembler::zero, COMPARE_CHAR);
8030 
8031   lea(ary1, Address(ary1, len, Address::times_1));
8032   negptr(len);
8033 
8034   bind(COMPARE_VECTORS);
8035   movl(tmp1, Address(ary1, len, Address::times_1));
8036   andl(tmp1, 0x80808080);
8037   jccb(Assembler::notZero, TRUE_LABEL);
8038   addptr(len, 4);
8039   jcc(Assembler::notZero, COMPARE_VECTORS);
8040 
8041   // Compare trailing char (final 2 bytes), if any
8042   bind(COMPARE_CHAR);
8043   testl(result, 0x2);   // tail  char
8044   jccb(Assembler::zero, COMPARE_BYTE);
8045   load_unsigned_short(tmp1, Address(ary1, 0));
8046   andl(tmp1, 0x00008080);
8047   jccb(Assembler::notZero, TRUE_LABEL);
8048   subptr(result, 2);
8049   lea(ary1, Address(ary1, 2));
8050 
8051   bind(COMPARE_BYTE);
8052   testl(result, 0x1);   // tail  byte
8053   jccb(Assembler::zero, FALSE_LABEL);
8054   load_unsigned_byte(tmp1, Address(ary1, 0));
8055   andl(tmp1, 0x00000080);
8056   jccb(Assembler::notEqual, TRUE_LABEL);
8057   jmpb(FALSE_LABEL);
8058 
8059   bind(TRUE_LABEL);
8060   movl(result, 1);   // return true
8061   jmpb(DONE);
8062 
8063   bind(FALSE_LABEL);
8064   xorl(result, result); // return false
8065 
8066   // That's it
8067   bind(DONE);
8068   if (UseAVX >= 2 && UseSSE >= 2) {
8069     // clean upper bits of YMM registers
8070     vpxor(vec1, vec1);
8071     vpxor(vec2, vec2);
8072   }
8073 }
8074 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8075 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8076                                    Register limit, Register result, Register chr,
8077                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8078   ShortBranchVerifier sbv(this);
8079   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8080 
8081   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8082   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8083 
8084   if (is_array_equ) {
8085     // Check the input args
8086     cmpoop(ary1, ary2);
8087     jcc(Assembler::equal, TRUE_LABEL);
8088 
8089     // Need additional checks for arrays_equals.
8090     testptr(ary1, ary1);
8091     jcc(Assembler::zero, FALSE_LABEL);
8092     testptr(ary2, ary2);
8093     jcc(Assembler::zero, FALSE_LABEL);
8094 
8095     // Check the lengths
8096     movl(limit, Address(ary1, length_offset));
8097     cmpl(limit, Address(ary2, length_offset));
8098     jcc(Assembler::notEqual, FALSE_LABEL);
8099   }
8100 
8101   // count == 0
8102   testl(limit, limit);
8103   jcc(Assembler::zero, TRUE_LABEL);
8104 
8105   if (is_array_equ) {
8106     // Load array address
8107     lea(ary1, Address(ary1, base_offset));
8108     lea(ary2, Address(ary2, base_offset));
8109   }
8110 
8111   if (is_array_equ && is_char) {
8112     // arrays_equals when used for char[].
8113     shll(limit, 1);      // byte count != 0
8114   }
8115   movl(result, limit); // copy
8116 
8117   if (UseAVX >= 2) {
8118     // With AVX2, use 32-byte vector compare
8119     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8120 
8121     // Compare 32-byte vectors
8122     andl(result, 0x0000001f);  //   tail count (in bytes)
8123     andl(limit, 0xffffffe0);   // vector count (in bytes)
8124     jcc(Assembler::zero, COMPARE_TAIL);
8125 
8126     lea(ary1, Address(ary1, limit, Address::times_1));
8127     lea(ary2, Address(ary2, limit, Address::times_1));
8128     negptr(limit);
8129 
8130     bind(COMPARE_WIDE_VECTORS);
8131 
8132 #ifdef _LP64
8133     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8134       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8135 
8136       cmpl(limit, -64);
8137       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8138 
8139       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8140 
8141       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8142       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8143       kortestql(k7, k7);
8144       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8145       addptr(limit, 64);  // update since we already compared at this addr
8146       cmpl(limit, -64);
8147       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8148 
8149       // At this point we may still need to compare -limit+result bytes.
8150       // We could execute the next two instruction and just continue via non-wide path:
8151       //  cmpl(limit, 0);
8152       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8153       // But since we stopped at the points ary{1,2}+limit which are
8154       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8155       // (|limit| <= 32 and result < 32),
8156       // we may just compare the last 64 bytes.
8157       //
8158       addptr(result, -64);   // it is safe, bc we just came from this area
8159       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8160       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8161       kortestql(k7, k7);
8162       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8163 
8164       jmp(TRUE_LABEL);
8165 
8166       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8167 
8168     }//if (VM_Version::supports_avx512vlbw())
8169 #endif //_LP64
8170 
8171     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8172     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8173     vpxor(vec1, vec2);
8174 
8175     vptest(vec1, vec1);
8176     jcc(Assembler::notZero, FALSE_LABEL);
8177     addptr(limit, 32);
8178     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8179 
8180     testl(result, result);
8181     jcc(Assembler::zero, TRUE_LABEL);
8182 
8183     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8184     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8185     vpxor(vec1, vec2);
8186 
8187     vptest(vec1, vec1);
8188     jccb(Assembler::notZero, FALSE_LABEL);
8189     jmpb(TRUE_LABEL);
8190 
8191     bind(COMPARE_TAIL); // limit is zero
8192     movl(limit, result);
8193     // Fallthru to tail compare
8194   } else if (UseSSE42Intrinsics) {
8195     // With SSE4.2, use double quad vector compare
8196     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8197 
8198     // Compare 16-byte vectors
8199     andl(result, 0x0000000f);  //   tail count (in bytes)
8200     andl(limit, 0xfffffff0);   // vector count (in bytes)
8201     jcc(Assembler::zero, COMPARE_TAIL);
8202 
8203     lea(ary1, Address(ary1, limit, Address::times_1));
8204     lea(ary2, Address(ary2, limit, Address::times_1));
8205     negptr(limit);
8206 
8207     bind(COMPARE_WIDE_VECTORS);
8208     movdqu(vec1, Address(ary1, limit, Address::times_1));
8209     movdqu(vec2, Address(ary2, limit, Address::times_1));
8210     pxor(vec1, vec2);
8211 
8212     ptest(vec1, vec1);
8213     jcc(Assembler::notZero, FALSE_LABEL);
8214     addptr(limit, 16);
8215     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8216 
8217     testl(result, result);
8218     jcc(Assembler::zero, TRUE_LABEL);
8219 
8220     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8221     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8222     pxor(vec1, vec2);
8223 
8224     ptest(vec1, vec1);
8225     jccb(Assembler::notZero, FALSE_LABEL);
8226     jmpb(TRUE_LABEL);
8227 
8228     bind(COMPARE_TAIL); // limit is zero
8229     movl(limit, result);
8230     // Fallthru to tail compare
8231   }
8232 
8233   // Compare 4-byte vectors
8234   andl(limit, 0xfffffffc); // vector count (in bytes)
8235   jccb(Assembler::zero, COMPARE_CHAR);
8236 
8237   lea(ary1, Address(ary1, limit, Address::times_1));
8238   lea(ary2, Address(ary2, limit, Address::times_1));
8239   negptr(limit);
8240 
8241   bind(COMPARE_VECTORS);
8242   movl(chr, Address(ary1, limit, Address::times_1));
8243   cmpl(chr, Address(ary2, limit, Address::times_1));
8244   jccb(Assembler::notEqual, FALSE_LABEL);
8245   addptr(limit, 4);
8246   jcc(Assembler::notZero, COMPARE_VECTORS);
8247 
8248   // Compare trailing char (final 2 bytes), if any
8249   bind(COMPARE_CHAR);
8250   testl(result, 0x2);   // tail  char
8251   jccb(Assembler::zero, COMPARE_BYTE);
8252   load_unsigned_short(chr, Address(ary1, 0));
8253   load_unsigned_short(limit, Address(ary2, 0));
8254   cmpl(chr, limit);
8255   jccb(Assembler::notEqual, FALSE_LABEL);
8256 
8257   if (is_array_equ && is_char) {
8258     bind(COMPARE_BYTE);
8259   } else {
8260     lea(ary1, Address(ary1, 2));
8261     lea(ary2, Address(ary2, 2));
8262 
8263     bind(COMPARE_BYTE);
8264     testl(result, 0x1);   // tail  byte
8265     jccb(Assembler::zero, TRUE_LABEL);
8266     load_unsigned_byte(chr, Address(ary1, 0));
8267     load_unsigned_byte(limit, Address(ary2, 0));
8268     cmpl(chr, limit);
8269     jccb(Assembler::notEqual, FALSE_LABEL);
8270   }
8271   bind(TRUE_LABEL);
8272   movl(result, 1);   // return true
8273   jmpb(DONE);
8274 
8275   bind(FALSE_LABEL);
8276   xorl(result, result); // return false
8277 
8278   // That's it
8279   bind(DONE);
8280   if (UseAVX >= 2) {
8281     // clean upper bits of YMM registers
8282     vpxor(vec1, vec1);
8283     vpxor(vec2, vec2);
8284   }
8285 }
8286 
8287 #endif
8288 
8289 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8290                                    Register to, Register value, Register count,
8291                                    Register rtmp, XMMRegister xtmp) {
8292   ShortBranchVerifier sbv(this);
8293   assert_different_registers(to, value, count, rtmp);
8294   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8295   Label L_fill_2_bytes, L_fill_4_bytes;
8296 
8297   int shift = -1;
8298   switch (t) {
8299     case T_BYTE:
8300       shift = 2;
8301       break;
8302     case T_SHORT:
8303       shift = 1;
8304       break;
8305     case T_INT:
8306       shift = 0;
8307       break;
8308     default: ShouldNotReachHere();
8309   }
8310 
8311   if (t == T_BYTE) {
8312     andl(value, 0xff);
8313     movl(rtmp, value);
8314     shll(rtmp, 8);
8315     orl(value, rtmp);
8316   }
8317   if (t == T_SHORT) {
8318     andl(value, 0xffff);
8319   }
8320   if (t == T_BYTE || t == T_SHORT) {
8321     movl(rtmp, value);
8322     shll(rtmp, 16);
8323     orl(value, rtmp);
8324   }
8325 
8326   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8327   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8328   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8329     // align source address at 4 bytes address boundary
8330     if (t == T_BYTE) {
8331       // One byte misalignment happens only for byte arrays
8332       testptr(to, 1);
8333       jccb(Assembler::zero, L_skip_align1);
8334       movb(Address(to, 0), value);
8335       increment(to);
8336       decrement(count);
8337       BIND(L_skip_align1);
8338     }
8339     // Two bytes misalignment happens only for byte and short (char) arrays
8340     testptr(to, 2);
8341     jccb(Assembler::zero, L_skip_align2);
8342     movw(Address(to, 0), value);
8343     addptr(to, 2);
8344     subl(count, 1<<(shift-1));
8345     BIND(L_skip_align2);
8346   }
8347   if (UseSSE < 2) {
8348     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8349     // Fill 32-byte chunks
8350     subl(count, 8 << shift);
8351     jcc(Assembler::less, L_check_fill_8_bytes);
8352     align(16);
8353 
8354     BIND(L_fill_32_bytes_loop);
8355 
8356     for (int i = 0; i < 32; i += 4) {
8357       movl(Address(to, i), value);
8358     }
8359 
8360     addptr(to, 32);
8361     subl(count, 8 << shift);
8362     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8363     BIND(L_check_fill_8_bytes);
8364     addl(count, 8 << shift);
8365     jccb(Assembler::zero, L_exit);
8366     jmpb(L_fill_8_bytes);
8367 
8368     //
8369     // length is too short, just fill qwords
8370     //
8371     BIND(L_fill_8_bytes_loop);
8372     movl(Address(to, 0), value);
8373     movl(Address(to, 4), value);
8374     addptr(to, 8);
8375     BIND(L_fill_8_bytes);
8376     subl(count, 1 << (shift + 1));
8377     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8378     // fall through to fill 4 bytes
8379   } else {
8380     Label L_fill_32_bytes;
8381     if (!UseUnalignedLoadStores) {
8382       // align to 8 bytes, we know we are 4 byte aligned to start
8383       testptr(to, 4);
8384       jccb(Assembler::zero, L_fill_32_bytes);
8385       movl(Address(to, 0), value);
8386       addptr(to, 4);
8387       subl(count, 1<<shift);
8388     }
8389     BIND(L_fill_32_bytes);
8390     {
8391       assert( UseSSE >= 2, "supported cpu only" );
8392       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8393       if (UseAVX > 2) {
8394         movl(rtmp, 0xffff);
8395         kmovwl(k1, rtmp);
8396       }
8397       movdl(xtmp, value);
8398       if (UseAVX > 2 && UseUnalignedLoadStores) {
8399         // Fill 64-byte chunks
8400         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8401         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8402 
8403         subl(count, 16 << shift);
8404         jcc(Assembler::less, L_check_fill_32_bytes);
8405         align(16);
8406 
8407         BIND(L_fill_64_bytes_loop);
8408         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8409         addptr(to, 64);
8410         subl(count, 16 << shift);
8411         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8412 
8413         BIND(L_check_fill_32_bytes);
8414         addl(count, 8 << shift);
8415         jccb(Assembler::less, L_check_fill_8_bytes);
8416         vmovdqu(Address(to, 0), xtmp);
8417         addptr(to, 32);
8418         subl(count, 8 << shift);
8419 
8420         BIND(L_check_fill_8_bytes);
8421       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8422         // Fill 64-byte chunks
8423         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8424         vpbroadcastd(xtmp, xtmp);
8425 
8426         subl(count, 16 << shift);
8427         jcc(Assembler::less, L_check_fill_32_bytes);
8428         align(16);
8429 
8430         BIND(L_fill_64_bytes_loop);
8431         vmovdqu(Address(to, 0), xtmp);
8432         vmovdqu(Address(to, 32), xtmp);
8433         addptr(to, 64);
8434         subl(count, 16 << shift);
8435         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8436 
8437         BIND(L_check_fill_32_bytes);
8438         addl(count, 8 << shift);
8439         jccb(Assembler::less, L_check_fill_8_bytes);
8440         vmovdqu(Address(to, 0), xtmp);
8441         addptr(to, 32);
8442         subl(count, 8 << shift);
8443 
8444         BIND(L_check_fill_8_bytes);
8445         // clean upper bits of YMM registers
8446         movdl(xtmp, value);
8447         pshufd(xtmp, xtmp, 0);
8448       } else {
8449         // Fill 32-byte chunks
8450         pshufd(xtmp, xtmp, 0);
8451 
8452         subl(count, 8 << shift);
8453         jcc(Assembler::less, L_check_fill_8_bytes);
8454         align(16);
8455 
8456         BIND(L_fill_32_bytes_loop);
8457 
8458         if (UseUnalignedLoadStores) {
8459           movdqu(Address(to, 0), xtmp);
8460           movdqu(Address(to, 16), xtmp);
8461         } else {
8462           movq(Address(to, 0), xtmp);
8463           movq(Address(to, 8), xtmp);
8464           movq(Address(to, 16), xtmp);
8465           movq(Address(to, 24), xtmp);
8466         }
8467 
8468         addptr(to, 32);
8469         subl(count, 8 << shift);
8470         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8471 
8472         BIND(L_check_fill_8_bytes);
8473       }
8474       addl(count, 8 << shift);
8475       jccb(Assembler::zero, L_exit);
8476       jmpb(L_fill_8_bytes);
8477 
8478       //
8479       // length is too short, just fill qwords
8480       //
8481       BIND(L_fill_8_bytes_loop);
8482       movq(Address(to, 0), xtmp);
8483       addptr(to, 8);
8484       BIND(L_fill_8_bytes);
8485       subl(count, 1 << (shift + 1));
8486       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8487     }
8488   }
8489   // fill trailing 4 bytes
8490   BIND(L_fill_4_bytes);
8491   testl(count, 1<<shift);
8492   jccb(Assembler::zero, L_fill_2_bytes);
8493   movl(Address(to, 0), value);
8494   if (t == T_BYTE || t == T_SHORT) {
8495     addptr(to, 4);
8496     BIND(L_fill_2_bytes);
8497     // fill trailing 2 bytes
8498     testl(count, 1<<(shift-1));
8499     jccb(Assembler::zero, L_fill_byte);
8500     movw(Address(to, 0), value);
8501     if (t == T_BYTE) {
8502       addptr(to, 2);
8503       BIND(L_fill_byte);
8504       // fill trailing byte
8505       testl(count, 1);
8506       jccb(Assembler::zero, L_exit);
8507       movb(Address(to, 0), value);
8508     } else {
8509       BIND(L_fill_byte);
8510     }
8511   } else {
8512     BIND(L_fill_2_bytes);
8513   }
8514   BIND(L_exit);
8515 }
8516 
8517 // encode char[] to byte[] in ISO_8859_1
8518    //@HotSpotIntrinsicCandidate
8519    //private static int implEncodeISOArray(byte[] sa, int sp,
8520    //byte[] da, int dp, int len) {
8521    //  int i = 0;
8522    //  for (; i < len; i++) {
8523    //    char c = StringUTF16.getChar(sa, sp++);
8524    //    if (c > '\u00FF')
8525    //      break;
8526    //    da[dp++] = (byte)c;
8527    //  }
8528    //  return i;
8529    //}
8530 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8531   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8532   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8533   Register tmp5, Register result) {
8534 
8535   // rsi: src
8536   // rdi: dst
8537   // rdx: len
8538   // rcx: tmp5
8539   // rax: result
8540   ShortBranchVerifier sbv(this);
8541   assert_different_registers(src, dst, len, tmp5, result);
8542   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8543 
8544   // set result
8545   xorl(result, result);
8546   // check for zero length
8547   testl(len, len);
8548   jcc(Assembler::zero, L_done);
8549 
8550   movl(result, len);
8551 
8552   // Setup pointers
8553   lea(src, Address(src, len, Address::times_2)); // char[]
8554   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8555   negptr(len);
8556 
8557   if (UseSSE42Intrinsics || UseAVX >= 2) {
8558     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8559     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8560 
8561     if (UseAVX >= 2) {
8562       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8563       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8564       movdl(tmp1Reg, tmp5);
8565       vpbroadcastd(tmp1Reg, tmp1Reg);
8566       jmp(L_chars_32_check);
8567 
8568       bind(L_copy_32_chars);
8569       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8570       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8571       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8572       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8573       jccb(Assembler::notZero, L_copy_32_chars_exit);
8574       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8575       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8576       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8577 
8578       bind(L_chars_32_check);
8579       addptr(len, 32);
8580       jcc(Assembler::lessEqual, L_copy_32_chars);
8581 
8582       bind(L_copy_32_chars_exit);
8583       subptr(len, 16);
8584       jccb(Assembler::greater, L_copy_16_chars_exit);
8585 
8586     } else if (UseSSE42Intrinsics) {
8587       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8588       movdl(tmp1Reg, tmp5);
8589       pshufd(tmp1Reg, tmp1Reg, 0);
8590       jmpb(L_chars_16_check);
8591     }
8592 
8593     bind(L_copy_16_chars);
8594     if (UseAVX >= 2) {
8595       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8596       vptest(tmp2Reg, tmp1Reg);
8597       jcc(Assembler::notZero, L_copy_16_chars_exit);
8598       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8599       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8600     } else {
8601       if (UseAVX > 0) {
8602         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8603         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8604         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8605       } else {
8606         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8607         por(tmp2Reg, tmp3Reg);
8608         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8609         por(tmp2Reg, tmp4Reg);
8610       }
8611       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8612       jccb(Assembler::notZero, L_copy_16_chars_exit);
8613       packuswb(tmp3Reg, tmp4Reg);
8614     }
8615     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8616 
8617     bind(L_chars_16_check);
8618     addptr(len, 16);
8619     jcc(Assembler::lessEqual, L_copy_16_chars);
8620 
8621     bind(L_copy_16_chars_exit);
8622     if (UseAVX >= 2) {
8623       // clean upper bits of YMM registers
8624       vpxor(tmp2Reg, tmp2Reg);
8625       vpxor(tmp3Reg, tmp3Reg);
8626       vpxor(tmp4Reg, tmp4Reg);
8627       movdl(tmp1Reg, tmp5);
8628       pshufd(tmp1Reg, tmp1Reg, 0);
8629     }
8630     subptr(len, 8);
8631     jccb(Assembler::greater, L_copy_8_chars_exit);
8632 
8633     bind(L_copy_8_chars);
8634     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8635     ptest(tmp3Reg, tmp1Reg);
8636     jccb(Assembler::notZero, L_copy_8_chars_exit);
8637     packuswb(tmp3Reg, tmp1Reg);
8638     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8639     addptr(len, 8);
8640     jccb(Assembler::lessEqual, L_copy_8_chars);
8641 
8642     bind(L_copy_8_chars_exit);
8643     subptr(len, 8);
8644     jccb(Assembler::zero, L_done);
8645   }
8646 
8647   bind(L_copy_1_char);
8648   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8649   testl(tmp5, 0xff00);      // check if Unicode char
8650   jccb(Assembler::notZero, L_copy_1_char_exit);
8651   movb(Address(dst, len, Address::times_1, 0), tmp5);
8652   addptr(len, 1);
8653   jccb(Assembler::less, L_copy_1_char);
8654 
8655   bind(L_copy_1_char_exit);
8656   addptr(result, len); // len is negative count of not processed elements
8657 
8658   bind(L_done);
8659 }
8660 
8661 #ifdef _LP64
8662 /**
8663  * Helper for multiply_to_len().
8664  */
8665 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8666   addq(dest_lo, src1);
8667   adcq(dest_hi, 0);
8668   addq(dest_lo, src2);
8669   adcq(dest_hi, 0);
8670 }
8671 
8672 /**
8673  * Multiply 64 bit by 64 bit first loop.
8674  */
8675 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8676                                            Register y, Register y_idx, Register z,
8677                                            Register carry, Register product,
8678                                            Register idx, Register kdx) {
8679   //
8680   //  jlong carry, x[], y[], z[];
8681   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8682   //    huge_128 product = y[idx] * x[xstart] + carry;
8683   //    z[kdx] = (jlong)product;
8684   //    carry  = (jlong)(product >>> 64);
8685   //  }
8686   //  z[xstart] = carry;
8687   //
8688 
8689   Label L_first_loop, L_first_loop_exit;
8690   Label L_one_x, L_one_y, L_multiply;
8691 
8692   decrementl(xstart);
8693   jcc(Assembler::negative, L_one_x);
8694 
8695   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8696   rorq(x_xstart, 32); // convert big-endian to little-endian
8697 
8698   bind(L_first_loop);
8699   decrementl(idx);
8700   jcc(Assembler::negative, L_first_loop_exit);
8701   decrementl(idx);
8702   jcc(Assembler::negative, L_one_y);
8703   movq(y_idx, Address(y, idx, Address::times_4,  0));
8704   rorq(y_idx, 32); // convert big-endian to little-endian
8705   bind(L_multiply);
8706   movq(product, x_xstart);
8707   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8708   addq(product, carry);
8709   adcq(rdx, 0);
8710   subl(kdx, 2);
8711   movl(Address(z, kdx, Address::times_4,  4), product);
8712   shrq(product, 32);
8713   movl(Address(z, kdx, Address::times_4,  0), product);
8714   movq(carry, rdx);
8715   jmp(L_first_loop);
8716 
8717   bind(L_one_y);
8718   movl(y_idx, Address(y,  0));
8719   jmp(L_multiply);
8720 
8721   bind(L_one_x);
8722   movl(x_xstart, Address(x,  0));
8723   jmp(L_first_loop);
8724 
8725   bind(L_first_loop_exit);
8726 }
8727 
8728 /**
8729  * Multiply 64 bit by 64 bit and add 128 bit.
8730  */
8731 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8732                                             Register yz_idx, Register idx,
8733                                             Register carry, Register product, int offset) {
8734   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8735   //     z[kdx] = (jlong)product;
8736 
8737   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8738   rorq(yz_idx, 32); // convert big-endian to little-endian
8739   movq(product, x_xstart);
8740   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8741   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8742   rorq(yz_idx, 32); // convert big-endian to little-endian
8743 
8744   add2_with_carry(rdx, product, carry, yz_idx);
8745 
8746   movl(Address(z, idx, Address::times_4,  offset+4), product);
8747   shrq(product, 32);
8748   movl(Address(z, idx, Address::times_4,  offset), product);
8749 
8750 }
8751 
8752 /**
8753  * Multiply 128 bit by 128 bit. Unrolled inner loop.
8754  */
8755 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
8756                                              Register yz_idx, Register idx, Register jdx,
8757                                              Register carry, Register product,
8758                                              Register carry2) {
8759   //   jlong carry, x[], y[], z[];
8760   //   int kdx = ystart+1;
8761   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8762   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
8763   //     z[kdx+idx+1] = (jlong)product;
8764   //     jlong carry2  = (jlong)(product >>> 64);
8765   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
8766   //     z[kdx+idx] = (jlong)product;
8767   //     carry  = (jlong)(product >>> 64);
8768   //   }
8769   //   idx += 2;
8770   //   if (idx > 0) {
8771   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
8772   //     z[kdx+idx] = (jlong)product;
8773   //     carry  = (jlong)(product >>> 64);
8774   //   }
8775   //
8776 
8777   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8778 
8779   movl(jdx, idx);
8780   andl(jdx, 0xFFFFFFFC);
8781   shrl(jdx, 2);
8782 
8783   bind(L_third_loop);
8784   subl(jdx, 1);
8785   jcc(Assembler::negative, L_third_loop_exit);
8786   subl(idx, 4);
8787 
8788   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
8789   movq(carry2, rdx);
8790 
8791   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
8792   movq(carry, rdx);
8793   jmp(L_third_loop);
8794 
8795   bind (L_third_loop_exit);
8796 
8797   andl (idx, 0x3);
8798   jcc(Assembler::zero, L_post_third_loop_done);
8799 
8800   Label L_check_1;
8801   subl(idx, 2);
8802   jcc(Assembler::negative, L_check_1);
8803 
8804   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
8805   movq(carry, rdx);
8806 
8807   bind (L_check_1);
8808   addl (idx, 0x2);
8809   andl (idx, 0x1);
8810   subl(idx, 1);
8811   jcc(Assembler::negative, L_post_third_loop_done);
8812 
8813   movl(yz_idx, Address(y, idx, Address::times_4,  0));
8814   movq(product, x_xstart);
8815   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
8816   movl(yz_idx, Address(z, idx, Address::times_4,  0));
8817 
8818   add2_with_carry(rdx, product, yz_idx, carry);
8819 
8820   movl(Address(z, idx, Address::times_4,  0), product);
8821   shrq(product, 32);
8822 
8823   shlq(rdx, 32);
8824   orq(product, rdx);
8825   movq(carry, product);
8826 
8827   bind(L_post_third_loop_done);
8828 }
8829 
8830 /**
8831  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
8832  *
8833  */
8834 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
8835                                                   Register carry, Register carry2,
8836                                                   Register idx, Register jdx,
8837                                                   Register yz_idx1, Register yz_idx2,
8838                                                   Register tmp, Register tmp3, Register tmp4) {
8839   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
8840 
8841   //   jlong carry, x[], y[], z[];
8842   //   int kdx = ystart+1;
8843   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8844   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
8845   //     jlong carry2  = (jlong)(tmp3 >>> 64);
8846   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
8847   //     carry  = (jlong)(tmp4 >>> 64);
8848   //     z[kdx+idx+1] = (jlong)tmp3;
8849   //     z[kdx+idx] = (jlong)tmp4;
8850   //   }
8851   //   idx += 2;
8852   //   if (idx > 0) {
8853   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
8854   //     z[kdx+idx] = (jlong)yz_idx1;
8855   //     carry  = (jlong)(yz_idx1 >>> 64);
8856   //   }
8857   //
8858 
8859   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8860 
8861   movl(jdx, idx);
8862   andl(jdx, 0xFFFFFFFC);
8863   shrl(jdx, 2);
8864 
8865   bind(L_third_loop);
8866   subl(jdx, 1);
8867   jcc(Assembler::negative, L_third_loop_exit);
8868   subl(idx, 4);
8869 
8870   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
8871   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
8872   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
8873   rorxq(yz_idx2, yz_idx2, 32);
8874 
8875   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
8876   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
8877 
8878   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
8879   rorxq(yz_idx1, yz_idx1, 32);
8880   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8881   rorxq(yz_idx2, yz_idx2, 32);
8882 
8883   if (VM_Version::supports_adx()) {
8884     adcxq(tmp3, carry);
8885     adoxq(tmp3, yz_idx1);
8886 
8887     adcxq(tmp4, tmp);
8888     adoxq(tmp4, yz_idx2);
8889 
8890     movl(carry, 0); // does not affect flags
8891     adcxq(carry2, carry);
8892     adoxq(carry2, carry);
8893   } else {
8894     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
8895     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
8896   }
8897   movq(carry, carry2);
8898 
8899   movl(Address(z, idx, Address::times_4, 12), tmp3);
8900   shrq(tmp3, 32);
8901   movl(Address(z, idx, Address::times_4,  8), tmp3);
8902 
8903   movl(Address(z, idx, Address::times_4,  4), tmp4);
8904   shrq(tmp4, 32);
8905   movl(Address(z, idx, Address::times_4,  0), tmp4);
8906 
8907   jmp(L_third_loop);
8908 
8909   bind (L_third_loop_exit);
8910 
8911   andl (idx, 0x3);
8912   jcc(Assembler::zero, L_post_third_loop_done);
8913 
8914   Label L_check_1;
8915   subl(idx, 2);
8916   jcc(Assembler::negative, L_check_1);
8917 
8918   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
8919   rorxq(yz_idx1, yz_idx1, 32);
8920   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
8921   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8922   rorxq(yz_idx2, yz_idx2, 32);
8923 
8924   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
8925 
8926   movl(Address(z, idx, Address::times_4,  4), tmp3);
8927   shrq(tmp3, 32);
8928   movl(Address(z, idx, Address::times_4,  0), tmp3);
8929   movq(carry, tmp4);
8930 
8931   bind (L_check_1);
8932   addl (idx, 0x2);
8933   andl (idx, 0x1);
8934   subl(idx, 1);
8935   jcc(Assembler::negative, L_post_third_loop_done);
8936   movl(tmp4, Address(y, idx, Address::times_4,  0));
8937   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
8938   movl(tmp4, Address(z, idx, Address::times_4,  0));
8939 
8940   add2_with_carry(carry2, tmp3, tmp4, carry);
8941 
8942   movl(Address(z, idx, Address::times_4,  0), tmp3);
8943   shrq(tmp3, 32);
8944 
8945   shlq(carry2, 32);
8946   orq(tmp3, carry2);
8947   movq(carry, tmp3);
8948 
8949   bind(L_post_third_loop_done);
8950 }
8951 
8952 /**
8953  * Code for BigInteger::multiplyToLen() instrinsic.
8954  *
8955  * rdi: x
8956  * rax: xlen
8957  * rsi: y
8958  * rcx: ylen
8959  * r8:  z
8960  * r11: zlen
8961  * r12: tmp1
8962  * r13: tmp2
8963  * r14: tmp3
8964  * r15: tmp4
8965  * rbx: tmp5
8966  *
8967  */
8968 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
8969                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
8970   ShortBranchVerifier sbv(this);
8971   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
8972 
8973   push(tmp1);
8974   push(tmp2);
8975   push(tmp3);
8976   push(tmp4);
8977   push(tmp5);
8978 
8979   push(xlen);
8980   push(zlen);
8981 
8982   const Register idx = tmp1;
8983   const Register kdx = tmp2;
8984   const Register xstart = tmp3;
8985 
8986   const Register y_idx = tmp4;
8987   const Register carry = tmp5;
8988   const Register product  = xlen;
8989   const Register x_xstart = zlen;  // reuse register
8990 
8991   // First Loop.
8992   //
8993   //  final static long LONG_MASK = 0xffffffffL;
8994   //  int xstart = xlen - 1;
8995   //  int ystart = ylen - 1;
8996   //  long carry = 0;
8997   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8998   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
8999   //    z[kdx] = (int)product;
9000   //    carry = product >>> 32;
9001   //  }
9002   //  z[xstart] = (int)carry;
9003   //
9004 
9005   movl(idx, ylen);      // idx = ylen;
9006   movl(kdx, zlen);      // kdx = xlen+ylen;
9007   xorq(carry, carry);   // carry = 0;
9008 
9009   Label L_done;
9010 
9011   movl(xstart, xlen);
9012   decrementl(xstart);
9013   jcc(Assembler::negative, L_done);
9014 
9015   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9016 
9017   Label L_second_loop;
9018   testl(kdx, kdx);
9019   jcc(Assembler::zero, L_second_loop);
9020 
9021   Label L_carry;
9022   subl(kdx, 1);
9023   jcc(Assembler::zero, L_carry);
9024 
9025   movl(Address(z, kdx, Address::times_4,  0), carry);
9026   shrq(carry, 32);
9027   subl(kdx, 1);
9028 
9029   bind(L_carry);
9030   movl(Address(z, kdx, Address::times_4,  0), carry);
9031 
9032   // Second and third (nested) loops.
9033   //
9034   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9035   //   carry = 0;
9036   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9037   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9038   //                    (z[k] & LONG_MASK) + carry;
9039   //     z[k] = (int)product;
9040   //     carry = product >>> 32;
9041   //   }
9042   //   z[i] = (int)carry;
9043   // }
9044   //
9045   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9046 
9047   const Register jdx = tmp1;
9048 
9049   bind(L_second_loop);
9050   xorl(carry, carry);    // carry = 0;
9051   movl(jdx, ylen);       // j = ystart+1
9052 
9053   subl(xstart, 1);       // i = xstart-1;
9054   jcc(Assembler::negative, L_done);
9055 
9056   push (z);
9057 
9058   Label L_last_x;
9059   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9060   subl(xstart, 1);       // i = xstart-1;
9061   jcc(Assembler::negative, L_last_x);
9062 
9063   if (UseBMI2Instructions) {
9064     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9065     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9066   } else {
9067     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9068     rorq(x_xstart, 32);  // convert big-endian to little-endian
9069   }
9070 
9071   Label L_third_loop_prologue;
9072   bind(L_third_loop_prologue);
9073 
9074   push (x);
9075   push (xstart);
9076   push (ylen);
9077 
9078 
9079   if (UseBMI2Instructions) {
9080     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9081   } else { // !UseBMI2Instructions
9082     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9083   }
9084 
9085   pop(ylen);
9086   pop(xlen);
9087   pop(x);
9088   pop(z);
9089 
9090   movl(tmp3, xlen);
9091   addl(tmp3, 1);
9092   movl(Address(z, tmp3, Address::times_4,  0), carry);
9093   subl(tmp3, 1);
9094   jccb(Assembler::negative, L_done);
9095 
9096   shrq(carry, 32);
9097   movl(Address(z, tmp3, Address::times_4,  0), carry);
9098   jmp(L_second_loop);
9099 
9100   // Next infrequent code is moved outside loops.
9101   bind(L_last_x);
9102   if (UseBMI2Instructions) {
9103     movl(rdx, Address(x,  0));
9104   } else {
9105     movl(x_xstart, Address(x,  0));
9106   }
9107   jmp(L_third_loop_prologue);
9108 
9109   bind(L_done);
9110 
9111   pop(zlen);
9112   pop(xlen);
9113 
9114   pop(tmp5);
9115   pop(tmp4);
9116   pop(tmp3);
9117   pop(tmp2);
9118   pop(tmp1);
9119 }
9120 
9121 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9122   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9123   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9124   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9125   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9126   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9127   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9128   Label SAME_TILL_END, DONE;
9129   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9130 
9131   //scale is in rcx in both Win64 and Unix
9132   ShortBranchVerifier sbv(this);
9133 
9134   shlq(length);
9135   xorq(result, result);
9136 
9137   if ((UseAVX > 2) &&
9138       VM_Version::supports_avx512vlbw()) {
9139     set_vector_masking();  // opening of the stub context for programming mask registers
9140     cmpq(length, 64);
9141     jcc(Assembler::less, VECTOR32_TAIL);
9142     movq(tmp1, length);
9143     andq(tmp1, 0x3F);      // tail count
9144     andq(length, ~(0x3F)); //vector count
9145 
9146     bind(VECTOR64_LOOP);
9147     // AVX512 code to compare 64 byte vectors.
9148     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9149     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9150     kortestql(k7, k7);
9151     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9152     addq(result, 64);
9153     subq(length, 64);
9154     jccb(Assembler::notZero, VECTOR64_LOOP);
9155 
9156     //bind(VECTOR64_TAIL);
9157     testq(tmp1, tmp1);
9158     jcc(Assembler::zero, SAME_TILL_END);
9159 
9160     bind(VECTOR64_TAIL);
9161     // AVX512 code to compare upto 63 byte vectors.
9162     // Save k1
9163     kmovql(k3, k1);
9164     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9165     shlxq(tmp2, tmp2, tmp1);
9166     notq(tmp2);
9167     kmovql(k1, tmp2);
9168 
9169     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9170     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9171 
9172     ktestql(k7, k1);
9173     // Restore k1
9174     kmovql(k1, k3);
9175     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9176 
9177     bind(VECTOR64_NOT_EQUAL);
9178     kmovql(tmp1, k7);
9179     notq(tmp1);
9180     tzcntq(tmp1, tmp1);
9181     addq(result, tmp1);
9182     shrq(result);
9183     jmp(DONE);
9184     bind(VECTOR32_TAIL);
9185     clear_vector_masking();   // closing of the stub context for programming mask registers
9186   }
9187 
9188   cmpq(length, 8);
9189   jcc(Assembler::equal, VECTOR8_LOOP);
9190   jcc(Assembler::less, VECTOR4_TAIL);
9191 
9192   if (UseAVX >= 2) {
9193 
9194     cmpq(length, 16);
9195     jcc(Assembler::equal, VECTOR16_LOOP);
9196     jcc(Assembler::less, VECTOR8_LOOP);
9197 
9198     cmpq(length, 32);
9199     jccb(Assembler::less, VECTOR16_TAIL);
9200 
9201     subq(length, 32);
9202     bind(VECTOR32_LOOP);
9203     vmovdqu(rymm0, Address(obja, result));
9204     vmovdqu(rymm1, Address(objb, result));
9205     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9206     vptest(rymm2, rymm2);
9207     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9208     addq(result, 32);
9209     subq(length, 32);
9210     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9211     addq(length, 32);
9212     jcc(Assembler::equal, SAME_TILL_END);
9213     //falling through if less than 32 bytes left //close the branch here.
9214 
9215     bind(VECTOR16_TAIL);
9216     cmpq(length, 16);
9217     jccb(Assembler::less, VECTOR8_TAIL);
9218     bind(VECTOR16_LOOP);
9219     movdqu(rymm0, Address(obja, result));
9220     movdqu(rymm1, Address(objb, result));
9221     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9222     ptest(rymm2, rymm2);
9223     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9224     addq(result, 16);
9225     subq(length, 16);
9226     jcc(Assembler::equal, SAME_TILL_END);
9227     //falling through if less than 16 bytes left
9228   } else {//regular intrinsics
9229 
9230     cmpq(length, 16);
9231     jccb(Assembler::less, VECTOR8_TAIL);
9232 
9233     subq(length, 16);
9234     bind(VECTOR16_LOOP);
9235     movdqu(rymm0, Address(obja, result));
9236     movdqu(rymm1, Address(objb, result));
9237     pxor(rymm0, rymm1);
9238     ptest(rymm0, rymm0);
9239     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9240     addq(result, 16);
9241     subq(length, 16);
9242     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9243     addq(length, 16);
9244     jcc(Assembler::equal, SAME_TILL_END);
9245     //falling through if less than 16 bytes left
9246   }
9247 
9248   bind(VECTOR8_TAIL);
9249   cmpq(length, 8);
9250   jccb(Assembler::less, VECTOR4_TAIL);
9251   bind(VECTOR8_LOOP);
9252   movq(tmp1, Address(obja, result));
9253   movq(tmp2, Address(objb, result));
9254   xorq(tmp1, tmp2);
9255   testq(tmp1, tmp1);
9256   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9257   addq(result, 8);
9258   subq(length, 8);
9259   jcc(Assembler::equal, SAME_TILL_END);
9260   //falling through if less than 8 bytes left
9261 
9262   bind(VECTOR4_TAIL);
9263   cmpq(length, 4);
9264   jccb(Assembler::less, BYTES_TAIL);
9265   bind(VECTOR4_LOOP);
9266   movl(tmp1, Address(obja, result));
9267   xorl(tmp1, Address(objb, result));
9268   testl(tmp1, tmp1);
9269   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9270   addq(result, 4);
9271   subq(length, 4);
9272   jcc(Assembler::equal, SAME_TILL_END);
9273   //falling through if less than 4 bytes left
9274 
9275   bind(BYTES_TAIL);
9276   bind(BYTES_LOOP);
9277   load_unsigned_byte(tmp1, Address(obja, result));
9278   load_unsigned_byte(tmp2, Address(objb, result));
9279   xorl(tmp1, tmp2);
9280   testl(tmp1, tmp1);
9281   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9282   decq(length);
9283   jccb(Assembler::zero, SAME_TILL_END);
9284   incq(result);
9285   load_unsigned_byte(tmp1, Address(obja, result));
9286   load_unsigned_byte(tmp2, Address(objb, result));
9287   xorl(tmp1, tmp2);
9288   testl(tmp1, tmp1);
9289   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9290   decq(length);
9291   jccb(Assembler::zero, SAME_TILL_END);
9292   incq(result);
9293   load_unsigned_byte(tmp1, Address(obja, result));
9294   load_unsigned_byte(tmp2, Address(objb, result));
9295   xorl(tmp1, tmp2);
9296   testl(tmp1, tmp1);
9297   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9298   jmpb(SAME_TILL_END);
9299 
9300   if (UseAVX >= 2) {
9301     bind(VECTOR32_NOT_EQUAL);
9302     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9303     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9304     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9305     vpmovmskb(tmp1, rymm0);
9306     bsfq(tmp1, tmp1);
9307     addq(result, tmp1);
9308     shrq(result);
9309     jmpb(DONE);
9310   }
9311 
9312   bind(VECTOR16_NOT_EQUAL);
9313   if (UseAVX >= 2) {
9314     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9315     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9316     pxor(rymm0, rymm2);
9317   } else {
9318     pcmpeqb(rymm2, rymm2);
9319     pxor(rymm0, rymm1);
9320     pcmpeqb(rymm0, rymm1);
9321     pxor(rymm0, rymm2);
9322   }
9323   pmovmskb(tmp1, rymm0);
9324   bsfq(tmp1, tmp1);
9325   addq(result, tmp1);
9326   shrq(result);
9327   jmpb(DONE);
9328 
9329   bind(VECTOR8_NOT_EQUAL);
9330   bind(VECTOR4_NOT_EQUAL);
9331   bsfq(tmp1, tmp1);
9332   shrq(tmp1, 3);
9333   addq(result, tmp1);
9334   bind(BYTES_NOT_EQUAL);
9335   shrq(result);
9336   jmpb(DONE);
9337 
9338   bind(SAME_TILL_END);
9339   mov64(result, -1);
9340 
9341   bind(DONE);
9342 }
9343 
9344 //Helper functions for square_to_len()
9345 
9346 /**
9347  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9348  * Preserves x and z and modifies rest of the registers.
9349  */
9350 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9351   // Perform square and right shift by 1
9352   // Handle odd xlen case first, then for even xlen do the following
9353   // jlong carry = 0;
9354   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9355   //     huge_128 product = x[j:j+1] * x[j:j+1];
9356   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9357   //     z[i+2:i+3] = (jlong)(product >>> 1);
9358   //     carry = (jlong)product;
9359   // }
9360 
9361   xorq(tmp5, tmp5);     // carry
9362   xorq(rdxReg, rdxReg);
9363   xorl(tmp1, tmp1);     // index for x
9364   xorl(tmp4, tmp4);     // index for z
9365 
9366   Label L_first_loop, L_first_loop_exit;
9367 
9368   testl(xlen, 1);
9369   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9370 
9371   // Square and right shift by 1 the odd element using 32 bit multiply
9372   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9373   imulq(raxReg, raxReg);
9374   shrq(raxReg, 1);
9375   adcq(tmp5, 0);
9376   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9377   incrementl(tmp1);
9378   addl(tmp4, 2);
9379 
9380   // Square and  right shift by 1 the rest using 64 bit multiply
9381   bind(L_first_loop);
9382   cmpptr(tmp1, xlen);
9383   jccb(Assembler::equal, L_first_loop_exit);
9384 
9385   // Square
9386   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9387   rorq(raxReg, 32);    // convert big-endian to little-endian
9388   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9389 
9390   // Right shift by 1 and save carry
9391   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9392   rcrq(rdxReg, 1);
9393   rcrq(raxReg, 1);
9394   adcq(tmp5, 0);
9395 
9396   // Store result in z
9397   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9398   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9399 
9400   // Update indices for x and z
9401   addl(tmp1, 2);
9402   addl(tmp4, 4);
9403   jmp(L_first_loop);
9404 
9405   bind(L_first_loop_exit);
9406 }
9407 
9408 
9409 /**
9410  * Perform the following multiply add operation using BMI2 instructions
9411  * carry:sum = sum + op1*op2 + carry
9412  * op2 should be in rdx
9413  * op2 is preserved, all other registers are modified
9414  */
9415 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9416   // assert op2 is rdx
9417   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9418   addq(sum, carry);
9419   adcq(tmp2, 0);
9420   addq(sum, op1);
9421   adcq(tmp2, 0);
9422   movq(carry, tmp2);
9423 }
9424 
9425 /**
9426  * Perform the following multiply add operation:
9427  * carry:sum = sum + op1*op2 + carry
9428  * Preserves op1, op2 and modifies rest of registers
9429  */
9430 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9431   // rdx:rax = op1 * op2
9432   movq(raxReg, op2);
9433   mulq(op1);
9434 
9435   //  rdx:rax = sum + carry + rdx:rax
9436   addq(sum, carry);
9437   adcq(rdxReg, 0);
9438   addq(sum, raxReg);
9439   adcq(rdxReg, 0);
9440 
9441   // carry:sum = rdx:sum
9442   movq(carry, rdxReg);
9443 }
9444 
9445 /**
9446  * Add 64 bit long carry into z[] with carry propogation.
9447  * Preserves z and carry register values and modifies rest of registers.
9448  *
9449  */
9450 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9451   Label L_fourth_loop, L_fourth_loop_exit;
9452 
9453   movl(tmp1, 1);
9454   subl(zlen, 2);
9455   addq(Address(z, zlen, Address::times_4, 0), carry);
9456 
9457   bind(L_fourth_loop);
9458   jccb(Assembler::carryClear, L_fourth_loop_exit);
9459   subl(zlen, 2);
9460   jccb(Assembler::negative, L_fourth_loop_exit);
9461   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9462   jmp(L_fourth_loop);
9463   bind(L_fourth_loop_exit);
9464 }
9465 
9466 /**
9467  * Shift z[] left by 1 bit.
9468  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9469  *
9470  */
9471 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9472 
9473   Label L_fifth_loop, L_fifth_loop_exit;
9474 
9475   // Fifth loop
9476   // Perform primitiveLeftShift(z, zlen, 1)
9477 
9478   const Register prev_carry = tmp1;
9479   const Register new_carry = tmp4;
9480   const Register value = tmp2;
9481   const Register zidx = tmp3;
9482 
9483   // int zidx, carry;
9484   // long value;
9485   // carry = 0;
9486   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9487   //    (carry:value)  = (z[i] << 1) | carry ;
9488   //    z[i] = value;
9489   // }
9490 
9491   movl(zidx, zlen);
9492   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9493 
9494   bind(L_fifth_loop);
9495   decl(zidx);  // Use decl to preserve carry flag
9496   decl(zidx);
9497   jccb(Assembler::negative, L_fifth_loop_exit);
9498 
9499   if (UseBMI2Instructions) {
9500      movq(value, Address(z, zidx, Address::times_4, 0));
9501      rclq(value, 1);
9502      rorxq(value, value, 32);
9503      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9504   }
9505   else {
9506     // clear new_carry
9507     xorl(new_carry, new_carry);
9508 
9509     // Shift z[i] by 1, or in previous carry and save new carry
9510     movq(value, Address(z, zidx, Address::times_4, 0));
9511     shlq(value, 1);
9512     adcl(new_carry, 0);
9513 
9514     orq(value, prev_carry);
9515     rorq(value, 0x20);
9516     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9517 
9518     // Set previous carry = new carry
9519     movl(prev_carry, new_carry);
9520   }
9521   jmp(L_fifth_loop);
9522 
9523   bind(L_fifth_loop_exit);
9524 }
9525 
9526 
9527 /**
9528  * Code for BigInteger::squareToLen() intrinsic
9529  *
9530  * rdi: x
9531  * rsi: len
9532  * r8:  z
9533  * rcx: zlen
9534  * r12: tmp1
9535  * r13: tmp2
9536  * r14: tmp3
9537  * r15: tmp4
9538  * rbx: tmp5
9539  *
9540  */
9541 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) {
9542 
9543   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;
9544   push(tmp1);
9545   push(tmp2);
9546   push(tmp3);
9547   push(tmp4);
9548   push(tmp5);
9549 
9550   // First loop
9551   // Store the squares, right shifted one bit (i.e., divided by 2).
9552   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9553 
9554   // Add in off-diagonal sums.
9555   //
9556   // Second, third (nested) and fourth loops.
9557   // zlen +=2;
9558   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9559   //    carry = 0;
9560   //    long op2 = x[xidx:xidx+1];
9561   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9562   //       k -= 2;
9563   //       long op1 = x[j:j+1];
9564   //       long sum = z[k:k+1];
9565   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9566   //       z[k:k+1] = sum;
9567   //    }
9568   //    add_one_64(z, k, carry, tmp_regs);
9569   // }
9570 
9571   const Register carry = tmp5;
9572   const Register sum = tmp3;
9573   const Register op1 = tmp4;
9574   Register op2 = tmp2;
9575 
9576   push(zlen);
9577   push(len);
9578   addl(zlen,2);
9579   bind(L_second_loop);
9580   xorq(carry, carry);
9581   subl(zlen, 4);
9582   subl(len, 2);
9583   push(zlen);
9584   push(len);
9585   cmpl(len, 0);
9586   jccb(Assembler::lessEqual, L_second_loop_exit);
9587 
9588   // Multiply an array by one 64 bit long.
9589   if (UseBMI2Instructions) {
9590     op2 = rdxReg;
9591     movq(op2, Address(x, len, Address::times_4,  0));
9592     rorxq(op2, op2, 32);
9593   }
9594   else {
9595     movq(op2, Address(x, len, Address::times_4,  0));
9596     rorq(op2, 32);
9597   }
9598 
9599   bind(L_third_loop);
9600   decrementl(len);
9601   jccb(Assembler::negative, L_third_loop_exit);
9602   decrementl(len);
9603   jccb(Assembler::negative, L_last_x);
9604 
9605   movq(op1, Address(x, len, Address::times_4,  0));
9606   rorq(op1, 32);
9607 
9608   bind(L_multiply);
9609   subl(zlen, 2);
9610   movq(sum, Address(z, zlen, Address::times_4,  0));
9611 
9612   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9613   if (UseBMI2Instructions) {
9614     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9615   }
9616   else {
9617     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9618   }
9619 
9620   movq(Address(z, zlen, Address::times_4, 0), sum);
9621 
9622   jmp(L_third_loop);
9623   bind(L_third_loop_exit);
9624 
9625   // Fourth loop
9626   // Add 64 bit long carry into z with carry propogation.
9627   // Uses offsetted zlen.
9628   add_one_64(z, zlen, carry, tmp1);
9629 
9630   pop(len);
9631   pop(zlen);
9632   jmp(L_second_loop);
9633 
9634   // Next infrequent code is moved outside loops.
9635   bind(L_last_x);
9636   movl(op1, Address(x, 0));
9637   jmp(L_multiply);
9638 
9639   bind(L_second_loop_exit);
9640   pop(len);
9641   pop(zlen);
9642   pop(len);
9643   pop(zlen);
9644 
9645   // Fifth loop
9646   // Shift z left 1 bit.
9647   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9648 
9649   // z[zlen-1] |= x[len-1] & 1;
9650   movl(tmp3, Address(x, len, Address::times_4, -4));
9651   andl(tmp3, 1);
9652   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9653 
9654   pop(tmp5);
9655   pop(tmp4);
9656   pop(tmp3);
9657   pop(tmp2);
9658   pop(tmp1);
9659 }
9660 
9661 /**
9662  * Helper function for mul_add()
9663  * Multiply the in[] by int k and add to out[] starting at offset offs using
9664  * 128 bit by 32 bit multiply and return the carry in tmp5.
9665  * Only quad int aligned length of in[] is operated on in this function.
9666  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9667  * This function preserves out, in and k registers.
9668  * len and offset point to the appropriate index in "in" & "out" correspondingly
9669  * tmp5 has the carry.
9670  * other registers are temporary and are modified.
9671  *
9672  */
9673 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9674   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9675   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9676 
9677   Label L_first_loop, L_first_loop_exit;
9678 
9679   movl(tmp1, len);
9680   shrl(tmp1, 2);
9681 
9682   bind(L_first_loop);
9683   subl(tmp1, 1);
9684   jccb(Assembler::negative, L_first_loop_exit);
9685 
9686   subl(len, 4);
9687   subl(offset, 4);
9688 
9689   Register op2 = tmp2;
9690   const Register sum = tmp3;
9691   const Register op1 = tmp4;
9692   const Register carry = tmp5;
9693 
9694   if (UseBMI2Instructions) {
9695     op2 = rdxReg;
9696   }
9697 
9698   movq(op1, Address(in, len, Address::times_4,  8));
9699   rorq(op1, 32);
9700   movq(sum, Address(out, offset, Address::times_4,  8));
9701   rorq(sum, 32);
9702   if (UseBMI2Instructions) {
9703     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9704   }
9705   else {
9706     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9707   }
9708   // Store back in big endian from little endian
9709   rorq(sum, 0x20);
9710   movq(Address(out, offset, Address::times_4,  8), sum);
9711 
9712   movq(op1, Address(in, len, Address::times_4,  0));
9713   rorq(op1, 32);
9714   movq(sum, Address(out, offset, Address::times_4,  0));
9715   rorq(sum, 32);
9716   if (UseBMI2Instructions) {
9717     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9718   }
9719   else {
9720     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9721   }
9722   // Store back in big endian from little endian
9723   rorq(sum, 0x20);
9724   movq(Address(out, offset, Address::times_4,  0), sum);
9725 
9726   jmp(L_first_loop);
9727   bind(L_first_loop_exit);
9728 }
9729 
9730 /**
9731  * Code for BigInteger::mulAdd() intrinsic
9732  *
9733  * rdi: out
9734  * rsi: in
9735  * r11: offs (out.length - offset)
9736  * rcx: len
9737  * r8:  k
9738  * r12: tmp1
9739  * r13: tmp2
9740  * r14: tmp3
9741  * r15: tmp4
9742  * rbx: tmp5
9743  * Multiply the in[] by word k and add to out[], return the carry in rax
9744  */
9745 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9746    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9747    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9748 
9749   Label L_carry, L_last_in, L_done;
9750 
9751 // carry = 0;
9752 // for (int j=len-1; j >= 0; j--) {
9753 //    long product = (in[j] & LONG_MASK) * kLong +
9754 //                   (out[offs] & LONG_MASK) + carry;
9755 //    out[offs--] = (int)product;
9756 //    carry = product >>> 32;
9757 // }
9758 //
9759   push(tmp1);
9760   push(tmp2);
9761   push(tmp3);
9762   push(tmp4);
9763   push(tmp5);
9764 
9765   Register op2 = tmp2;
9766   const Register sum = tmp3;
9767   const Register op1 = tmp4;
9768   const Register carry =  tmp5;
9769 
9770   if (UseBMI2Instructions) {
9771     op2 = rdxReg;
9772     movl(op2, k);
9773   }
9774   else {
9775     movl(op2, k);
9776   }
9777 
9778   xorq(carry, carry);
9779 
9780   //First loop
9781 
9782   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9783   //The carry is in tmp5
9784   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9785 
9786   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9787   decrementl(len);
9788   jccb(Assembler::negative, L_carry);
9789   decrementl(len);
9790   jccb(Assembler::negative, L_last_in);
9791 
9792   movq(op1, Address(in, len, Address::times_4,  0));
9793   rorq(op1, 32);
9794 
9795   subl(offs, 2);
9796   movq(sum, Address(out, offs, Address::times_4,  0));
9797   rorq(sum, 32);
9798 
9799   if (UseBMI2Instructions) {
9800     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9801   }
9802   else {
9803     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9804   }
9805 
9806   // Store back in big endian from little endian
9807   rorq(sum, 0x20);
9808   movq(Address(out, offs, Address::times_4,  0), sum);
9809 
9810   testl(len, len);
9811   jccb(Assembler::zero, L_carry);
9812 
9813   //Multiply the last in[] entry, if any
9814   bind(L_last_in);
9815   movl(op1, Address(in, 0));
9816   movl(sum, Address(out, offs, Address::times_4,  -4));
9817 
9818   movl(raxReg, k);
9819   mull(op1); //tmp4 * eax -> edx:eax
9820   addl(sum, carry);
9821   adcl(rdxReg, 0);
9822   addl(sum, raxReg);
9823   adcl(rdxReg, 0);
9824   movl(carry, rdxReg);
9825 
9826   movl(Address(out, offs, Address::times_4,  -4), sum);
9827 
9828   bind(L_carry);
9829   //return tmp5/carry as carry in rax
9830   movl(rax, carry);
9831 
9832   bind(L_done);
9833   pop(tmp5);
9834   pop(tmp4);
9835   pop(tmp3);
9836   pop(tmp2);
9837   pop(tmp1);
9838 }
9839 #endif
9840 
9841 /**
9842  * Emits code to update CRC-32 with a byte value according to constants in table
9843  *
9844  * @param [in,out]crc   Register containing the crc.
9845  * @param [in]val       Register containing the byte to fold into the CRC.
9846  * @param [in]table     Register containing the table of crc constants.
9847  *
9848  * uint32_t crc;
9849  * val = crc_table[(val ^ crc) & 0xFF];
9850  * crc = val ^ (crc >> 8);
9851  *
9852  */
9853 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9854   xorl(val, crc);
9855   andl(val, 0xFF);
9856   shrl(crc, 8); // unsigned shift
9857   xorl(crc, Address(table, val, Address::times_4, 0));
9858 }
9859 
9860 /**
9861 * Fold four 128-bit data chunks
9862 */
9863 void MacroAssembler::fold_128bit_crc32_avx512(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9864   evpclmulhdq(xtmp, xK, xcrc, Assembler::AVX_512bit); // [123:64]
9865   evpclmulldq(xcrc, xK, xcrc, Assembler::AVX_512bit); // [63:0]
9866   evpxorq(xcrc, xcrc, Address(buf, offset), Assembler::AVX_512bit /* vector_len */);
9867   evpxorq(xcrc, xcrc, xtmp, Assembler::AVX_512bit /* vector_len */);
9868 }
9869 
9870 /**
9871  * Fold 128-bit data chunk
9872  */
9873 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9874   if (UseAVX > 0) {
9875     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9876     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9877     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9878     pxor(xcrc, xtmp);
9879   } else {
9880     movdqa(xtmp, xcrc);
9881     pclmulhdq(xtmp, xK);   // [123:64]
9882     pclmulldq(xcrc, xK);   // [63:0]
9883     pxor(xcrc, xtmp);
9884     movdqu(xtmp, Address(buf, offset));
9885     pxor(xcrc, xtmp);
9886   }
9887 }
9888 
9889 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9890   if (UseAVX > 0) {
9891     vpclmulhdq(xtmp, xK, xcrc);
9892     vpclmulldq(xcrc, xK, xcrc);
9893     pxor(xcrc, xbuf);
9894     pxor(xcrc, xtmp);
9895   } else {
9896     movdqa(xtmp, xcrc);
9897     pclmulhdq(xtmp, xK);
9898     pclmulldq(xcrc, xK);
9899     pxor(xcrc, xbuf);
9900     pxor(xcrc, xtmp);
9901   }
9902 }
9903 
9904 /**
9905  * 8-bit folds to compute 32-bit CRC
9906  *
9907  * uint64_t xcrc;
9908  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9909  */
9910 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9911   movdl(tmp, xcrc);
9912   andl(tmp, 0xFF);
9913   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
9914   psrldq(xcrc, 1); // unsigned shift one byte
9915   pxor(xcrc, xtmp);
9916 }
9917 
9918 /**
9919  * uint32_t crc;
9920  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
9921  */
9922 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
9923   movl(tmp, crc);
9924   andl(tmp, 0xFF);
9925   shrl(crc, 8);
9926   xorl(crc, Address(table, tmp, Address::times_4, 0));
9927 }
9928 
9929 /**
9930  * @param crc   register containing existing CRC (32-bit)
9931  * @param buf   register pointing to input byte buffer (byte*)
9932  * @param len   register containing number of bytes
9933  * @param table register that will contain address of CRC table
9934  * @param tmp   scratch register
9935  */
9936 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
9937   assert_different_registers(crc, buf, len, table, tmp, rax);
9938 
9939   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
9940   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
9941 
9942   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
9943   // context for the registers used, where all instructions below are using 128-bit mode
9944   // On EVEX without VL and BW, these instructions will all be AVX.
9945   if (VM_Version::supports_avx512vlbw()) {
9946     movl(tmp, 0xffff);
9947     kmovwl(k1, tmp);
9948   }
9949 
9950   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
9951   notl(crc); // ~crc
9952   cmpl(len, 16);
9953   jcc(Assembler::less, L_tail);
9954 
9955   // Align buffer to 16 bytes
9956   movl(tmp, buf);
9957   andl(tmp, 0xF);
9958   jccb(Assembler::zero, L_aligned);
9959   subl(tmp,  16);
9960   addl(len, tmp);
9961 
9962   align(4);
9963   BIND(L_align_loop);
9964   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9965   update_byte_crc32(crc, rax, table);
9966   increment(buf);
9967   incrementl(tmp);
9968   jccb(Assembler::less, L_align_loop);
9969 
9970   BIND(L_aligned);
9971   movl(tmp, len); // save
9972   shrl(len, 4);
9973   jcc(Assembler::zero, L_tail_restore);
9974 
9975   // Fold total 512 bits of polynomial on each iteration
9976   if (VM_Version::supports_vpclmulqdq()) {
9977     Label Parallel_loop, L_No_Parallel;
9978 
9979     cmpl(len, 8);
9980     jccb(Assembler::less, L_No_Parallel);
9981 
9982     movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9983     evmovdquq(xmm1, Address(buf, 0), Assembler::AVX_512bit);
9984     movdl(xmm5, crc);
9985     evpxorq(xmm1, xmm1, xmm5, Assembler::AVX_512bit);
9986     addptr(buf, 64);
9987     subl(len, 7);
9988     evshufi64x2(xmm0, xmm0, xmm0, 0x00, Assembler::AVX_512bit); //propagate the mask from 128 bits to 512 bits
9989 
9990     BIND(Parallel_loop);
9991     fold_128bit_crc32_avx512(xmm1, xmm0, xmm5, buf, 0);
9992     addptr(buf, 64);
9993     subl(len, 4);
9994     jcc(Assembler::greater, Parallel_loop);
9995 
9996     vextracti64x2(xmm2, xmm1, 0x01);
9997     vextracti64x2(xmm3, xmm1, 0x02);
9998     vextracti64x2(xmm4, xmm1, 0x03);
9999     jmp(L_fold_512b);
10000 
10001     BIND(L_No_Parallel);
10002   }
10003   // Fold crc into first bytes of vector
10004   movdqa(xmm1, Address(buf, 0));
10005   movdl(rax, xmm1);
10006   xorl(crc, rax);
10007   if (VM_Version::supports_sse4_1()) {
10008     pinsrd(xmm1, crc, 0);
10009   } else {
10010     pinsrw(xmm1, crc, 0);
10011     shrl(crc, 16);
10012     pinsrw(xmm1, crc, 1);
10013   }
10014   addptr(buf, 16);
10015   subl(len, 4); // len > 0
10016   jcc(Assembler::less, L_fold_tail);
10017 
10018   movdqa(xmm2, Address(buf,  0));
10019   movdqa(xmm3, Address(buf, 16));
10020   movdqa(xmm4, Address(buf, 32));
10021   addptr(buf, 48);
10022   subl(len, 3);
10023   jcc(Assembler::lessEqual, L_fold_512b);
10024 
10025   // Fold total 512 bits of polynomial on each iteration,
10026   // 128 bits per each of 4 parallel streams.
10027   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10028 
10029   align(32);
10030   BIND(L_fold_512b_loop);
10031   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10032   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10033   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10034   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10035   addptr(buf, 64);
10036   subl(len, 4);
10037   jcc(Assembler::greater, L_fold_512b_loop);
10038 
10039   // Fold 512 bits to 128 bits.
10040   BIND(L_fold_512b);
10041   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10042   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10043   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10044   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10045 
10046   // Fold the rest of 128 bits data chunks
10047   BIND(L_fold_tail);
10048   addl(len, 3);
10049   jccb(Assembler::lessEqual, L_fold_128b);
10050   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10051 
10052   BIND(L_fold_tail_loop);
10053   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10054   addptr(buf, 16);
10055   decrementl(len);
10056   jccb(Assembler::greater, L_fold_tail_loop);
10057 
10058   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10059   BIND(L_fold_128b);
10060   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10061   if (UseAVX > 0) {
10062     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10063     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10064     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10065   } else {
10066     movdqa(xmm2, xmm0);
10067     pclmulqdq(xmm2, xmm1, 0x1);
10068     movdqa(xmm3, xmm0);
10069     pand(xmm3, xmm2);
10070     pclmulqdq(xmm0, xmm3, 0x1);
10071   }
10072   psrldq(xmm1, 8);
10073   psrldq(xmm2, 4);
10074   pxor(xmm0, xmm1);
10075   pxor(xmm0, xmm2);
10076 
10077   // 8 8-bit folds to compute 32-bit CRC.
10078   for (int j = 0; j < 4; j++) {
10079     fold_8bit_crc32(xmm0, table, xmm1, rax);
10080   }
10081   movdl(crc, xmm0); // mov 32 bits to general register
10082   for (int j = 0; j < 4; j++) {
10083     fold_8bit_crc32(crc, table, rax);
10084   }
10085 
10086   BIND(L_tail_restore);
10087   movl(len, tmp); // restore
10088   BIND(L_tail);
10089   andl(len, 0xf);
10090   jccb(Assembler::zero, L_exit);
10091 
10092   // Fold the rest of bytes
10093   align(4);
10094   BIND(L_tail_loop);
10095   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10096   update_byte_crc32(crc, rax, table);
10097   increment(buf);
10098   decrementl(len);
10099   jccb(Assembler::greater, L_tail_loop);
10100 
10101   BIND(L_exit);
10102   notl(crc); // ~c
10103 }
10104 
10105 #ifdef _LP64
10106 // S. Gueron / Information Processing Letters 112 (2012) 184
10107 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10108 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10109 // Output: the 64-bit carry-less product of B * CONST
10110 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10111                                      Register tmp1, Register tmp2, Register tmp3) {
10112   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10113   if (n > 0) {
10114     addq(tmp3, n * 256 * 8);
10115   }
10116   //    Q1 = TABLEExt[n][B & 0xFF];
10117   movl(tmp1, in);
10118   andl(tmp1, 0x000000FF);
10119   shll(tmp1, 3);
10120   addq(tmp1, tmp3);
10121   movq(tmp1, Address(tmp1, 0));
10122 
10123   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10124   movl(tmp2, in);
10125   shrl(tmp2, 8);
10126   andl(tmp2, 0x000000FF);
10127   shll(tmp2, 3);
10128   addq(tmp2, tmp3);
10129   movq(tmp2, Address(tmp2, 0));
10130 
10131   shlq(tmp2, 8);
10132   xorq(tmp1, tmp2);
10133 
10134   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10135   movl(tmp2, in);
10136   shrl(tmp2, 16);
10137   andl(tmp2, 0x000000FF);
10138   shll(tmp2, 3);
10139   addq(tmp2, tmp3);
10140   movq(tmp2, Address(tmp2, 0));
10141 
10142   shlq(tmp2, 16);
10143   xorq(tmp1, tmp2);
10144 
10145   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10146   shrl(in, 24);
10147   andl(in, 0x000000FF);
10148   shll(in, 3);
10149   addq(in, tmp3);
10150   movq(in, Address(in, 0));
10151 
10152   shlq(in, 24);
10153   xorq(in, tmp1);
10154   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10155 }
10156 
10157 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10158                                       Register in_out,
10159                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10160                                       XMMRegister w_xtmp2,
10161                                       Register tmp1,
10162                                       Register n_tmp2, Register n_tmp3) {
10163   if (is_pclmulqdq_supported) {
10164     movdl(w_xtmp1, in_out); // modified blindly
10165 
10166     movl(tmp1, const_or_pre_comp_const_index);
10167     movdl(w_xtmp2, tmp1);
10168     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10169 
10170     movdq(in_out, w_xtmp1);
10171   } else {
10172     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10173   }
10174 }
10175 
10176 // Recombination Alternative 2: No bit-reflections
10177 // T1 = (CRC_A * U1) << 1
10178 // T2 = (CRC_B * U2) << 1
10179 // C1 = T1 >> 32
10180 // C2 = T2 >> 32
10181 // T1 = T1 & 0xFFFFFFFF
10182 // T2 = T2 & 0xFFFFFFFF
10183 // T1 = CRC32(0, T1)
10184 // T2 = CRC32(0, T2)
10185 // C1 = C1 ^ T1
10186 // C2 = C2 ^ T2
10187 // CRC = C1 ^ C2 ^ CRC_C
10188 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,
10189                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10190                                      Register tmp1, Register tmp2,
10191                                      Register n_tmp3) {
10192   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10193   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10194   shlq(in_out, 1);
10195   movl(tmp1, in_out);
10196   shrq(in_out, 32);
10197   xorl(tmp2, tmp2);
10198   crc32(tmp2, tmp1, 4);
10199   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10200   shlq(in1, 1);
10201   movl(tmp1, in1);
10202   shrq(in1, 32);
10203   xorl(tmp2, tmp2);
10204   crc32(tmp2, tmp1, 4);
10205   xorl(in1, tmp2);
10206   xorl(in_out, in1);
10207   xorl(in_out, in2);
10208 }
10209 
10210 // Set N to predefined value
10211 // Subtract from a lenght of a buffer
10212 // execute in a loop:
10213 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10214 // for i = 1 to N do
10215 //  CRC_A = CRC32(CRC_A, A[i])
10216 //  CRC_B = CRC32(CRC_B, B[i])
10217 //  CRC_C = CRC32(CRC_C, C[i])
10218 // end for
10219 // Recombine
10220 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,
10221                                        Register in_out1, Register in_out2, Register in_out3,
10222                                        Register tmp1, Register tmp2, Register tmp3,
10223                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10224                                        Register tmp4, Register tmp5,
10225                                        Register n_tmp6) {
10226   Label L_processPartitions;
10227   Label L_processPartition;
10228   Label L_exit;
10229 
10230   bind(L_processPartitions);
10231   cmpl(in_out1, 3 * size);
10232   jcc(Assembler::less, L_exit);
10233     xorl(tmp1, tmp1);
10234     xorl(tmp2, tmp2);
10235     movq(tmp3, in_out2);
10236     addq(tmp3, size);
10237 
10238     bind(L_processPartition);
10239       crc32(in_out3, Address(in_out2, 0), 8);
10240       crc32(tmp1, Address(in_out2, size), 8);
10241       crc32(tmp2, Address(in_out2, size * 2), 8);
10242       addq(in_out2, 8);
10243       cmpq(in_out2, tmp3);
10244       jcc(Assembler::less, L_processPartition);
10245     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10246             w_xtmp1, w_xtmp2, w_xtmp3,
10247             tmp4, tmp5,
10248             n_tmp6);
10249     addq(in_out2, 2 * size);
10250     subl(in_out1, 3 * size);
10251     jmp(L_processPartitions);
10252 
10253   bind(L_exit);
10254 }
10255 #else
10256 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10257                                      Register tmp1, Register tmp2, Register tmp3,
10258                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10259   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10260   if (n > 0) {
10261     addl(tmp3, n * 256 * 8);
10262   }
10263   //    Q1 = TABLEExt[n][B & 0xFF];
10264   movl(tmp1, in_out);
10265   andl(tmp1, 0x000000FF);
10266   shll(tmp1, 3);
10267   addl(tmp1, tmp3);
10268   movq(xtmp1, Address(tmp1, 0));
10269 
10270   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10271   movl(tmp2, in_out);
10272   shrl(tmp2, 8);
10273   andl(tmp2, 0x000000FF);
10274   shll(tmp2, 3);
10275   addl(tmp2, tmp3);
10276   movq(xtmp2, Address(tmp2, 0));
10277 
10278   psllq(xtmp2, 8);
10279   pxor(xtmp1, xtmp2);
10280 
10281   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10282   movl(tmp2, in_out);
10283   shrl(tmp2, 16);
10284   andl(tmp2, 0x000000FF);
10285   shll(tmp2, 3);
10286   addl(tmp2, tmp3);
10287   movq(xtmp2, Address(tmp2, 0));
10288 
10289   psllq(xtmp2, 16);
10290   pxor(xtmp1, xtmp2);
10291 
10292   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10293   shrl(in_out, 24);
10294   andl(in_out, 0x000000FF);
10295   shll(in_out, 3);
10296   addl(in_out, tmp3);
10297   movq(xtmp2, Address(in_out, 0));
10298 
10299   psllq(xtmp2, 24);
10300   pxor(xtmp1, xtmp2); // Result in CXMM
10301   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10302 }
10303 
10304 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10305                                       Register in_out,
10306                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10307                                       XMMRegister w_xtmp2,
10308                                       Register tmp1,
10309                                       Register n_tmp2, Register n_tmp3) {
10310   if (is_pclmulqdq_supported) {
10311     movdl(w_xtmp1, in_out);
10312 
10313     movl(tmp1, const_or_pre_comp_const_index);
10314     movdl(w_xtmp2, tmp1);
10315     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10316     // Keep result in XMM since GPR is 32 bit in length
10317   } else {
10318     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10319   }
10320 }
10321 
10322 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,
10323                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10324                                      Register tmp1, Register tmp2,
10325                                      Register n_tmp3) {
10326   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10327   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10328 
10329   psllq(w_xtmp1, 1);
10330   movdl(tmp1, w_xtmp1);
10331   psrlq(w_xtmp1, 32);
10332   movdl(in_out, w_xtmp1);
10333 
10334   xorl(tmp2, tmp2);
10335   crc32(tmp2, tmp1, 4);
10336   xorl(in_out, tmp2);
10337 
10338   psllq(w_xtmp2, 1);
10339   movdl(tmp1, w_xtmp2);
10340   psrlq(w_xtmp2, 32);
10341   movdl(in1, w_xtmp2);
10342 
10343   xorl(tmp2, tmp2);
10344   crc32(tmp2, tmp1, 4);
10345   xorl(in1, tmp2);
10346   xorl(in_out, in1);
10347   xorl(in_out, in2);
10348 }
10349 
10350 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,
10351                                        Register in_out1, Register in_out2, Register in_out3,
10352                                        Register tmp1, Register tmp2, Register tmp3,
10353                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10354                                        Register tmp4, Register tmp5,
10355                                        Register n_tmp6) {
10356   Label L_processPartitions;
10357   Label L_processPartition;
10358   Label L_exit;
10359 
10360   bind(L_processPartitions);
10361   cmpl(in_out1, 3 * size);
10362   jcc(Assembler::less, L_exit);
10363     xorl(tmp1, tmp1);
10364     xorl(tmp2, tmp2);
10365     movl(tmp3, in_out2);
10366     addl(tmp3, size);
10367 
10368     bind(L_processPartition);
10369       crc32(in_out3, Address(in_out2, 0), 4);
10370       crc32(tmp1, Address(in_out2, size), 4);
10371       crc32(tmp2, Address(in_out2, size*2), 4);
10372       crc32(in_out3, Address(in_out2, 0+4), 4);
10373       crc32(tmp1, Address(in_out2, size+4), 4);
10374       crc32(tmp2, Address(in_out2, size*2+4), 4);
10375       addl(in_out2, 8);
10376       cmpl(in_out2, tmp3);
10377       jcc(Assembler::less, L_processPartition);
10378 
10379         push(tmp3);
10380         push(in_out1);
10381         push(in_out2);
10382         tmp4 = tmp3;
10383         tmp5 = in_out1;
10384         n_tmp6 = in_out2;
10385 
10386       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10387             w_xtmp1, w_xtmp2, w_xtmp3,
10388             tmp4, tmp5,
10389             n_tmp6);
10390 
10391         pop(in_out2);
10392         pop(in_out1);
10393         pop(tmp3);
10394 
10395     addl(in_out2, 2 * size);
10396     subl(in_out1, 3 * size);
10397     jmp(L_processPartitions);
10398 
10399   bind(L_exit);
10400 }
10401 #endif //LP64
10402 
10403 #ifdef _LP64
10404 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10405 // Input: A buffer I of L bytes.
10406 // Output: the CRC32C value of the buffer.
10407 // Notations:
10408 // Write L = 24N + r, with N = floor (L/24).
10409 // r = L mod 24 (0 <= r < 24).
10410 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10411 // N quadwords, and R consists of r bytes.
10412 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10413 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10414 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10415 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10416 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10417                                           Register tmp1, Register tmp2, Register tmp3,
10418                                           Register tmp4, Register tmp5, Register tmp6,
10419                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10420                                           bool is_pclmulqdq_supported) {
10421   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10422   Label L_wordByWord;
10423   Label L_byteByByteProlog;
10424   Label L_byteByByte;
10425   Label L_exit;
10426 
10427   if (is_pclmulqdq_supported ) {
10428     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10429     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10430 
10431     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10432     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10433 
10434     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10435     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10436     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10437   } else {
10438     const_or_pre_comp_const_index[0] = 1;
10439     const_or_pre_comp_const_index[1] = 0;
10440 
10441     const_or_pre_comp_const_index[2] = 3;
10442     const_or_pre_comp_const_index[3] = 2;
10443 
10444     const_or_pre_comp_const_index[4] = 5;
10445     const_or_pre_comp_const_index[5] = 4;
10446    }
10447   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10448                     in2, in1, in_out,
10449                     tmp1, tmp2, tmp3,
10450                     w_xtmp1, w_xtmp2, w_xtmp3,
10451                     tmp4, tmp5,
10452                     tmp6);
10453   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10454                     in2, in1, in_out,
10455                     tmp1, tmp2, tmp3,
10456                     w_xtmp1, w_xtmp2, w_xtmp3,
10457                     tmp4, tmp5,
10458                     tmp6);
10459   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10460                     in2, in1, in_out,
10461                     tmp1, tmp2, tmp3,
10462                     w_xtmp1, w_xtmp2, w_xtmp3,
10463                     tmp4, tmp5,
10464                     tmp6);
10465   movl(tmp1, in2);
10466   andl(tmp1, 0x00000007);
10467   negl(tmp1);
10468   addl(tmp1, in2);
10469   addq(tmp1, in1);
10470 
10471   BIND(L_wordByWord);
10472   cmpq(in1, tmp1);
10473   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10474     crc32(in_out, Address(in1, 0), 4);
10475     addq(in1, 4);
10476     jmp(L_wordByWord);
10477 
10478   BIND(L_byteByByteProlog);
10479   andl(in2, 0x00000007);
10480   movl(tmp2, 1);
10481 
10482   BIND(L_byteByByte);
10483   cmpl(tmp2, in2);
10484   jccb(Assembler::greater, L_exit);
10485     crc32(in_out, Address(in1, 0), 1);
10486     incq(in1);
10487     incl(tmp2);
10488     jmp(L_byteByByte);
10489 
10490   BIND(L_exit);
10491 }
10492 #else
10493 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10494                                           Register tmp1, Register  tmp2, Register tmp3,
10495                                           Register tmp4, Register  tmp5, Register tmp6,
10496                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10497                                           bool is_pclmulqdq_supported) {
10498   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10499   Label L_wordByWord;
10500   Label L_byteByByteProlog;
10501   Label L_byteByByte;
10502   Label L_exit;
10503 
10504   if (is_pclmulqdq_supported) {
10505     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10506     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10507 
10508     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10509     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10510 
10511     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10512     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10513   } else {
10514     const_or_pre_comp_const_index[0] = 1;
10515     const_or_pre_comp_const_index[1] = 0;
10516 
10517     const_or_pre_comp_const_index[2] = 3;
10518     const_or_pre_comp_const_index[3] = 2;
10519 
10520     const_or_pre_comp_const_index[4] = 5;
10521     const_or_pre_comp_const_index[5] = 4;
10522   }
10523   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10524                     in2, in1, in_out,
10525                     tmp1, tmp2, tmp3,
10526                     w_xtmp1, w_xtmp2, w_xtmp3,
10527                     tmp4, tmp5,
10528                     tmp6);
10529   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10530                     in2, in1, in_out,
10531                     tmp1, tmp2, tmp3,
10532                     w_xtmp1, w_xtmp2, w_xtmp3,
10533                     tmp4, tmp5,
10534                     tmp6);
10535   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10536                     in2, in1, in_out,
10537                     tmp1, tmp2, tmp3,
10538                     w_xtmp1, w_xtmp2, w_xtmp3,
10539                     tmp4, tmp5,
10540                     tmp6);
10541   movl(tmp1, in2);
10542   andl(tmp1, 0x00000007);
10543   negl(tmp1);
10544   addl(tmp1, in2);
10545   addl(tmp1, in1);
10546 
10547   BIND(L_wordByWord);
10548   cmpl(in1, tmp1);
10549   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10550     crc32(in_out, Address(in1,0), 4);
10551     addl(in1, 4);
10552     jmp(L_wordByWord);
10553 
10554   BIND(L_byteByByteProlog);
10555   andl(in2, 0x00000007);
10556   movl(tmp2, 1);
10557 
10558   BIND(L_byteByByte);
10559   cmpl(tmp2, in2);
10560   jccb(Assembler::greater, L_exit);
10561     movb(tmp1, Address(in1, 0));
10562     crc32(in_out, tmp1, 1);
10563     incl(in1);
10564     incl(tmp2);
10565     jmp(L_byteByByte);
10566 
10567   BIND(L_exit);
10568 }
10569 #endif // LP64
10570 #undef BIND
10571 #undef BLOCK_COMMENT
10572 
10573 // Compress char[] array to byte[].
10574 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10575 //   @HotSpotIntrinsicCandidate
10576 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10577 //     for (int i = 0; i < len; i++) {
10578 //       int c = src[srcOff++];
10579 //       if (c >>> 8 != 0) {
10580 //         return 0;
10581 //       }
10582 //       dst[dstOff++] = (byte)c;
10583 //     }
10584 //     return len;
10585 //   }
10586 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10587   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10588   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10589   Register tmp5, Register result) {
10590   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10591 
10592   // rsi: src
10593   // rdi: dst
10594   // rdx: len
10595   // rcx: tmp5
10596   // rax: result
10597 
10598   // rsi holds start addr of source char[] to be compressed
10599   // rdi holds start addr of destination byte[]
10600   // rdx holds length
10601 
10602   assert(len != result, "");
10603 
10604   // save length for return
10605   push(len);
10606 
10607   if ((UseAVX > 2) && // AVX512
10608     VM_Version::supports_avx512vlbw() &&
10609     VM_Version::supports_bmi2()) {
10610 
10611     set_vector_masking();  // opening of the stub context for programming mask registers
10612 
10613     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10614 
10615     // alignement
10616     Label post_alignement;
10617 
10618     // if length of the string is less than 16, handle it in an old fashioned
10619     // way
10620     testl(len, -32);
10621     jcc(Assembler::zero, below_threshold);
10622 
10623     // First check whether a character is compressable ( <= 0xFF).
10624     // Create mask to test for Unicode chars inside zmm vector
10625     movl(result, 0x00FF);
10626     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10627 
10628     // Save k1
10629     kmovql(k3, k1);
10630 
10631     testl(len, -64);
10632     jcc(Assembler::zero, post_alignement);
10633 
10634     movl(tmp5, dst);
10635     andl(tmp5, (32 - 1));
10636     negl(tmp5);
10637     andl(tmp5, (32 - 1));
10638 
10639     // bail out when there is nothing to be done
10640     testl(tmp5, 0xFFFFFFFF);
10641     jcc(Assembler::zero, post_alignement);
10642 
10643     // ~(~0 << len), where len is the # of remaining elements to process
10644     movl(result, 0xFFFFFFFF);
10645     shlxl(result, result, tmp5);
10646     notl(result);
10647     kmovdl(k1, result);
10648 
10649     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10650     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10651     ktestd(k2, k1);
10652     jcc(Assembler::carryClear, restore_k1_return_zero);
10653 
10654     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10655 
10656     addptr(src, tmp5);
10657     addptr(src, tmp5);
10658     addptr(dst, tmp5);
10659     subl(len, tmp5);
10660 
10661     bind(post_alignement);
10662     // end of alignement
10663 
10664     movl(tmp5, len);
10665     andl(tmp5, (32 - 1));    // tail count (in chars)
10666     andl(len, ~(32 - 1));    // vector count (in chars)
10667     jcc(Assembler::zero, copy_loop_tail);
10668 
10669     lea(src, Address(src, len, Address::times_2));
10670     lea(dst, Address(dst, len, Address::times_1));
10671     negptr(len);
10672 
10673     bind(copy_32_loop);
10674     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10675     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10676     kortestdl(k2, k2);
10677     jcc(Assembler::carryClear, restore_k1_return_zero);
10678 
10679     // All elements in current processed chunk are valid candidates for
10680     // compression. Write a truncated byte elements to the memory.
10681     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10682     addptr(len, 32);
10683     jcc(Assembler::notZero, copy_32_loop);
10684 
10685     bind(copy_loop_tail);
10686     // bail out when there is nothing to be done
10687     testl(tmp5, 0xFFFFFFFF);
10688     // Restore k1
10689     kmovql(k1, k3);
10690     jcc(Assembler::zero, return_length);
10691 
10692     movl(len, tmp5);
10693 
10694     // ~(~0 << len), where len is the # of remaining elements to process
10695     movl(result, 0xFFFFFFFF);
10696     shlxl(result, result, len);
10697     notl(result);
10698 
10699     kmovdl(k1, result);
10700 
10701     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10702     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10703     ktestd(k2, k1);
10704     jcc(Assembler::carryClear, restore_k1_return_zero);
10705 
10706     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10707     // Restore k1
10708     kmovql(k1, k3);
10709     jmp(return_length);
10710 
10711     bind(restore_k1_return_zero);
10712     // Restore k1
10713     kmovql(k1, k3);
10714     jmp(return_zero);
10715 
10716     clear_vector_masking();   // closing of the stub context for programming mask registers
10717   }
10718   if (UseSSE42Intrinsics) {
10719     Label copy_32_loop, copy_16, copy_tail;
10720 
10721     bind(below_threshold);
10722 
10723     movl(result, len);
10724 
10725     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10726 
10727     // vectored compression
10728     andl(len, 0xfffffff0);    // vector count (in chars)
10729     andl(result, 0x0000000f);    // tail count (in chars)
10730     testl(len, len);
10731     jccb(Assembler::zero, copy_16);
10732 
10733     // compress 16 chars per iter
10734     movdl(tmp1Reg, tmp5);
10735     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10736     pxor(tmp4Reg, tmp4Reg);
10737 
10738     lea(src, Address(src, len, Address::times_2));
10739     lea(dst, Address(dst, len, Address::times_1));
10740     negptr(len);
10741 
10742     bind(copy_32_loop);
10743     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10744     por(tmp4Reg, tmp2Reg);
10745     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10746     por(tmp4Reg, tmp3Reg);
10747     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10748     jcc(Assembler::notZero, return_zero);
10749     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10750     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10751     addptr(len, 16);
10752     jcc(Assembler::notZero, copy_32_loop);
10753 
10754     // compress next vector of 8 chars (if any)
10755     bind(copy_16);
10756     movl(len, result);
10757     andl(len, 0xfffffff8);    // vector count (in chars)
10758     andl(result, 0x00000007);    // tail count (in chars)
10759     testl(len, len);
10760     jccb(Assembler::zero, copy_tail);
10761 
10762     movdl(tmp1Reg, tmp5);
10763     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10764     pxor(tmp3Reg, tmp3Reg);
10765 
10766     movdqu(tmp2Reg, Address(src, 0));
10767     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10768     jccb(Assembler::notZero, return_zero);
10769     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10770     movq(Address(dst, 0), tmp2Reg);
10771     addptr(src, 16);
10772     addptr(dst, 8);
10773 
10774     bind(copy_tail);
10775     movl(len, result);
10776   }
10777   // compress 1 char per iter
10778   testl(len, len);
10779   jccb(Assembler::zero, return_length);
10780   lea(src, Address(src, len, Address::times_2));
10781   lea(dst, Address(dst, len, Address::times_1));
10782   negptr(len);
10783 
10784   bind(copy_chars_loop);
10785   load_unsigned_short(result, Address(src, len, Address::times_2));
10786   testl(result, 0xff00);      // check if Unicode char
10787   jccb(Assembler::notZero, return_zero);
10788   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10789   increment(len);
10790   jcc(Assembler::notZero, copy_chars_loop);
10791 
10792   // if compression succeeded, return length
10793   bind(return_length);
10794   pop(result);
10795   jmpb(done);
10796 
10797   // if compression failed, return 0
10798   bind(return_zero);
10799   xorl(result, result);
10800   addptr(rsp, wordSize);
10801 
10802   bind(done);
10803 }
10804 
10805 // Inflate byte[] array to char[].
10806 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
10807 //   @HotSpotIntrinsicCandidate
10808 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
10809 //     for (int i = 0; i < len; i++) {
10810 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
10811 //     }
10812 //   }
10813 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10814   XMMRegister tmp1, Register tmp2) {
10815   Label copy_chars_loop, done, below_threshold;
10816   // rsi: src
10817   // rdi: dst
10818   // rdx: len
10819   // rcx: tmp2
10820 
10821   // rsi holds start addr of source byte[] to be inflated
10822   // rdi holds start addr of destination char[]
10823   // rdx holds length
10824   assert_different_registers(src, dst, len, tmp2);
10825 
10826   if ((UseAVX > 2) && // AVX512
10827     VM_Version::supports_avx512vlbw() &&
10828     VM_Version::supports_bmi2()) {
10829 
10830     set_vector_masking();  // opening of the stub context for programming mask registers
10831 
10832     Label copy_32_loop, copy_tail;
10833     Register tmp3_aliased = len;
10834 
10835     // if length of the string is less than 16, handle it in an old fashioned
10836     // way
10837     testl(len, -16);
10838     jcc(Assembler::zero, below_threshold);
10839 
10840     // In order to use only one arithmetic operation for the main loop we use
10841     // this pre-calculation
10842     movl(tmp2, len);
10843     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
10844     andl(len, -32);     // vector count
10845     jccb(Assembler::zero, copy_tail);
10846 
10847     lea(src, Address(src, len, Address::times_1));
10848     lea(dst, Address(dst, len, Address::times_2));
10849     negptr(len);
10850 
10851 
10852     // inflate 32 chars per iter
10853     bind(copy_32_loop);
10854     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
10855     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
10856     addptr(len, 32);
10857     jcc(Assembler::notZero, copy_32_loop);
10858 
10859     bind(copy_tail);
10860     // bail out when there is nothing to be done
10861     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
10862     jcc(Assembler::zero, done);
10863 
10864     // Save k1
10865     kmovql(k2, k1);
10866 
10867     // ~(~0 << length), where length is the # of remaining elements to process
10868     movl(tmp3_aliased, -1);
10869     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
10870     notl(tmp3_aliased);
10871     kmovdl(k1, tmp3_aliased);
10872     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
10873     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
10874 
10875     // Restore k1
10876     kmovql(k1, k2);
10877     jmp(done);
10878 
10879     clear_vector_masking();   // closing of the stub context for programming mask registers
10880   }
10881   if (UseSSE42Intrinsics) {
10882     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
10883 
10884     movl(tmp2, len);
10885 
10886     if (UseAVX > 1) {
10887       andl(tmp2, (16 - 1));
10888       andl(len, -16);
10889       jccb(Assembler::zero, copy_new_tail);
10890     } else {
10891       andl(tmp2, 0x00000007);   // tail count (in chars)
10892       andl(len, 0xfffffff8);    // vector count (in chars)
10893       jccb(Assembler::zero, copy_tail);
10894     }
10895 
10896     // vectored inflation
10897     lea(src, Address(src, len, Address::times_1));
10898     lea(dst, Address(dst, len, Address::times_2));
10899     negptr(len);
10900 
10901     if (UseAVX > 1) {
10902       bind(copy_16_loop);
10903       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
10904       vmovdqu(Address(dst, len, Address::times_2), tmp1);
10905       addptr(len, 16);
10906       jcc(Assembler::notZero, copy_16_loop);
10907 
10908       bind(below_threshold);
10909       bind(copy_new_tail);
10910       if ((UseAVX > 2) &&
10911         VM_Version::supports_avx512vlbw() &&
10912         VM_Version::supports_bmi2()) {
10913         movl(tmp2, len);
10914       } else {
10915         movl(len, tmp2);
10916       }
10917       andl(tmp2, 0x00000007);
10918       andl(len, 0xFFFFFFF8);
10919       jccb(Assembler::zero, copy_tail);
10920 
10921       pmovzxbw(tmp1, Address(src, 0));
10922       movdqu(Address(dst, 0), tmp1);
10923       addptr(src, 8);
10924       addptr(dst, 2 * 8);
10925 
10926       jmp(copy_tail, true);
10927     }
10928 
10929     // inflate 8 chars per iter
10930     bind(copy_8_loop);
10931     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10932     movdqu(Address(dst, len, Address::times_2), tmp1);
10933     addptr(len, 8);
10934     jcc(Assembler::notZero, copy_8_loop);
10935 
10936     bind(copy_tail);
10937     movl(len, tmp2);
10938 
10939     cmpl(len, 4);
10940     jccb(Assembler::less, copy_bytes);
10941 
10942     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10943     pmovzxbw(tmp1, tmp1);
10944     movq(Address(dst, 0), tmp1);
10945     subptr(len, 4);
10946     addptr(src, 4);
10947     addptr(dst, 8);
10948 
10949     bind(copy_bytes);
10950   }
10951   testl(len, len);
10952   jccb(Assembler::zero, done);
10953   lea(src, Address(src, len, Address::times_1));
10954   lea(dst, Address(dst, len, Address::times_2));
10955   negptr(len);
10956 
10957   // inflate 1 char per iter
10958   bind(copy_chars_loop);
10959   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10960   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10961   increment(len);
10962   jcc(Assembler::notZero, copy_chars_loop);
10963 
10964   bind(done);
10965 }
10966 
10967 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10968   switch (cond) {
10969     // Note some conditions are synonyms for others
10970     case Assembler::zero:         return Assembler::notZero;
10971     case Assembler::notZero:      return Assembler::zero;
10972     case Assembler::less:         return Assembler::greaterEqual;
10973     case Assembler::lessEqual:    return Assembler::greater;
10974     case Assembler::greater:      return Assembler::lessEqual;
10975     case Assembler::greaterEqual: return Assembler::less;
10976     case Assembler::below:        return Assembler::aboveEqual;
10977     case Assembler::belowEqual:   return Assembler::above;
10978     case Assembler::above:        return Assembler::belowEqual;
10979     case Assembler::aboveEqual:   return Assembler::below;
10980     case Assembler::overflow:     return Assembler::noOverflow;
10981     case Assembler::noOverflow:   return Assembler::overflow;
10982     case Assembler::negative:     return Assembler::positive;
10983     case Assembler::positive:     return Assembler::negative;
10984     case Assembler::parity:       return Assembler::noParity;
10985     case Assembler::noParity:     return Assembler::parity;
10986   }
10987   ShouldNotReachHere(); return Assembler::overflow;
10988 }
10989 
10990 SkipIfEqual::SkipIfEqual(
10991     MacroAssembler* masm, const bool* flag_addr, bool value) {
10992   _masm = masm;
10993   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10994   _masm->jcc(Assembler::equal, _label);
10995 }
10996 
10997 SkipIfEqual::~SkipIfEqual() {
10998   _masm->bind(_label);
10999 }
11000 
11001 // 32-bit Windows has its own fast-path implementation
11002 // of get_thread
11003 #if !defined(WIN32) || defined(_LP64)
11004 
11005 // This is simply a call to Thread::current()
11006 void MacroAssembler::get_thread(Register thread) {
11007   if (thread != rax) {
11008     push(rax);
11009   }
11010   LP64_ONLY(push(rdi);)
11011   LP64_ONLY(push(rsi);)
11012   push(rdx);
11013   push(rcx);
11014 #ifdef _LP64
11015   push(r8);
11016   push(r9);
11017   push(r10);
11018   push(r11);
11019 #endif
11020 
11021   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11022 
11023 #ifdef _LP64
11024   pop(r11);
11025   pop(r10);
11026   pop(r9);
11027   pop(r8);
11028 #endif
11029   pop(rcx);
11030   pop(rdx);
11031   LP64_ONLY(pop(rsi);)
11032   LP64_ONLY(pop(rdi);)
11033   if (thread != rax) {
11034     mov(thread, rax);
11035     pop(rax);
11036   }
11037 }
11038 
11039 #endif