1 /*
   2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "asm/assembler.hpp"
  28 #include "asm/assembler.inline.hpp"
  29 #include "compiler/disassembler.hpp"
  30 #include "gc/shared/barrierSet.hpp"
  31 #include "gc/shared/barrierSetAssembler.hpp"
  32 #include "gc/shared/collectedHeap.inline.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "memory/universe.hpp"
  36 #include "oops/accessDecorators.hpp"
  37 #include "oops/klass.inline.hpp"
  38 #include "prims/methodHandles.hpp"
  39 #include "runtime/biasedLocking.hpp"
  40 #include "runtime/flags/flagSetting.hpp"
  41 #include "runtime/interfaceSupport.inline.hpp"
  42 #include "runtime/objectMonitor.hpp"
  43 #include "runtime/os.hpp"
  44 #include "runtime/safepoint.hpp"
  45 #include "runtime/safepointMechanism.hpp"
  46 #include "runtime/sharedRuntime.hpp"
  47 #include "runtime/stubRoutines.hpp"
  48 #include "runtime/thread.hpp"
  49 #include "utilities/macros.hpp"
  50 #include "crc32c.h"
  51 #ifdef COMPILER2
  52 #include "opto/intrinsicnode.hpp"
  53 #endif
  54 
  55 #ifdef PRODUCT
  56 #define BLOCK_COMMENT(str) /* nothing */
  57 #define STOP(error) stop(error)
  58 #else
  59 #define BLOCK_COMMENT(str) block_comment(str)
  60 #define STOP(error) block_comment(error); stop(error)
  61 #endif
  62 
  63 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  64 
  65 #ifdef ASSERT
  66 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  67 #endif
  68 
  69 static Assembler::Condition reverse[] = {
  70     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  71     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  72     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  73     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  74     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  75     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  76     Assembler::above          /* belowEqual    = 0x6 */ ,
  77     Assembler::belowEqual     /* above         = 0x7 */ ,
  78     Assembler::positive       /* negative      = 0x8 */ ,
  79     Assembler::negative       /* positive      = 0x9 */ ,
  80     Assembler::noParity       /* parity        = 0xa */ ,
  81     Assembler::parity         /* noParity      = 0xb */ ,
  82     Assembler::greaterEqual   /* less          = 0xc */ ,
  83     Assembler::less           /* greaterEqual  = 0xd */ ,
  84     Assembler::greater        /* lessEqual     = 0xe */ ,
  85     Assembler::lessEqual      /* greater       = 0xf, */
  86 
  87 };
  88 
  89 
  90 // Implementation of MacroAssembler
  91 
  92 // First all the versions that have distinct versions depending on 32/64 bit
  93 // Unless the difference is trivial (1 line or so).
  94 
  95 #ifndef _LP64
  96 
  97 // 32bit versions
  98 
  99 Address MacroAssembler::as_Address(AddressLiteral adr) {
 100   return Address(adr.target(), adr.rspec());
 101 }
 102 
 103 Address MacroAssembler::as_Address(ArrayAddress adr) {
 104   return Address::make_array(adr);
 105 }
 106 
 107 void MacroAssembler::call_VM_leaf_base(address entry_point,
 108                                        int number_of_arguments) {
 109   call(RuntimeAddress(entry_point));
 110   increment(rsp, number_of_arguments * wordSize);
 111 }
 112 
 113 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 114   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 115 }
 116 
 117 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 118   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 119 }
 120 
 121 void MacroAssembler::cmpoop(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::andpd(XMMRegister dst, AddressLiteral src) {
 997   // Used in sign-masking with aligned address.
 998   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 999   if (reachable(src)) {
1000     Assembler::andpd(dst, as_Address(src));
1001   } else {
1002     lea(rscratch1, src);
1003     Assembler::andpd(dst, Address(rscratch1, 0));
1004   }
1005 }
1006 
1007 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1008   // Used in sign-masking with aligned address.
1009   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1010   if (reachable(src)) {
1011     Assembler::andps(dst, as_Address(src));
1012   } else {
1013     lea(rscratch1, src);
1014     Assembler::andps(dst, Address(rscratch1, 0));
1015   }
1016 }
1017 
1018 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1019   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1020 }
1021 
1022 void MacroAssembler::atomic_incl(Address counter_addr) {
1023   if (os::is_MP())
1024     lock();
1025   incrementl(counter_addr);
1026 }
1027 
1028 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1029   if (reachable(counter_addr)) {
1030     atomic_incl(as_Address(counter_addr));
1031   } else {
1032     lea(scr, counter_addr);
1033     atomic_incl(Address(scr, 0));
1034   }
1035 }
1036 
1037 #ifdef _LP64
1038 void MacroAssembler::atomic_incq(Address counter_addr) {
1039   if (os::is_MP())
1040     lock();
1041   incrementq(counter_addr);
1042 }
1043 
1044 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1045   if (reachable(counter_addr)) {
1046     atomic_incq(as_Address(counter_addr));
1047   } else {
1048     lea(scr, counter_addr);
1049     atomic_incq(Address(scr, 0));
1050   }
1051 }
1052 #endif
1053 
1054 // Writes to stack successive pages until offset reached to check for
1055 // stack overflow + shadow pages.  This clobbers tmp.
1056 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1057   movptr(tmp, rsp);
1058   // Bang stack for total size given plus shadow page size.
1059   // Bang one page at a time because large size can bang beyond yellow and
1060   // red zones.
1061   Label loop;
1062   bind(loop);
1063   movl(Address(tmp, (-os::vm_page_size())), size );
1064   subptr(tmp, os::vm_page_size());
1065   subl(size, os::vm_page_size());
1066   jcc(Assembler::greater, loop);
1067 
1068   // Bang down shadow pages too.
1069   // At this point, (tmp-0) is the last address touched, so don't
1070   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1071   // was post-decremented.)  Skip this address by starting at i=1, and
1072   // touch a few more pages below.  N.B.  It is important to touch all
1073   // the way down including all pages in the shadow zone.
1074   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1075     // this could be any sized move but this is can be a debugging crumb
1076     // so the bigger the better.
1077     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1078   }
1079 }
1080 
1081 void MacroAssembler::reserved_stack_check() {
1082     // testing if reserved zone needs to be enabled
1083     Label no_reserved_zone_enabling;
1084     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1085     NOT_LP64(get_thread(rsi);)
1086 
1087     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1088     jcc(Assembler::below, no_reserved_zone_enabling);
1089 
1090     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1091     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1092     should_not_reach_here();
1093 
1094     bind(no_reserved_zone_enabling);
1095 }
1096 
1097 int MacroAssembler::biased_locking_enter(Register lock_reg,
1098                                          Register obj_reg,
1099                                          Register swap_reg,
1100                                          Register tmp_reg,
1101                                          bool swap_reg_contains_mark,
1102                                          Label& done,
1103                                          Label* slow_case,
1104                                          BiasedLockingCounters* counters) {
1105   assert(UseBiasedLocking, "why call this otherwise?");
1106   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1107   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1108   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1109   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1110   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1111   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1112 
1113   if (PrintBiasedLockingStatistics && counters == NULL) {
1114     counters = BiasedLocking::counters();
1115   }
1116   // Biased locking
1117   // See whether the lock is currently biased toward our thread and
1118   // whether the epoch is still valid
1119   // Note that the runtime guarantees sufficient alignment of JavaThread
1120   // pointers to allow age to be placed into low bits
1121   // First check to see whether biasing is even enabled for this object
1122   Label cas_label;
1123   int null_check_offset = -1;
1124   if (!swap_reg_contains_mark) {
1125     null_check_offset = offset();
1126     movptr(swap_reg, mark_addr);
1127   }
1128   movptr(tmp_reg, swap_reg);
1129   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1130   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1131   jcc(Assembler::notEqual, cas_label);
1132   // The bias pattern is present in the object's header. Need to check
1133   // whether the bias owner and the epoch are both still current.
1134 #ifndef _LP64
1135   // Note that because there is no current thread register on x86_32 we
1136   // need to store off the mark word we read out of the object to
1137   // avoid reloading it and needing to recheck invariants below. This
1138   // store is unfortunate but it makes the overall code shorter and
1139   // simpler.
1140   movptr(saved_mark_addr, swap_reg);
1141 #endif
1142   if (swap_reg_contains_mark) {
1143     null_check_offset = offset();
1144   }
1145   load_prototype_header(tmp_reg, obj_reg);
1146 #ifdef _LP64
1147   orptr(tmp_reg, r15_thread);
1148   xorptr(tmp_reg, swap_reg);
1149   Register header_reg = tmp_reg;
1150 #else
1151   xorptr(tmp_reg, swap_reg);
1152   get_thread(swap_reg);
1153   xorptr(swap_reg, tmp_reg);
1154   Register header_reg = swap_reg;
1155 #endif
1156   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1157   if (counters != NULL) {
1158     cond_inc32(Assembler::zero,
1159                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1160   }
1161   jcc(Assembler::equal, done);
1162 
1163   Label try_revoke_bias;
1164   Label try_rebias;
1165 
1166   // At this point we know that the header has the bias pattern and
1167   // that we are not the bias owner in the current epoch. We need to
1168   // figure out more details about the state of the header in order to
1169   // know what operations can be legally performed on the object's
1170   // header.
1171 
1172   // If the low three bits in the xor result aren't clear, that means
1173   // the prototype header is no longer biased and we have to revoke
1174   // the bias on this object.
1175   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1176   jccb(Assembler::notZero, try_revoke_bias);
1177 
1178   // Biasing is still enabled for this data type. See whether the
1179   // epoch of the current bias is still valid, meaning that the epoch
1180   // bits of the mark word are equal to the epoch bits of the
1181   // prototype header. (Note that the prototype header's epoch bits
1182   // only change at a safepoint.) If not, attempt to rebias the object
1183   // toward the current thread. Note that we must be absolutely sure
1184   // that the current epoch is invalid in order to do this because
1185   // otherwise the manipulations it performs on the mark word are
1186   // illegal.
1187   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1188   jccb(Assembler::notZero, try_rebias);
1189 
1190   // The epoch of the current bias is still valid but we know nothing
1191   // about the owner; it might be set or it might be clear. Try to
1192   // acquire the bias of the object using an atomic operation. If this
1193   // fails we will go in to the runtime to revoke the object's bias.
1194   // Note that we first construct the presumed unbiased header so we
1195   // don't accidentally blow away another thread's valid bias.
1196   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1197   andptr(swap_reg,
1198          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1199 #ifdef _LP64
1200   movptr(tmp_reg, swap_reg);
1201   orptr(tmp_reg, r15_thread);
1202 #else
1203   get_thread(tmp_reg);
1204   orptr(tmp_reg, swap_reg);
1205 #endif
1206   if (os::is_MP()) {
1207     lock();
1208   }
1209   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1210   // If the biasing toward our thread failed, this means that
1211   // another thread succeeded in biasing it toward itself and we
1212   // need to revoke that bias. The revocation will occur in the
1213   // interpreter runtime in the slow case.
1214   if (counters != NULL) {
1215     cond_inc32(Assembler::zero,
1216                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1217   }
1218   if (slow_case != NULL) {
1219     jcc(Assembler::notZero, *slow_case);
1220   }
1221   jmp(done);
1222 
1223   bind(try_rebias);
1224   // At this point we know the epoch has expired, meaning that the
1225   // current "bias owner", if any, is actually invalid. Under these
1226   // circumstances _only_, we are allowed to use the current header's
1227   // value as the comparison value when doing the cas to acquire the
1228   // bias in the current epoch. In other words, we allow transfer of
1229   // the bias from one thread to another directly in this situation.
1230   //
1231   // FIXME: due to a lack of registers we currently blow away the age
1232   // bits in this situation. Should attempt to preserve them.
1233   load_prototype_header(tmp_reg, obj_reg);
1234 #ifdef _LP64
1235   orptr(tmp_reg, r15_thread);
1236 #else
1237   get_thread(swap_reg);
1238   orptr(tmp_reg, swap_reg);
1239   movptr(swap_reg, saved_mark_addr);
1240 #endif
1241   if (os::is_MP()) {
1242     lock();
1243   }
1244   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1245   // If the biasing toward our thread failed, then another thread
1246   // succeeded in biasing it toward itself and we need to revoke that
1247   // bias. The revocation will occur in the runtime in the slow case.
1248   if (counters != NULL) {
1249     cond_inc32(Assembler::zero,
1250                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1251   }
1252   if (slow_case != NULL) {
1253     jcc(Assembler::notZero, *slow_case);
1254   }
1255   jmp(done);
1256 
1257   bind(try_revoke_bias);
1258   // The prototype mark in the klass doesn't have the bias bit set any
1259   // more, indicating that objects of this data type are not supposed
1260   // to be biased any more. We are going to try to reset the mark of
1261   // this object to the prototype value and fall through to the
1262   // CAS-based locking scheme. Note that if our CAS fails, it means
1263   // that another thread raced us for the privilege of revoking the
1264   // bias of this particular object, so it's okay to continue in the
1265   // normal locking code.
1266   //
1267   // FIXME: due to a lack of registers we currently blow away the age
1268   // bits in this situation. Should attempt to preserve them.
1269   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1270   load_prototype_header(tmp_reg, obj_reg);
1271   if (os::is_MP()) {
1272     lock();
1273   }
1274   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1275   // Fall through to the normal CAS-based lock, because no matter what
1276   // the result of the above CAS, some thread must have succeeded in
1277   // removing the bias bit from the object's header.
1278   if (counters != NULL) {
1279     cond_inc32(Assembler::zero,
1280                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1281   }
1282 
1283   bind(cas_label);
1284 
1285   return null_check_offset;
1286 }
1287 
1288 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1289   assert(UseBiasedLocking, "why call this otherwise?");
1290 
1291   // Check for biased locking unlock case, which is a no-op
1292   // Note: we do not have to check the thread ID for two reasons.
1293   // First, the interpreter checks for IllegalMonitorStateException at
1294   // a higher level. Second, if the bias was revoked while we held the
1295   // lock, the object could not be rebiased toward another thread, so
1296   // the bias bit would be clear.
1297   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1298   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1299   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1300   jcc(Assembler::equal, done);
1301 }
1302 
1303 #ifdef COMPILER2
1304 
1305 #if INCLUDE_RTM_OPT
1306 
1307 // Update rtm_counters based on abort status
1308 // input: abort_status
1309 //        rtm_counters (RTMLockingCounters*)
1310 // flags are killed
1311 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1312 
1313   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1314   if (PrintPreciseRTMLockingStatistics) {
1315     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1316       Label check_abort;
1317       testl(abort_status, (1<<i));
1318       jccb(Assembler::equal, check_abort);
1319       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1320       bind(check_abort);
1321     }
1322   }
1323 }
1324 
1325 // Branch if (random & (count-1) != 0), count is 2^n
1326 // tmp, scr and flags are killed
1327 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1328   assert(tmp == rax, "");
1329   assert(scr == rdx, "");
1330   rdtsc(); // modifies EDX:EAX
1331   andptr(tmp, count-1);
1332   jccb(Assembler::notZero, brLabel);
1333 }
1334 
1335 // Perform abort ratio calculation, set no_rtm bit if high ratio
1336 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1337 // tmpReg, rtm_counters_Reg and flags are killed
1338 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1339                                                  Register rtm_counters_Reg,
1340                                                  RTMLockingCounters* rtm_counters,
1341                                                  Metadata* method_data) {
1342   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1343 
1344   if (RTMLockingCalculationDelay > 0) {
1345     // Delay calculation
1346     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1347     testptr(tmpReg, tmpReg);
1348     jccb(Assembler::equal, L_done);
1349   }
1350   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1351   //   Aborted transactions = abort_count * 100
1352   //   All transactions = total_count *  RTMTotalCountIncrRate
1353   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1354 
1355   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1356   cmpptr(tmpReg, RTMAbortThreshold);
1357   jccb(Assembler::below, L_check_always_rtm2);
1358   imulptr(tmpReg, tmpReg, 100);
1359 
1360   Register scrReg = rtm_counters_Reg;
1361   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1362   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1363   imulptr(scrReg, scrReg, RTMAbortRatio);
1364   cmpptr(tmpReg, scrReg);
1365   jccb(Assembler::below, L_check_always_rtm1);
1366   if (method_data != NULL) {
1367     // set rtm_state to "no rtm" in MDO
1368     mov_metadata(tmpReg, method_data);
1369     if (os::is_MP()) {
1370       lock();
1371     }
1372     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1373   }
1374   jmpb(L_done);
1375   bind(L_check_always_rtm1);
1376   // Reload RTMLockingCounters* address
1377   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1378   bind(L_check_always_rtm2);
1379   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1380   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1381   jccb(Assembler::below, L_done);
1382   if (method_data != NULL) {
1383     // set rtm_state to "always rtm" in MDO
1384     mov_metadata(tmpReg, method_data);
1385     if (os::is_MP()) {
1386       lock();
1387     }
1388     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1389   }
1390   bind(L_done);
1391 }
1392 
1393 // Update counters and perform abort ratio calculation
1394 // input:  abort_status_Reg
1395 // rtm_counters_Reg, flags are killed
1396 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1397                                    Register rtm_counters_Reg,
1398                                    RTMLockingCounters* rtm_counters,
1399                                    Metadata* method_data,
1400                                    bool profile_rtm) {
1401 
1402   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1403   // update rtm counters based on rax value at abort
1404   // reads abort_status_Reg, updates flags
1405   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1406   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1407   if (profile_rtm) {
1408     // Save abort status because abort_status_Reg is used by following code.
1409     if (RTMRetryCount > 0) {
1410       push(abort_status_Reg);
1411     }
1412     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1413     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1414     // restore abort status
1415     if (RTMRetryCount > 0) {
1416       pop(abort_status_Reg);
1417     }
1418   }
1419 }
1420 
1421 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1422 // inputs: retry_count_Reg
1423 //       : abort_status_Reg
1424 // output: retry_count_Reg decremented by 1
1425 // flags are killed
1426 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1427   Label doneRetry;
1428   assert(abort_status_Reg == rax, "");
1429   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1430   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1431   // if reason is in 0x6 and retry count != 0 then retry
1432   andptr(abort_status_Reg, 0x6);
1433   jccb(Assembler::zero, doneRetry);
1434   testl(retry_count_Reg, retry_count_Reg);
1435   jccb(Assembler::zero, doneRetry);
1436   pause();
1437   decrementl(retry_count_Reg);
1438   jmp(retryLabel);
1439   bind(doneRetry);
1440 }
1441 
1442 // Spin and retry if lock is busy,
1443 // inputs: box_Reg (monitor address)
1444 //       : retry_count_Reg
1445 // output: retry_count_Reg decremented by 1
1446 //       : clear z flag if retry count exceeded
1447 // tmp_Reg, scr_Reg, flags are killed
1448 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1449                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1450   Label SpinLoop, SpinExit, doneRetry;
1451   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1452 
1453   testl(retry_count_Reg, retry_count_Reg);
1454   jccb(Assembler::zero, doneRetry);
1455   decrementl(retry_count_Reg);
1456   movptr(scr_Reg, RTMSpinLoopCount);
1457 
1458   bind(SpinLoop);
1459   pause();
1460   decrementl(scr_Reg);
1461   jccb(Assembler::lessEqual, SpinExit);
1462   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1463   testptr(tmp_Reg, tmp_Reg);
1464   jccb(Assembler::notZero, SpinLoop);
1465 
1466   bind(SpinExit);
1467   jmp(retryLabel);
1468   bind(doneRetry);
1469   incrementl(retry_count_Reg); // clear z flag
1470 }
1471 
1472 // Use RTM for normal stack locks
1473 // Input: objReg (object to lock)
1474 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1475                                        Register retry_on_abort_count_Reg,
1476                                        RTMLockingCounters* stack_rtm_counters,
1477                                        Metadata* method_data, bool profile_rtm,
1478                                        Label& DONE_LABEL, Label& IsInflated) {
1479   assert(UseRTMForStackLocks, "why call this otherwise?");
1480   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1481   assert(tmpReg == rax, "");
1482   assert(scrReg == rdx, "");
1483   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1484 
1485   if (RTMRetryCount > 0) {
1486     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1487     bind(L_rtm_retry);
1488   }
1489   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1490   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1491   jcc(Assembler::notZero, IsInflated);
1492 
1493   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1494     Label L_noincrement;
1495     if (RTMTotalCountIncrRate > 1) {
1496       // tmpReg, scrReg and flags are killed
1497       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1498     }
1499     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1500     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1501     bind(L_noincrement);
1502   }
1503   xbegin(L_on_abort);
1504   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1505   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1506   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1507   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1508 
1509   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1510   if (UseRTMXendForLockBusy) {
1511     xend();
1512     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1513     jmp(L_decrement_retry);
1514   }
1515   else {
1516     xabort(0);
1517   }
1518   bind(L_on_abort);
1519   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1520     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1521   }
1522   bind(L_decrement_retry);
1523   if (RTMRetryCount > 0) {
1524     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1525     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1526   }
1527 }
1528 
1529 // Use RTM for inflating locks
1530 // inputs: objReg (object to lock)
1531 //         boxReg (on-stack box address (displaced header location) - KILLED)
1532 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1533 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1534                                           Register scrReg, Register retry_on_busy_count_Reg,
1535                                           Register retry_on_abort_count_Reg,
1536                                           RTMLockingCounters* rtm_counters,
1537                                           Metadata* method_data, bool profile_rtm,
1538                                           Label& DONE_LABEL) {
1539   assert(UseRTMLocking, "why call this otherwise?");
1540   assert(tmpReg == rax, "");
1541   assert(scrReg == rdx, "");
1542   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1543   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1544 
1545   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1546   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1547   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1548 
1549   if (RTMRetryCount > 0) {
1550     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1551     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1552     bind(L_rtm_retry);
1553   }
1554   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1555     Label L_noincrement;
1556     if (RTMTotalCountIncrRate > 1) {
1557       // tmpReg, scrReg and flags are killed
1558       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1559     }
1560     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1561     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1562     bind(L_noincrement);
1563   }
1564   xbegin(L_on_abort);
1565   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1566   movptr(tmpReg, Address(tmpReg, owner_offset));
1567   testptr(tmpReg, tmpReg);
1568   jcc(Assembler::zero, DONE_LABEL);
1569   if (UseRTMXendForLockBusy) {
1570     xend();
1571     jmp(L_decrement_retry);
1572   }
1573   else {
1574     xabort(0);
1575   }
1576   bind(L_on_abort);
1577   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1578   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1579     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1580   }
1581   if (RTMRetryCount > 0) {
1582     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1583     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1584   }
1585 
1586   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1587   testptr(tmpReg, tmpReg) ;
1588   jccb(Assembler::notZero, L_decrement_retry) ;
1589 
1590   // Appears unlocked - try to swing _owner from null to non-null.
1591   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1592 #ifdef _LP64
1593   Register threadReg = r15_thread;
1594 #else
1595   get_thread(scrReg);
1596   Register threadReg = scrReg;
1597 #endif
1598   if (os::is_MP()) {
1599     lock();
1600   }
1601   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1602 
1603   if (RTMRetryCount > 0) {
1604     // success done else retry
1605     jccb(Assembler::equal, DONE_LABEL) ;
1606     bind(L_decrement_retry);
1607     // Spin and retry if lock is busy.
1608     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1609   }
1610   else {
1611     bind(L_decrement_retry);
1612   }
1613 }
1614 
1615 #endif //  INCLUDE_RTM_OPT
1616 
1617 // Fast_Lock and Fast_Unlock used by C2
1618 
1619 // Because the transitions from emitted code to the runtime
1620 // monitorenter/exit helper stubs are so slow it's critical that
1621 // we inline both the stack-locking fast-path and the inflated fast path.
1622 //
1623 // See also: cmpFastLock and cmpFastUnlock.
1624 //
1625 // What follows is a specialized inline transliteration of the code
1626 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1627 // another option would be to emit TrySlowEnter and TrySlowExit methods
1628 // at startup-time.  These methods would accept arguments as
1629 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1630 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1631 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1632 // In practice, however, the # of lock sites is bounded and is usually small.
1633 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1634 // if the processor uses simple bimodal branch predictors keyed by EIP
1635 // Since the helper routines would be called from multiple synchronization
1636 // sites.
1637 //
1638 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1639 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1640 // to those specialized methods.  That'd give us a mostly platform-independent
1641 // implementation that the JITs could optimize and inline at their pleasure.
1642 // Done correctly, the only time we'd need to cross to native could would be
1643 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1644 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1645 // (b) explicit barriers or fence operations.
1646 //
1647 // TODO:
1648 //
1649 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1650 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1651 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1652 //    the lock operators would typically be faster than reifying Self.
1653 //
1654 // *  Ideally I'd define the primitives as:
1655 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1656 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1657 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1658 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1659 //    Furthermore the register assignments are overconstrained, possibly resulting in
1660 //    sub-optimal code near the synchronization site.
1661 //
1662 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1663 //    Alternately, use a better sp-proximity test.
1664 //
1665 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1666 //    Either one is sufficient to uniquely identify a thread.
1667 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1668 //
1669 // *  Intrinsify notify() and notifyAll() for the common cases where the
1670 //    object is locked by the calling thread but the waitlist is empty.
1671 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1672 //
1673 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1674 //    But beware of excessive branch density on AMD Opterons.
1675 //
1676 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1677 //    or failure of the fast-path.  If the fast-path fails then we pass
1678 //    control to the slow-path, typically in C.  In Fast_Lock and
1679 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1680 //    will emit a conditional branch immediately after the node.
1681 //    So we have branches to branches and lots of ICC.ZF games.
1682 //    Instead, it might be better to have C2 pass a "FailureLabel"
1683 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1684 //    will drop through the node.  ICC.ZF is undefined at exit.
1685 //    In the case of failure, the node will branch directly to the
1686 //    FailureLabel
1687 
1688 
1689 // obj: object to lock
1690 // box: on-stack box address (displaced header location) - KILLED
1691 // rax,: tmp -- KILLED
1692 // scr: tmp -- KILLED
1693 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1694                                Register scrReg, Register cx1Reg, Register cx2Reg,
1695                                BiasedLockingCounters* counters,
1696                                RTMLockingCounters* rtm_counters,
1697                                RTMLockingCounters* stack_rtm_counters,
1698                                Metadata* method_data,
1699                                bool use_rtm, bool profile_rtm) {
1700   // Ensure the register assignments are disjoint
1701   assert(tmpReg == rax, "");
1702 
1703   if (use_rtm) {
1704     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1705   } else {
1706     assert(cx1Reg == noreg, "");
1707     assert(cx2Reg == noreg, "");
1708     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1709   }
1710 
1711   if (counters != NULL) {
1712     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1713   }
1714   if (EmitSync & 1) {
1715       // set box->dhw = markOopDesc::unused_mark()
1716       // Force all sync thru slow-path: slow_enter() and slow_exit()
1717       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1718       cmpptr (rsp, (int32_t)NULL_WORD);
1719   } else {
1720     // Possible cases that we'll encounter in fast_lock
1721     // ------------------------------------------------
1722     // * Inflated
1723     //    -- unlocked
1724     //    -- Locked
1725     //       = by self
1726     //       = by other
1727     // * biased
1728     //    -- by Self
1729     //    -- by other
1730     // * neutral
1731     // * stack-locked
1732     //    -- by self
1733     //       = sp-proximity test hits
1734     //       = sp-proximity test generates false-negative
1735     //    -- by other
1736     //
1737 
1738     Label IsInflated, DONE_LABEL;
1739 
1740     // it's stack-locked, biased or neutral
1741     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1742     // order to reduce the number of conditional branches in the most common cases.
1743     // Beware -- there's a subtle invariant that fetch of the markword
1744     // at [FETCH], below, will never observe a biased encoding (*101b).
1745     // If this invariant is not held we risk exclusion (safety) failure.
1746     if (UseBiasedLocking && !UseOptoBiasInlining) {
1747       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1748     }
1749 
1750 #if INCLUDE_RTM_OPT
1751     if (UseRTMForStackLocks && use_rtm) {
1752       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1753                         stack_rtm_counters, method_data, profile_rtm,
1754                         DONE_LABEL, IsInflated);
1755     }
1756 #endif // INCLUDE_RTM_OPT
1757 
1758     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1759     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1760     jccb(Assembler::notZero, IsInflated);
1761 
1762     // Attempt stack-locking ...
1763     orptr (tmpReg, markOopDesc::unlocked_value);
1764     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1765     if (os::is_MP()) {
1766       lock();
1767     }
1768     cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1769     if (counters != NULL) {
1770       cond_inc32(Assembler::equal,
1771                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1772     }
1773     jcc(Assembler::equal, DONE_LABEL);           // Success
1774 
1775     // Recursive locking.
1776     // The object is stack-locked: markword contains stack pointer to BasicLock.
1777     // Locked by current thread if difference with current SP is less than one page.
1778     subptr(tmpReg, rsp);
1779     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1780     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1781     movptr(Address(boxReg, 0), tmpReg);
1782     if (counters != NULL) {
1783       cond_inc32(Assembler::equal,
1784                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1785     }
1786     jmp(DONE_LABEL);
1787 
1788     bind(IsInflated);
1789     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1790 
1791 #if INCLUDE_RTM_OPT
1792     // Use the same RTM locking code in 32- and 64-bit VM.
1793     if (use_rtm) {
1794       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1795                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1796     } else {
1797 #endif // INCLUDE_RTM_OPT
1798 
1799 #ifndef _LP64
1800     // The object is inflated.
1801 
1802     // boxReg refers to the on-stack BasicLock in the current frame.
1803     // We'd like to write:
1804     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1805     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1806     // additional latency as we have another ST in the store buffer that must drain.
1807 
1808     if (EmitSync & 8192) {
1809        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1810        get_thread (scrReg);
1811        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1812        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1813        if (os::is_MP()) {
1814          lock();
1815        }
1816        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1817     } else
1818     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1819        // register juggle because we need tmpReg for cmpxchgptr below
1820        movptr(scrReg, boxReg);
1821        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1822 
1823        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1824        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1825           // prefetchw [eax + Offset(_owner)-2]
1826           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1827        }
1828 
1829        if ((EmitSync & 64) == 0) {
1830          // Optimistic form: consider XORL tmpReg,tmpReg
1831          movptr(tmpReg, NULL_WORD);
1832        } else {
1833          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1834          // Test-And-CAS instead of CAS
1835          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1836          testptr(tmpReg, tmpReg);                   // Locked ?
1837          jccb  (Assembler::notZero, DONE_LABEL);
1838        }
1839 
1840        // Appears unlocked - try to swing _owner from null to non-null.
1841        // Ideally, I'd manifest "Self" with get_thread and then attempt
1842        // to CAS the register containing Self into m->Owner.
1843        // But we don't have enough registers, so instead we can either try to CAS
1844        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1845        // we later store "Self" into m->Owner.  Transiently storing a stack address
1846        // (rsp or the address of the box) into  m->owner is harmless.
1847        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1848        if (os::is_MP()) {
1849          lock();
1850        }
1851        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1852        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1853        // If we weren't able to swing _owner from NULL to the BasicLock
1854        // then take the slow path.
1855        jccb  (Assembler::notZero, DONE_LABEL);
1856        // update _owner from BasicLock to thread
1857        get_thread (scrReg);                    // beware: clobbers ICCs
1858        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1859        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1860 
1861        // If the CAS fails we can either retry or pass control to the slow-path.
1862        // We use the latter tactic.
1863        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1864        // If the CAS was successful ...
1865        //   Self has acquired the lock
1866        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1867        // Intentional fall-through into DONE_LABEL ...
1868     } else {
1869        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1870        movptr(boxReg, tmpReg);
1871 
1872        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1873        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1874           // prefetchw [eax + Offset(_owner)-2]
1875           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1876        }
1877 
1878        if ((EmitSync & 64) == 0) {
1879          // Optimistic form
1880          xorptr  (tmpReg, tmpReg);
1881        } else {
1882          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1883          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1884          testptr(tmpReg, tmpReg);                   // Locked ?
1885          jccb  (Assembler::notZero, DONE_LABEL);
1886        }
1887 
1888        // Appears unlocked - try to swing _owner from null to non-null.
1889        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1890        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1891        get_thread (scrReg);
1892        if (os::is_MP()) {
1893          lock();
1894        }
1895        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1896 
1897        // If the CAS fails we can either retry or pass control to the slow-path.
1898        // We use the latter tactic.
1899        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1900        // If the CAS was successful ...
1901        //   Self has acquired the lock
1902        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1903        // Intentional fall-through into DONE_LABEL ...
1904     }
1905 #else // _LP64
1906     // It's inflated
1907     movq(scrReg, tmpReg);
1908     xorq(tmpReg, tmpReg);
1909 
1910     if (os::is_MP()) {
1911       lock();
1912     }
1913     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1914     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1915     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1916     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1917     // Intentional fall-through into DONE_LABEL ...
1918     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1919 #endif // _LP64
1920 #if INCLUDE_RTM_OPT
1921     } // use_rtm()
1922 #endif
1923     // DONE_LABEL is a hot target - we'd really like to place it at the
1924     // start of cache line by padding with NOPs.
1925     // See the AMD and Intel software optimization manuals for the
1926     // most efficient "long" NOP encodings.
1927     // Unfortunately none of our alignment mechanisms suffice.
1928     bind(DONE_LABEL);
1929 
1930     // At DONE_LABEL the icc ZFlag is set as follows ...
1931     // Fast_Unlock uses the same protocol.
1932     // ZFlag == 1 -> Success
1933     // ZFlag == 0 -> Failure - force control through the slow-path
1934   }
1935 }
1936 
1937 // obj: object to unlock
1938 // box: box address (displaced header location), killed.  Must be EAX.
1939 // tmp: killed, cannot be obj nor box.
1940 //
1941 // Some commentary on balanced locking:
1942 //
1943 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1944 // Methods that don't have provably balanced locking are forced to run in the
1945 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1946 // The interpreter provides two properties:
1947 // I1:  At return-time the interpreter automatically and quietly unlocks any
1948 //      objects acquired the current activation (frame).  Recall that the
1949 //      interpreter maintains an on-stack list of locks currently held by
1950 //      a frame.
1951 // I2:  If a method attempts to unlock an object that is not held by the
1952 //      the frame the interpreter throws IMSX.
1953 //
1954 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1955 // B() doesn't have provably balanced locking so it runs in the interpreter.
1956 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1957 // is still locked by A().
1958 //
1959 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1960 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1961 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1962 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1963 // Arguably given that the spec legislates the JNI case as undefined our implementation
1964 // could reasonably *avoid* checking owner in Fast_Unlock().
1965 // In the interest of performance we elide m->Owner==Self check in unlock.
1966 // A perfectly viable alternative is to elide the owner check except when
1967 // Xcheck:jni is enabled.
1968 
1969 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1970   assert(boxReg == rax, "");
1971   assert_different_registers(objReg, boxReg, tmpReg);
1972 
1973   if (EmitSync & 4) {
1974     // Disable - inhibit all inlining.  Force control through the slow-path
1975     cmpptr (rsp, 0);
1976   } else {
1977     Label DONE_LABEL, Stacked, CheckSucc;
1978 
1979     // Critically, the biased locking test must have precedence over
1980     // and appear before the (box->dhw == 0) recursive stack-lock test.
1981     if (UseBiasedLocking && !UseOptoBiasInlining) {
1982        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1983     }
1984 
1985 #if INCLUDE_RTM_OPT
1986     if (UseRTMForStackLocks && use_rtm) {
1987       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1988       Label L_regular_unlock;
1989       movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
1990       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1991       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1992       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1993       xend();                                       // otherwise end...
1994       jmp(DONE_LABEL);                              // ... and we're done
1995       bind(L_regular_unlock);
1996     }
1997 #endif
1998 
1999     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
2000     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2001     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
2002     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2003     jccb  (Assembler::zero, Stacked);
2004 
2005     // It's inflated.
2006 #if INCLUDE_RTM_OPT
2007     if (use_rtm) {
2008       Label L_regular_inflated_unlock;
2009       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2010       movptr(boxReg, Address(tmpReg, owner_offset));
2011       testptr(boxReg, boxReg);
2012       jccb(Assembler::notZero, L_regular_inflated_unlock);
2013       xend();
2014       jmpb(DONE_LABEL);
2015       bind(L_regular_inflated_unlock);
2016     }
2017 #endif
2018 
2019     // Despite our balanced locking property we still check that m->_owner == Self
2020     // as java routines or native JNI code called by this thread might
2021     // have released the lock.
2022     // Refer to the comments in synchronizer.cpp for how we might encode extra
2023     // state in _succ so we can avoid fetching EntryList|cxq.
2024     //
2025     // I'd like to add more cases in fast_lock() and fast_unlock() --
2026     // such as recursive enter and exit -- but we have to be wary of
2027     // I$ bloat, T$ effects and BP$ effects.
2028     //
2029     // If there's no contention try a 1-0 exit.  That is, exit without
2030     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2031     // we detect and recover from the race that the 1-0 exit admits.
2032     //
2033     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2034     // before it STs null into _owner, releasing the lock.  Updates
2035     // to data protected by the critical section must be visible before
2036     // we drop the lock (and thus before any other thread could acquire
2037     // the lock and observe the fields protected by the lock).
2038     // IA32's memory-model is SPO, so STs are ordered with respect to
2039     // each other and there's no need for an explicit barrier (fence).
2040     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2041 #ifndef _LP64
2042     get_thread (boxReg);
2043     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2044       // prefetchw [ebx + Offset(_owner)-2]
2045       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2046     }
2047 
2048     // Note that we could employ various encoding schemes to reduce
2049     // the number of loads below (currently 4) to just 2 or 3.
2050     // Refer to the comments in synchronizer.cpp.
2051     // In practice the chain of fetches doesn't seem to impact performance, however.
2052     xorptr(boxReg, boxReg);
2053     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2054        // Attempt to reduce branch density - AMD's branch predictor.
2055        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2056        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2057        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2058        jccb  (Assembler::notZero, DONE_LABEL);
2059        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2060        jmpb  (DONE_LABEL);
2061     } else {
2062        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2063        jccb  (Assembler::notZero, DONE_LABEL);
2064        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2065        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2066        jccb  (Assembler::notZero, CheckSucc);
2067        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2068        jmpb  (DONE_LABEL);
2069     }
2070 
2071     // The Following code fragment (EmitSync & 65536) improves the performance of
2072     // contended applications and contended synchronization microbenchmarks.
2073     // Unfortunately the emission of the code - even though not executed - causes regressions
2074     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2075     // with an equal number of never-executed NOPs results in the same regression.
2076     // We leave it off by default.
2077 
2078     if ((EmitSync & 65536) != 0) {
2079        Label LSuccess, LGoSlowPath ;
2080 
2081        bind  (CheckSucc);
2082 
2083        // Optional pre-test ... it's safe to elide this
2084        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2085        jccb(Assembler::zero, LGoSlowPath);
2086 
2087        // We have a classic Dekker-style idiom:
2088        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2089        // There are a number of ways to implement the barrier:
2090        // (1) lock:andl &m->_owner, 0
2091        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2092        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2093        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2094        // (2) If supported, an explicit MFENCE is appealing.
2095        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2096        //     particularly if the write-buffer is full as might be the case if
2097        //     if stores closely precede the fence or fence-equivalent instruction.
2098        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2099        //     as the situation has changed with Nehalem and Shanghai.
2100        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2101        //     The $lines underlying the top-of-stack should be in M-state.
2102        //     The locked add instruction is serializing, of course.
2103        // (4) Use xchg, which is serializing
2104        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2105        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2106        //     The integer condition codes will tell us if succ was 0.
2107        //     Since _succ and _owner should reside in the same $line and
2108        //     we just stored into _owner, it's likely that the $line
2109        //     remains in M-state for the lock:orl.
2110        //
2111        // We currently use (3), although it's likely that switching to (2)
2112        // is correct for the future.
2113 
2114        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2115        if (os::is_MP()) {
2116          lock(); addptr(Address(rsp, 0), 0);
2117        }
2118        // Ratify _succ remains non-null
2119        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2120        jccb  (Assembler::notZero, LSuccess);
2121 
2122        xorptr(boxReg, boxReg);                  // box is really EAX
2123        if (os::is_MP()) { lock(); }
2124        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2125        // There's no successor so we tried to regrab the lock with the
2126        // placeholder value. If that didn't work, then another thread
2127        // grabbed the lock so we're done (and exit was a success).
2128        jccb  (Assembler::notEqual, LSuccess);
2129        // Since we're low on registers we installed rsp as a placeholding in _owner.
2130        // Now install Self over rsp.  This is safe as we're transitioning from
2131        // non-null to non=null
2132        get_thread (boxReg);
2133        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2134        // Intentional fall-through into LGoSlowPath ...
2135 
2136        bind  (LGoSlowPath);
2137        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2138        jmpb  (DONE_LABEL);
2139 
2140        bind  (LSuccess);
2141        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2142        jmpb  (DONE_LABEL);
2143     }
2144 
2145     bind (Stacked);
2146     // It's not inflated and it's not recursively stack-locked and it's not biased.
2147     // It must be stack-locked.
2148     // Try to reset the header to displaced header.
2149     // The "box" value on the stack is stable, so we can reload
2150     // and be assured we observe the same value as above.
2151     movptr(tmpReg, Address(boxReg, 0));
2152     if (os::is_MP()) {
2153       lock();
2154     }
2155     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2156     // Intention fall-thru into DONE_LABEL
2157 
2158     // DONE_LABEL is a hot target - we'd really like to place it at the
2159     // start of cache line by padding with NOPs.
2160     // See the AMD and Intel software optimization manuals for the
2161     // most efficient "long" NOP encodings.
2162     // Unfortunately none of our alignment mechanisms suffice.
2163     if ((EmitSync & 65536) == 0) {
2164        bind (CheckSucc);
2165     }
2166 #else // _LP64
2167     // It's inflated
2168     if (EmitSync & 1024) {
2169       // Emit code to check that _owner == Self
2170       // We could fold the _owner test into subsequent code more efficiently
2171       // than using a stand-alone check, but since _owner checking is off by
2172       // default we don't bother. We also might consider predicating the
2173       // _owner==Self check on Xcheck:jni or running on a debug build.
2174       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2175       xorptr(boxReg, r15_thread);
2176     } else {
2177       xorptr(boxReg, boxReg);
2178     }
2179     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2180     jccb  (Assembler::notZero, DONE_LABEL);
2181     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2182     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2183     jccb  (Assembler::notZero, CheckSucc);
2184     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2185     jmpb  (DONE_LABEL);
2186 
2187     if ((EmitSync & 65536) == 0) {
2188       // Try to avoid passing control into the slow_path ...
2189       Label LSuccess, LGoSlowPath ;
2190       bind  (CheckSucc);
2191 
2192       // The following optional optimization can be elided if necessary
2193       // Effectively: if (succ == null) goto SlowPath
2194       // The code reduces the window for a race, however,
2195       // and thus benefits performance.
2196       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2197       jccb  (Assembler::zero, LGoSlowPath);
2198 
2199       xorptr(boxReg, boxReg);
2200       if ((EmitSync & 16) && os::is_MP()) {
2201         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2202       } else {
2203         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2204         if (os::is_MP()) {
2205           // Memory barrier/fence
2206           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2207           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2208           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2209           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2210           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2211           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2212           lock(); addl(Address(rsp, 0), 0);
2213         }
2214       }
2215       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2216       jccb  (Assembler::notZero, LSuccess);
2217 
2218       // Rare inopportune interleaving - race.
2219       // The successor vanished in the small window above.
2220       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2221       // We need to ensure progress and succession.
2222       // Try to reacquire the lock.
2223       // If that fails then the new owner is responsible for succession and this
2224       // thread needs to take no further action and can exit via the fast path (success).
2225       // If the re-acquire succeeds then pass control into the slow path.
2226       // As implemented, this latter mode is horrible because we generated more
2227       // coherence traffic on the lock *and* artifically extended the critical section
2228       // length while by virtue of passing control into the slow path.
2229 
2230       // box is really RAX -- the following CMPXCHG depends on that binding
2231       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2232       if (os::is_MP()) { lock(); }
2233       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2234       // There's no successor so we tried to regrab the lock.
2235       // If that didn't work, then another thread grabbed the
2236       // lock so we're done (and exit was a success).
2237       jccb  (Assembler::notEqual, LSuccess);
2238       // Intentional fall-through into slow-path
2239 
2240       bind  (LGoSlowPath);
2241       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2242       jmpb  (DONE_LABEL);
2243 
2244       bind  (LSuccess);
2245       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2246       jmpb  (DONE_LABEL);
2247     }
2248 
2249     bind  (Stacked);
2250     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2251     if (os::is_MP()) { lock(); }
2252     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2253 
2254     if (EmitSync & 65536) {
2255        bind (CheckSucc);
2256     }
2257 #endif
2258     bind(DONE_LABEL);
2259   }
2260 }
2261 #endif // COMPILER2
2262 
2263 void MacroAssembler::c2bool(Register x) {
2264   // implements x == 0 ? 0 : 1
2265   // note: must only look at least-significant byte of x
2266   //       since C-style booleans are stored in one byte
2267   //       only! (was bug)
2268   andl(x, 0xFF);
2269   setb(Assembler::notZero, x);
2270 }
2271 
2272 // Wouldn't need if AddressLiteral version had new name
2273 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2274   Assembler::call(L, rtype);
2275 }
2276 
2277 void MacroAssembler::call(Register entry) {
2278   Assembler::call(entry);
2279 }
2280 
2281 void MacroAssembler::call(AddressLiteral entry) {
2282   if (reachable(entry)) {
2283     Assembler::call_literal(entry.target(), entry.rspec());
2284   } else {
2285     lea(rscratch1, entry);
2286     Assembler::call(rscratch1);
2287   }
2288 }
2289 
2290 void MacroAssembler::ic_call(address entry, jint method_index) {
2291   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2292   movptr(rax, (intptr_t)Universe::non_oop_word());
2293   call(AddressLiteral(entry, rh));
2294 }
2295 
2296 // Implementation of call_VM versions
2297 
2298 void MacroAssembler::call_VM(Register oop_result,
2299                              address entry_point,
2300                              bool check_exceptions) {
2301   Label C, E;
2302   call(C, relocInfo::none);
2303   jmp(E);
2304 
2305   bind(C);
2306   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2307   ret(0);
2308 
2309   bind(E);
2310 }
2311 
2312 void MacroAssembler::call_VM(Register oop_result,
2313                              address entry_point,
2314                              Register arg_1,
2315                              bool check_exceptions) {
2316   Label C, E;
2317   call(C, relocInfo::none);
2318   jmp(E);
2319 
2320   bind(C);
2321   pass_arg1(this, arg_1);
2322   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2323   ret(0);
2324 
2325   bind(E);
2326 }
2327 
2328 void MacroAssembler::call_VM(Register oop_result,
2329                              address entry_point,
2330                              Register arg_1,
2331                              Register arg_2,
2332                              bool check_exceptions) {
2333   Label C, E;
2334   call(C, relocInfo::none);
2335   jmp(E);
2336 
2337   bind(C);
2338 
2339   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2340 
2341   pass_arg2(this, arg_2);
2342   pass_arg1(this, arg_1);
2343   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2344   ret(0);
2345 
2346   bind(E);
2347 }
2348 
2349 void MacroAssembler::call_VM(Register oop_result,
2350                              address entry_point,
2351                              Register arg_1,
2352                              Register arg_2,
2353                              Register arg_3,
2354                              bool check_exceptions) {
2355   Label C, E;
2356   call(C, relocInfo::none);
2357   jmp(E);
2358 
2359   bind(C);
2360 
2361   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2362   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2363   pass_arg3(this, arg_3);
2364 
2365   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2366   pass_arg2(this, arg_2);
2367 
2368   pass_arg1(this, arg_1);
2369   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2370   ret(0);
2371 
2372   bind(E);
2373 }
2374 
2375 void MacroAssembler::call_VM(Register oop_result,
2376                              Register last_java_sp,
2377                              address entry_point,
2378                              int number_of_arguments,
2379                              bool check_exceptions) {
2380   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2381   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2382 }
2383 
2384 void MacroAssembler::call_VM(Register oop_result,
2385                              Register last_java_sp,
2386                              address entry_point,
2387                              Register arg_1,
2388                              bool check_exceptions) {
2389   pass_arg1(this, arg_1);
2390   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2391 }
2392 
2393 void MacroAssembler::call_VM(Register oop_result,
2394                              Register last_java_sp,
2395                              address entry_point,
2396                              Register arg_1,
2397                              Register arg_2,
2398                              bool check_exceptions) {
2399 
2400   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2401   pass_arg2(this, arg_2);
2402   pass_arg1(this, arg_1);
2403   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2404 }
2405 
2406 void MacroAssembler::call_VM(Register oop_result,
2407                              Register last_java_sp,
2408                              address entry_point,
2409                              Register arg_1,
2410                              Register arg_2,
2411                              Register arg_3,
2412                              bool check_exceptions) {
2413   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2414   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2415   pass_arg3(this, arg_3);
2416   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2417   pass_arg2(this, arg_2);
2418   pass_arg1(this, arg_1);
2419   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2420 }
2421 
2422 void MacroAssembler::super_call_VM(Register oop_result,
2423                                    Register last_java_sp,
2424                                    address entry_point,
2425                                    int number_of_arguments,
2426                                    bool check_exceptions) {
2427   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2428   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2429 }
2430 
2431 void MacroAssembler::super_call_VM(Register oop_result,
2432                                    Register last_java_sp,
2433                                    address entry_point,
2434                                    Register arg_1,
2435                                    bool check_exceptions) {
2436   pass_arg1(this, arg_1);
2437   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2438 }
2439 
2440 void MacroAssembler::super_call_VM(Register oop_result,
2441                                    Register last_java_sp,
2442                                    address entry_point,
2443                                    Register arg_1,
2444                                    Register arg_2,
2445                                    bool check_exceptions) {
2446 
2447   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2448   pass_arg2(this, arg_2);
2449   pass_arg1(this, arg_1);
2450   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2451 }
2452 
2453 void MacroAssembler::super_call_VM(Register oop_result,
2454                                    Register last_java_sp,
2455                                    address entry_point,
2456                                    Register arg_1,
2457                                    Register arg_2,
2458                                    Register arg_3,
2459                                    bool check_exceptions) {
2460   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2461   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2462   pass_arg3(this, arg_3);
2463   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2464   pass_arg2(this, arg_2);
2465   pass_arg1(this, arg_1);
2466   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2467 }
2468 
2469 void MacroAssembler::call_VM_base(Register oop_result,
2470                                   Register java_thread,
2471                                   Register last_java_sp,
2472                                   address  entry_point,
2473                                   int      number_of_arguments,
2474                                   bool     check_exceptions) {
2475   // determine java_thread register
2476   if (!java_thread->is_valid()) {
2477 #ifdef _LP64
2478     java_thread = r15_thread;
2479 #else
2480     java_thread = rdi;
2481     get_thread(java_thread);
2482 #endif // LP64
2483   }
2484   // determine last_java_sp register
2485   if (!last_java_sp->is_valid()) {
2486     last_java_sp = rsp;
2487   }
2488   // debugging support
2489   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2490   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2491 #ifdef ASSERT
2492   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2493   // r12 is the heapbase.
2494   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2495 #endif // ASSERT
2496 
2497   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2498   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2499 
2500   // push java thread (becomes first argument of C function)
2501 
2502   NOT_LP64(push(java_thread); number_of_arguments++);
2503   LP64_ONLY(mov(c_rarg0, r15_thread));
2504 
2505   // set last Java frame before call
2506   assert(last_java_sp != rbp, "can't use ebp/rbp");
2507 
2508   // Only interpreter should have to set fp
2509   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2510 
2511   // do the call, remove parameters
2512   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2513 
2514   // restore the thread (cannot use the pushed argument since arguments
2515   // may be overwritten by C code generated by an optimizing compiler);
2516   // however can use the register value directly if it is callee saved.
2517   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2518     // rdi & rsi (also r15) are callee saved -> nothing to do
2519 #ifdef ASSERT
2520     guarantee(java_thread != rax, "change this code");
2521     push(rax);
2522     { Label L;
2523       get_thread(rax);
2524       cmpptr(java_thread, rax);
2525       jcc(Assembler::equal, L);
2526       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2527       bind(L);
2528     }
2529     pop(rax);
2530 #endif
2531   } else {
2532     get_thread(java_thread);
2533   }
2534   // reset last Java frame
2535   // Only interpreter should have to clear fp
2536   reset_last_Java_frame(java_thread, true);
2537 
2538    // C++ interp handles this in the interpreter
2539   check_and_handle_popframe(java_thread);
2540   check_and_handle_earlyret(java_thread);
2541 
2542   if (check_exceptions) {
2543     // check for pending exceptions (java_thread is set upon return)
2544     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2545 #ifndef _LP64
2546     jump_cc(Assembler::notEqual,
2547             RuntimeAddress(StubRoutines::forward_exception_entry()));
2548 #else
2549     // This used to conditionally jump to forward_exception however it is
2550     // possible if we relocate that the branch will not reach. So we must jump
2551     // around so we can always reach
2552 
2553     Label ok;
2554     jcc(Assembler::equal, ok);
2555     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2556     bind(ok);
2557 #endif // LP64
2558   }
2559 
2560   // get oop result if there is one and reset the value in the thread
2561   if (oop_result->is_valid()) {
2562     get_vm_result(oop_result, java_thread);
2563   }
2564 }
2565 
2566 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2567 
2568   // Calculate the value for last_Java_sp
2569   // somewhat subtle. call_VM does an intermediate call
2570   // which places a return address on the stack just under the
2571   // stack pointer as the user finsihed with it. This allows
2572   // use to retrieve last_Java_pc from last_Java_sp[-1].
2573   // On 32bit we then have to push additional args on the stack to accomplish
2574   // the actual requested call. On 64bit call_VM only can use register args
2575   // so the only extra space is the return address that call_VM created.
2576   // This hopefully explains the calculations here.
2577 
2578 #ifdef _LP64
2579   // We've pushed one address, correct last_Java_sp
2580   lea(rax, Address(rsp, wordSize));
2581 #else
2582   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2583 #endif // LP64
2584 
2585   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2586 
2587 }
2588 
2589 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2590 void MacroAssembler::call_VM_leaf0(address entry_point) {
2591   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2592 }
2593 
2594 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2595   call_VM_leaf_base(entry_point, number_of_arguments);
2596 }
2597 
2598 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2599   pass_arg0(this, arg_0);
2600   call_VM_leaf(entry_point, 1);
2601 }
2602 
2603 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2604 
2605   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2606   pass_arg1(this, arg_1);
2607   pass_arg0(this, arg_0);
2608   call_VM_leaf(entry_point, 2);
2609 }
2610 
2611 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2612   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2613   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2614   pass_arg2(this, arg_2);
2615   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2616   pass_arg1(this, arg_1);
2617   pass_arg0(this, arg_0);
2618   call_VM_leaf(entry_point, 3);
2619 }
2620 
2621 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2622   pass_arg0(this, arg_0);
2623   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2624 }
2625 
2626 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2627 
2628   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2629   pass_arg1(this, arg_1);
2630   pass_arg0(this, arg_0);
2631   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2632 }
2633 
2634 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2635   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2636   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2637   pass_arg2(this, arg_2);
2638   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2639   pass_arg1(this, arg_1);
2640   pass_arg0(this, arg_0);
2641   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2642 }
2643 
2644 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2645   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2646   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2647   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2648   pass_arg3(this, arg_3);
2649   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2650   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2651   pass_arg2(this, arg_2);
2652   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2653   pass_arg1(this, arg_1);
2654   pass_arg0(this, arg_0);
2655   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2656 }
2657 
2658 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2659   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2660   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2661   verify_oop(oop_result, "broken oop in call_VM_base");
2662 }
2663 
2664 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2665   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2666   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2667 }
2668 
2669 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2670 }
2671 
2672 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2673 }
2674 
2675 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2676   if (reachable(src1)) {
2677     cmpl(as_Address(src1), imm);
2678   } else {
2679     lea(rscratch1, src1);
2680     cmpl(Address(rscratch1, 0), imm);
2681   }
2682 }
2683 
2684 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2685   assert(!src2.is_lval(), "use cmpptr");
2686   if (reachable(src2)) {
2687     cmpl(src1, as_Address(src2));
2688   } else {
2689     lea(rscratch1, src2);
2690     cmpl(src1, Address(rscratch1, 0));
2691   }
2692 }
2693 
2694 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2695   Assembler::cmpl(src1, imm);
2696 }
2697 
2698 void MacroAssembler::cmp32(Register src1, Address src2) {
2699   Assembler::cmpl(src1, src2);
2700 }
2701 
2702 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2703   ucomisd(opr1, opr2);
2704 
2705   Label L;
2706   if (unordered_is_less) {
2707     movl(dst, -1);
2708     jcc(Assembler::parity, L);
2709     jcc(Assembler::below , L);
2710     movl(dst, 0);
2711     jcc(Assembler::equal , L);
2712     increment(dst);
2713   } else { // unordered is greater
2714     movl(dst, 1);
2715     jcc(Assembler::parity, L);
2716     jcc(Assembler::above , L);
2717     movl(dst, 0);
2718     jcc(Assembler::equal , L);
2719     decrementl(dst);
2720   }
2721   bind(L);
2722 }
2723 
2724 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2725   ucomiss(opr1, opr2);
2726 
2727   Label L;
2728   if (unordered_is_less) {
2729     movl(dst, -1);
2730     jcc(Assembler::parity, L);
2731     jcc(Assembler::below , L);
2732     movl(dst, 0);
2733     jcc(Assembler::equal , L);
2734     increment(dst);
2735   } else { // unordered is greater
2736     movl(dst, 1);
2737     jcc(Assembler::parity, L);
2738     jcc(Assembler::above , L);
2739     movl(dst, 0);
2740     jcc(Assembler::equal , L);
2741     decrementl(dst);
2742   }
2743   bind(L);
2744 }
2745 
2746 
2747 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2748   if (reachable(src1)) {
2749     cmpb(as_Address(src1), imm);
2750   } else {
2751     lea(rscratch1, src1);
2752     cmpb(Address(rscratch1, 0), imm);
2753   }
2754 }
2755 
2756 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2757 #ifdef _LP64
2758   if (src2.is_lval()) {
2759     movptr(rscratch1, src2);
2760     Assembler::cmpq(src1, rscratch1);
2761   } else if (reachable(src2)) {
2762     cmpq(src1, as_Address(src2));
2763   } else {
2764     lea(rscratch1, src2);
2765     Assembler::cmpq(src1, Address(rscratch1, 0));
2766   }
2767 #else
2768   if (src2.is_lval()) {
2769     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2770   } else {
2771     cmpl(src1, as_Address(src2));
2772   }
2773 #endif // _LP64
2774 }
2775 
2776 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2777   assert(src2.is_lval(), "not a mem-mem compare");
2778 #ifdef _LP64
2779   // moves src2's literal address
2780   movptr(rscratch1, src2);
2781   Assembler::cmpq(src1, rscratch1);
2782 #else
2783   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2784 #endif // _LP64
2785 }
2786 
2787 void MacroAssembler::cmpoop(Register src1, Register src2) {
2788   cmpptr(src1, src2);
2789 }
2790 
2791 void MacroAssembler::cmpoop(Register src1, Address src2) {
2792   cmpptr(src1, src2);
2793 }
2794 
2795 #ifdef _LP64
2796 void MacroAssembler::cmpoop(Register src1, jobject src2) {
2797   movoop(rscratch1, src2);
2798   cmpptr(src1, rscratch1);
2799 }
2800 #endif
2801 
2802 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2803   if (reachable(adr)) {
2804     if (os::is_MP())
2805       lock();
2806     cmpxchgptr(reg, as_Address(adr));
2807   } else {
2808     lea(rscratch1, adr);
2809     if (os::is_MP())
2810       lock();
2811     cmpxchgptr(reg, Address(rscratch1, 0));
2812   }
2813 }
2814 
2815 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2816   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2817 }
2818 
2819 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2820   if (reachable(src)) {
2821     Assembler::comisd(dst, as_Address(src));
2822   } else {
2823     lea(rscratch1, src);
2824     Assembler::comisd(dst, Address(rscratch1, 0));
2825   }
2826 }
2827 
2828 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2829   if (reachable(src)) {
2830     Assembler::comiss(dst, as_Address(src));
2831   } else {
2832     lea(rscratch1, src);
2833     Assembler::comiss(dst, Address(rscratch1, 0));
2834   }
2835 }
2836 
2837 
2838 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2839   Condition negated_cond = negate_condition(cond);
2840   Label L;
2841   jcc(negated_cond, L);
2842   pushf(); // Preserve flags
2843   atomic_incl(counter_addr);
2844   popf();
2845   bind(L);
2846 }
2847 
2848 int MacroAssembler::corrected_idivl(Register reg) {
2849   // Full implementation of Java idiv and irem; checks for
2850   // special case as described in JVM spec., p.243 & p.271.
2851   // The function returns the (pc) offset of the idivl
2852   // instruction - may be needed for implicit exceptions.
2853   //
2854   //         normal case                           special case
2855   //
2856   // input : rax,: dividend                         min_int
2857   //         reg: divisor   (may not be rax,/rdx)   -1
2858   //
2859   // output: rax,: quotient  (= rax, idiv reg)       min_int
2860   //         rdx: remainder (= rax, irem reg)       0
2861   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2862   const int min_int = 0x80000000;
2863   Label normal_case, special_case;
2864 
2865   // check for special case
2866   cmpl(rax, min_int);
2867   jcc(Assembler::notEqual, normal_case);
2868   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2869   cmpl(reg, -1);
2870   jcc(Assembler::equal, special_case);
2871 
2872   // handle normal case
2873   bind(normal_case);
2874   cdql();
2875   int idivl_offset = offset();
2876   idivl(reg);
2877 
2878   // normal and special case exit
2879   bind(special_case);
2880 
2881   return idivl_offset;
2882 }
2883 
2884 
2885 
2886 void MacroAssembler::decrementl(Register reg, int value) {
2887   if (value == min_jint) {subl(reg, value) ; return; }
2888   if (value <  0) { incrementl(reg, -value); return; }
2889   if (value == 0) {                        ; return; }
2890   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2891   /* else */      { subl(reg, value)       ; return; }
2892 }
2893 
2894 void MacroAssembler::decrementl(Address dst, int value) {
2895   if (value == min_jint) {subl(dst, value) ; return; }
2896   if (value <  0) { incrementl(dst, -value); return; }
2897   if (value == 0) {                        ; return; }
2898   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2899   /* else */      { subl(dst, value)       ; return; }
2900 }
2901 
2902 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2903   assert (shift_value > 0, "illegal shift value");
2904   Label _is_positive;
2905   testl (reg, reg);
2906   jcc (Assembler::positive, _is_positive);
2907   int offset = (1 << shift_value) - 1 ;
2908 
2909   if (offset == 1) {
2910     incrementl(reg);
2911   } else {
2912     addl(reg, offset);
2913   }
2914 
2915   bind (_is_positive);
2916   sarl(reg, shift_value);
2917 }
2918 
2919 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2920   if (reachable(src)) {
2921     Assembler::divsd(dst, as_Address(src));
2922   } else {
2923     lea(rscratch1, src);
2924     Assembler::divsd(dst, Address(rscratch1, 0));
2925   }
2926 }
2927 
2928 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2929   if (reachable(src)) {
2930     Assembler::divss(dst, as_Address(src));
2931   } else {
2932     lea(rscratch1, src);
2933     Assembler::divss(dst, Address(rscratch1, 0));
2934   }
2935 }
2936 
2937 // !defined(COMPILER2) is because of stupid core builds
2938 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2939 void MacroAssembler::empty_FPU_stack() {
2940   if (VM_Version::supports_mmx()) {
2941     emms();
2942   } else {
2943     for (int i = 8; i-- > 0; ) ffree(i);
2944   }
2945 }
2946 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2947 
2948 
2949 // Defines obj, preserves var_size_in_bytes
2950 void MacroAssembler::eden_allocate(Register obj,
2951                                    Register var_size_in_bytes,
2952                                    int con_size_in_bytes,
2953                                    Register t1,
2954                                    Label& slow_case) {
2955   assert(obj == rax, "obj must be in rax, for cmpxchg");
2956   assert_different_registers(obj, var_size_in_bytes, t1);
2957   if (!Universe::heap()->supports_inline_contig_alloc()) {
2958     jmp(slow_case);
2959   } else {
2960     Register end = t1;
2961     Label retry;
2962     bind(retry);
2963     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2964     movptr(obj, heap_top);
2965     if (var_size_in_bytes == noreg) {
2966       lea(end, Address(obj, con_size_in_bytes));
2967     } else {
2968       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2969     }
2970     // if end < obj then we wrapped around => object too long => slow case
2971     cmpptr(end, obj);
2972     jcc(Assembler::below, slow_case);
2973     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2974     jcc(Assembler::above, slow_case);
2975     // Compare obj with the top addr, and if still equal, store the new top addr in
2976     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2977     // it otherwise. Use lock prefix for atomicity on MPs.
2978     locked_cmpxchgptr(end, heap_top);
2979     jcc(Assembler::notEqual, retry);
2980   }
2981 }
2982 
2983 void MacroAssembler::enter() {
2984   push(rbp);
2985   mov(rbp, rsp);
2986 }
2987 
2988 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2989 void MacroAssembler::fat_nop() {
2990   if (UseAddressNop) {
2991     addr_nop_5();
2992   } else {
2993     emit_int8(0x26); // es:
2994     emit_int8(0x2e); // cs:
2995     emit_int8(0x64); // fs:
2996     emit_int8(0x65); // gs:
2997     emit_int8((unsigned char)0x90);
2998   }
2999 }
3000 
3001 void MacroAssembler::fcmp(Register tmp) {
3002   fcmp(tmp, 1, true, true);
3003 }
3004 
3005 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
3006   assert(!pop_right || pop_left, "usage error");
3007   if (VM_Version::supports_cmov()) {
3008     assert(tmp == noreg, "unneeded temp");
3009     if (pop_left) {
3010       fucomip(index);
3011     } else {
3012       fucomi(index);
3013     }
3014     if (pop_right) {
3015       fpop();
3016     }
3017   } else {
3018     assert(tmp != noreg, "need temp");
3019     if (pop_left) {
3020       if (pop_right) {
3021         fcompp();
3022       } else {
3023         fcomp(index);
3024       }
3025     } else {
3026       fcom(index);
3027     }
3028     // convert FPU condition into eflags condition via rax,
3029     save_rax(tmp);
3030     fwait(); fnstsw_ax();
3031     sahf();
3032     restore_rax(tmp);
3033   }
3034   // condition codes set as follows:
3035   //
3036   // CF (corresponds to C0) if x < y
3037   // PF (corresponds to C2) if unordered
3038   // ZF (corresponds to C3) if x = y
3039 }
3040 
3041 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3042   fcmp2int(dst, unordered_is_less, 1, true, true);
3043 }
3044 
3045 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3046   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3047   Label L;
3048   if (unordered_is_less) {
3049     movl(dst, -1);
3050     jcc(Assembler::parity, L);
3051     jcc(Assembler::below , L);
3052     movl(dst, 0);
3053     jcc(Assembler::equal , L);
3054     increment(dst);
3055   } else { // unordered is greater
3056     movl(dst, 1);
3057     jcc(Assembler::parity, L);
3058     jcc(Assembler::above , L);
3059     movl(dst, 0);
3060     jcc(Assembler::equal , L);
3061     decrementl(dst);
3062   }
3063   bind(L);
3064 }
3065 
3066 void MacroAssembler::fld_d(AddressLiteral src) {
3067   fld_d(as_Address(src));
3068 }
3069 
3070 void MacroAssembler::fld_s(AddressLiteral src) {
3071   fld_s(as_Address(src));
3072 }
3073 
3074 void MacroAssembler::fld_x(AddressLiteral src) {
3075   Assembler::fld_x(as_Address(src));
3076 }
3077 
3078 void MacroAssembler::fldcw(AddressLiteral src) {
3079   Assembler::fldcw(as_Address(src));
3080 }
3081 
3082 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3083   if (reachable(src)) {
3084     Assembler::mulpd(dst, as_Address(src));
3085   } else {
3086     lea(rscratch1, src);
3087     Assembler::mulpd(dst, Address(rscratch1, 0));
3088   }
3089 }
3090 
3091 void MacroAssembler::increase_precision() {
3092   subptr(rsp, BytesPerWord);
3093   fnstcw(Address(rsp, 0));
3094   movl(rax, Address(rsp, 0));
3095   orl(rax, 0x300);
3096   push(rax);
3097   fldcw(Address(rsp, 0));
3098   pop(rax);
3099 }
3100 
3101 void MacroAssembler::restore_precision() {
3102   fldcw(Address(rsp, 0));
3103   addptr(rsp, BytesPerWord);
3104 }
3105 
3106 void MacroAssembler::fpop() {
3107   ffree();
3108   fincstp();
3109 }
3110 
3111 void MacroAssembler::load_float(Address src) {
3112   if (UseSSE >= 1) {
3113     movflt(xmm0, src);
3114   } else {
3115     LP64_ONLY(ShouldNotReachHere());
3116     NOT_LP64(fld_s(src));
3117   }
3118 }
3119 
3120 void MacroAssembler::store_float(Address dst) {
3121   if (UseSSE >= 1) {
3122     movflt(dst, xmm0);
3123   } else {
3124     LP64_ONLY(ShouldNotReachHere());
3125     NOT_LP64(fstp_s(dst));
3126   }
3127 }
3128 
3129 void MacroAssembler::load_double(Address src) {
3130   if (UseSSE >= 2) {
3131     movdbl(xmm0, src);
3132   } else {
3133     LP64_ONLY(ShouldNotReachHere());
3134     NOT_LP64(fld_d(src));
3135   }
3136 }
3137 
3138 void MacroAssembler::store_double(Address dst) {
3139   if (UseSSE >= 2) {
3140     movdbl(dst, xmm0);
3141   } else {
3142     LP64_ONLY(ShouldNotReachHere());
3143     NOT_LP64(fstp_d(dst));
3144   }
3145 }
3146 
3147 void MacroAssembler::fremr(Register tmp) {
3148   save_rax(tmp);
3149   { Label L;
3150     bind(L);
3151     fprem();
3152     fwait(); fnstsw_ax();
3153 #ifdef _LP64
3154     testl(rax, 0x400);
3155     jcc(Assembler::notEqual, L);
3156 #else
3157     sahf();
3158     jcc(Assembler::parity, L);
3159 #endif // _LP64
3160   }
3161   restore_rax(tmp);
3162   // Result is in ST0.
3163   // Note: fxch & fpop to get rid of ST1
3164   // (otherwise FPU stack could overflow eventually)
3165   fxch(1);
3166   fpop();
3167 }
3168 
3169 // dst = c = a * b + c
3170 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3171   Assembler::vfmadd231sd(c, a, b);
3172   if (dst != c) {
3173     movdbl(dst, c);
3174   }
3175 }
3176 
3177 // dst = c = a * b + c
3178 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3179   Assembler::vfmadd231ss(c, a, b);
3180   if (dst != c) {
3181     movflt(dst, c);
3182   }
3183 }
3184 
3185 // dst = c = a * b + c
3186 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3187   Assembler::vfmadd231pd(c, a, b, vector_len);
3188   if (dst != c) {
3189     vmovdqu(dst, c);
3190   }
3191 }
3192 
3193 // dst = c = a * b + c
3194 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3195   Assembler::vfmadd231ps(c, a, b, vector_len);
3196   if (dst != c) {
3197     vmovdqu(dst, c);
3198   }
3199 }
3200 
3201 // dst = c = a * b + c
3202 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3203   Assembler::vfmadd231pd(c, a, b, vector_len);
3204   if (dst != c) {
3205     vmovdqu(dst, c);
3206   }
3207 }
3208 
3209 // dst = c = a * b + c
3210 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3211   Assembler::vfmadd231ps(c, a, b, vector_len);
3212   if (dst != c) {
3213     vmovdqu(dst, c);
3214   }
3215 }
3216 
3217 void MacroAssembler::incrementl(AddressLiteral dst) {
3218   if (reachable(dst)) {
3219     incrementl(as_Address(dst));
3220   } else {
3221     lea(rscratch1, dst);
3222     incrementl(Address(rscratch1, 0));
3223   }
3224 }
3225 
3226 void MacroAssembler::incrementl(ArrayAddress dst) {
3227   incrementl(as_Address(dst));
3228 }
3229 
3230 void MacroAssembler::incrementl(Register reg, int value) {
3231   if (value == min_jint) {addl(reg, value) ; return; }
3232   if (value <  0) { decrementl(reg, -value); return; }
3233   if (value == 0) {                        ; return; }
3234   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3235   /* else */      { addl(reg, value)       ; return; }
3236 }
3237 
3238 void MacroAssembler::incrementl(Address dst, int value) {
3239   if (value == min_jint) {addl(dst, value) ; return; }
3240   if (value <  0) { decrementl(dst, -value); return; }
3241   if (value == 0) {                        ; return; }
3242   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3243   /* else */      { addl(dst, value)       ; return; }
3244 }
3245 
3246 void MacroAssembler::jump(AddressLiteral dst) {
3247   if (reachable(dst)) {
3248     jmp_literal(dst.target(), dst.rspec());
3249   } else {
3250     lea(rscratch1, dst);
3251     jmp(rscratch1);
3252   }
3253 }
3254 
3255 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3256   if (reachable(dst)) {
3257     InstructionMark im(this);
3258     relocate(dst.reloc());
3259     const int short_size = 2;
3260     const int long_size = 6;
3261     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3262     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3263       // 0111 tttn #8-bit disp
3264       emit_int8(0x70 | cc);
3265       emit_int8((offs - short_size) & 0xFF);
3266     } else {
3267       // 0000 1111 1000 tttn #32-bit disp
3268       emit_int8(0x0F);
3269       emit_int8((unsigned char)(0x80 | cc));
3270       emit_int32(offs - long_size);
3271     }
3272   } else {
3273 #ifdef ASSERT
3274     warning("reversing conditional branch");
3275 #endif /* ASSERT */
3276     Label skip;
3277     jccb(reverse[cc], skip);
3278     lea(rscratch1, dst);
3279     Assembler::jmp(rscratch1);
3280     bind(skip);
3281   }
3282 }
3283 
3284 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3285   if (reachable(src)) {
3286     Assembler::ldmxcsr(as_Address(src));
3287   } else {
3288     lea(rscratch1, src);
3289     Assembler::ldmxcsr(Address(rscratch1, 0));
3290   }
3291 }
3292 
3293 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3294   int off;
3295   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3296     off = offset();
3297     movsbl(dst, src); // movsxb
3298   } else {
3299     off = load_unsigned_byte(dst, src);
3300     shll(dst, 24);
3301     sarl(dst, 24);
3302   }
3303   return off;
3304 }
3305 
3306 // Note: load_signed_short used to be called load_signed_word.
3307 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3308 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3309 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3310 int MacroAssembler::load_signed_short(Register dst, Address src) {
3311   int off;
3312   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3313     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3314     // version but this is what 64bit has always done. This seems to imply
3315     // that users are only using 32bits worth.
3316     off = offset();
3317     movswl(dst, src); // movsxw
3318   } else {
3319     off = load_unsigned_short(dst, src);
3320     shll(dst, 16);
3321     sarl(dst, 16);
3322   }
3323   return off;
3324 }
3325 
3326 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3327   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3328   // and "3.9 Partial Register Penalties", p. 22).
3329   int off;
3330   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3331     off = offset();
3332     movzbl(dst, src); // movzxb
3333   } else {
3334     xorl(dst, dst);
3335     off = offset();
3336     movb(dst, src);
3337   }
3338   return off;
3339 }
3340 
3341 // Note: load_unsigned_short used to be called load_unsigned_word.
3342 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3343   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3344   // and "3.9 Partial Register Penalties", p. 22).
3345   int off;
3346   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3347     off = offset();
3348     movzwl(dst, src); // movzxw
3349   } else {
3350     xorl(dst, dst);
3351     off = offset();
3352     movw(dst, src);
3353   }
3354   return off;
3355 }
3356 
3357 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3358   switch (size_in_bytes) {
3359 #ifndef _LP64
3360   case  8:
3361     assert(dst2 != noreg, "second dest register required");
3362     movl(dst,  src);
3363     movl(dst2, src.plus_disp(BytesPerInt));
3364     break;
3365 #else
3366   case  8:  movq(dst, src); break;
3367 #endif
3368   case  4:  movl(dst, src); break;
3369   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3370   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3371   default:  ShouldNotReachHere();
3372   }
3373 }
3374 
3375 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3376   switch (size_in_bytes) {
3377 #ifndef _LP64
3378   case  8:
3379     assert(src2 != noreg, "second source register required");
3380     movl(dst,                        src);
3381     movl(dst.plus_disp(BytesPerInt), src2);
3382     break;
3383 #else
3384   case  8:  movq(dst, src); break;
3385 #endif
3386   case  4:  movl(dst, src); break;
3387   case  2:  movw(dst, src); break;
3388   case  1:  movb(dst, src); break;
3389   default:  ShouldNotReachHere();
3390   }
3391 }
3392 
3393 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3394   if (reachable(dst)) {
3395     movl(as_Address(dst), src);
3396   } else {
3397     lea(rscratch1, dst);
3398     movl(Address(rscratch1, 0), src);
3399   }
3400 }
3401 
3402 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3403   if (reachable(src)) {
3404     movl(dst, as_Address(src));
3405   } else {
3406     lea(rscratch1, src);
3407     movl(dst, Address(rscratch1, 0));
3408   }
3409 }
3410 
3411 // C++ bool manipulation
3412 
3413 void MacroAssembler::movbool(Register dst, Address src) {
3414   if(sizeof(bool) == 1)
3415     movb(dst, src);
3416   else if(sizeof(bool) == 2)
3417     movw(dst, src);
3418   else if(sizeof(bool) == 4)
3419     movl(dst, src);
3420   else
3421     // unsupported
3422     ShouldNotReachHere();
3423 }
3424 
3425 void MacroAssembler::movbool(Address dst, bool boolconst) {
3426   if(sizeof(bool) == 1)
3427     movb(dst, (int) boolconst);
3428   else if(sizeof(bool) == 2)
3429     movw(dst, (int) boolconst);
3430   else if(sizeof(bool) == 4)
3431     movl(dst, (int) boolconst);
3432   else
3433     // unsupported
3434     ShouldNotReachHere();
3435 }
3436 
3437 void MacroAssembler::movbool(Address dst, Register src) {
3438   if(sizeof(bool) == 1)
3439     movb(dst, src);
3440   else if(sizeof(bool) == 2)
3441     movw(dst, src);
3442   else if(sizeof(bool) == 4)
3443     movl(dst, src);
3444   else
3445     // unsupported
3446     ShouldNotReachHere();
3447 }
3448 
3449 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3450   movb(as_Address(dst), src);
3451 }
3452 
3453 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3454   if (reachable(src)) {
3455     movdl(dst, as_Address(src));
3456   } else {
3457     lea(rscratch1, src);
3458     movdl(dst, Address(rscratch1, 0));
3459   }
3460 }
3461 
3462 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3463   if (reachable(src)) {
3464     movq(dst, as_Address(src));
3465   } else {
3466     lea(rscratch1, src);
3467     movq(dst, Address(rscratch1, 0));
3468   }
3469 }
3470 
3471 void MacroAssembler::setvectmask(Register dst, Register src) {
3472   Assembler::movl(dst, 1);
3473   Assembler::shlxl(dst, dst, src);
3474   Assembler::decl(dst);
3475   Assembler::kmovdl(k1, dst);
3476   Assembler::movl(dst, src);
3477 }
3478 
3479 void MacroAssembler::restorevectmask() {
3480   Assembler::knotwl(k1, k0);
3481 }
3482 
3483 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3484   if (reachable(src)) {
3485     if (UseXmmLoadAndClearUpper) {
3486       movsd (dst, as_Address(src));
3487     } else {
3488       movlpd(dst, as_Address(src));
3489     }
3490   } else {
3491     lea(rscratch1, src);
3492     if (UseXmmLoadAndClearUpper) {
3493       movsd (dst, Address(rscratch1, 0));
3494     } else {
3495       movlpd(dst, Address(rscratch1, 0));
3496     }
3497   }
3498 }
3499 
3500 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3501   if (reachable(src)) {
3502     movss(dst, as_Address(src));
3503   } else {
3504     lea(rscratch1, src);
3505     movss(dst, Address(rscratch1, 0));
3506   }
3507 }
3508 
3509 void MacroAssembler::movptr(Register dst, Register src) {
3510   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3511 }
3512 
3513 void MacroAssembler::movptr(Register dst, Address src) {
3514   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3515 }
3516 
3517 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3518 void MacroAssembler::movptr(Register dst, intptr_t src) {
3519   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3520 }
3521 
3522 void MacroAssembler::movptr(Address dst, Register src) {
3523   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3524 }
3525 
3526 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3527   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3528     Assembler::vextractf32x4(dst, src, 0);
3529   } else {
3530     Assembler::movdqu(dst, src);
3531   }
3532 }
3533 
3534 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3535   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3536     Assembler::vinsertf32x4(dst, dst, src, 0);
3537   } else {
3538     Assembler::movdqu(dst, src);
3539   }
3540 }
3541 
3542 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3543   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3544     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3545   } else {
3546     Assembler::movdqu(dst, src);
3547   }
3548 }
3549 
3550 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3551   if (reachable(src)) {
3552     movdqu(dst, as_Address(src));
3553   } else {
3554     lea(scratchReg, src);
3555     movdqu(dst, Address(scratchReg, 0));
3556   }
3557 }
3558 
3559 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3560   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3561     vextractf64x4_low(dst, src);
3562   } else {
3563     Assembler::vmovdqu(dst, src);
3564   }
3565 }
3566 
3567 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3568   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3569     vinsertf64x4_low(dst, src);
3570   } else {
3571     Assembler::vmovdqu(dst, src);
3572   }
3573 }
3574 
3575 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3576   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3577     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3578   }
3579   else {
3580     Assembler::vmovdqu(dst, src);
3581   }
3582 }
3583 
3584 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3585   if (reachable(src)) {
3586     vmovdqu(dst, as_Address(src));
3587   }
3588   else {
3589     lea(rscratch1, src);
3590     vmovdqu(dst, Address(rscratch1, 0));
3591   }
3592 }
3593 
3594 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3595   if (reachable(src)) {
3596     Assembler::movdqa(dst, as_Address(src));
3597   } else {
3598     lea(rscratch1, src);
3599     Assembler::movdqa(dst, Address(rscratch1, 0));
3600   }
3601 }
3602 
3603 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3604   if (reachable(src)) {
3605     Assembler::movsd(dst, as_Address(src));
3606   } else {
3607     lea(rscratch1, src);
3608     Assembler::movsd(dst, Address(rscratch1, 0));
3609   }
3610 }
3611 
3612 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3613   if (reachable(src)) {
3614     Assembler::movss(dst, as_Address(src));
3615   } else {
3616     lea(rscratch1, src);
3617     Assembler::movss(dst, Address(rscratch1, 0));
3618   }
3619 }
3620 
3621 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3622   if (reachable(src)) {
3623     Assembler::mulsd(dst, as_Address(src));
3624   } else {
3625     lea(rscratch1, src);
3626     Assembler::mulsd(dst, Address(rscratch1, 0));
3627   }
3628 }
3629 
3630 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3631   if (reachable(src)) {
3632     Assembler::mulss(dst, as_Address(src));
3633   } else {
3634     lea(rscratch1, src);
3635     Assembler::mulss(dst, Address(rscratch1, 0));
3636   }
3637 }
3638 
3639 void MacroAssembler::null_check(Register reg, int offset) {
3640   if (needs_explicit_null_check(offset)) {
3641     // provoke OS NULL exception if reg = NULL by
3642     // accessing M[reg] w/o changing any (non-CC) registers
3643     // NOTE: cmpl is plenty here to provoke a segv
3644     cmpptr(rax, Address(reg, 0));
3645     // Note: should probably use testl(rax, Address(reg, 0));
3646     //       may be shorter code (however, this version of
3647     //       testl needs to be implemented first)
3648   } else {
3649     // nothing to do, (later) access of M[reg + offset]
3650     // will provoke OS NULL exception if reg = NULL
3651   }
3652 }
3653 
3654 void MacroAssembler::os_breakpoint() {
3655   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3656   // (e.g., MSVC can't call ps() otherwise)
3657   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3658 }
3659 
3660 void MacroAssembler::unimplemented(const char* what) {
3661   const char* buf = NULL;
3662   {
3663     ResourceMark rm;
3664     stringStream ss;
3665     ss.print("unimplemented: %s", what);
3666     buf = code_string(ss.as_string());
3667   }
3668   stop(buf);
3669 }
3670 
3671 #ifdef _LP64
3672 #define XSTATE_BV 0x200
3673 #endif
3674 
3675 void MacroAssembler::pop_CPU_state() {
3676   pop_FPU_state();
3677   pop_IU_state();
3678 }
3679 
3680 void MacroAssembler::pop_FPU_state() {
3681 #ifndef _LP64
3682   frstor(Address(rsp, 0));
3683 #else
3684   fxrstor(Address(rsp, 0));
3685 #endif
3686   addptr(rsp, FPUStateSizeInWords * wordSize);
3687 }
3688 
3689 void MacroAssembler::pop_IU_state() {
3690   popa();
3691   LP64_ONLY(addq(rsp, 8));
3692   popf();
3693 }
3694 
3695 // Save Integer and Float state
3696 // Warning: Stack must be 16 byte aligned (64bit)
3697 void MacroAssembler::push_CPU_state() {
3698   push_IU_state();
3699   push_FPU_state();
3700 }
3701 
3702 void MacroAssembler::push_FPU_state() {
3703   subptr(rsp, FPUStateSizeInWords * wordSize);
3704 #ifndef _LP64
3705   fnsave(Address(rsp, 0));
3706   fwait();
3707 #else
3708   fxsave(Address(rsp, 0));
3709 #endif // LP64
3710 }
3711 
3712 void MacroAssembler::push_IU_state() {
3713   // Push flags first because pusha kills them
3714   pushf();
3715   // Make sure rsp stays 16-byte aligned
3716   LP64_ONLY(subq(rsp, 8));
3717   pusha();
3718 }
3719 
3720 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3721   if (!java_thread->is_valid()) {
3722     java_thread = rdi;
3723     get_thread(java_thread);
3724   }
3725   // we must set sp to zero to clear frame
3726   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3727   if (clear_fp) {
3728     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3729   }
3730 
3731   // Always clear the pc because it could have been set by make_walkable()
3732   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3733 
3734   vzeroupper();
3735 }
3736 
3737 void MacroAssembler::restore_rax(Register tmp) {
3738   if (tmp == noreg) pop(rax);
3739   else if (tmp != rax) mov(rax, tmp);
3740 }
3741 
3742 void MacroAssembler::round_to(Register reg, int modulus) {
3743   addptr(reg, modulus - 1);
3744   andptr(reg, -modulus);
3745 }
3746 
3747 void MacroAssembler::save_rax(Register tmp) {
3748   if (tmp == noreg) push(rax);
3749   else if (tmp != rax) mov(tmp, rax);
3750 }
3751 
3752 // Write serialization page so VM thread can do a pseudo remote membar.
3753 // We use the current thread pointer to calculate a thread specific
3754 // offset to write to within the page. This minimizes bus traffic
3755 // due to cache line collision.
3756 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3757   movl(tmp, thread);
3758   shrl(tmp, os::get_serialize_page_shift_count());
3759   andl(tmp, (os::vm_page_size() - sizeof(int)));
3760 
3761   Address index(noreg, tmp, Address::times_1);
3762   ExternalAddress page(os::get_memory_serialize_page());
3763 
3764   // Size of store must match masking code above
3765   movl(as_Address(ArrayAddress(page, index)), tmp);
3766 }
3767 
3768 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, Register temp_reg) {
3769   if (SafepointMechanism::uses_thread_local_poll()) {
3770 #ifdef _LP64
3771     assert(thread_reg == r15_thread, "should be");
3772 #else
3773     if (thread_reg == noreg) {
3774       thread_reg = temp_reg;
3775       get_thread(thread_reg);
3776     }
3777 #endif
3778     testb(Address(thread_reg, Thread::polling_page_offset()), SafepointMechanism::poll_bit());
3779     jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
3780   } else {
3781     cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3782         SafepointSynchronize::_not_synchronized);
3783     jcc(Assembler::notEqual, slow_path);
3784   }
3785 }
3786 
3787 // Calls to C land
3788 //
3789 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3790 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3791 // has to be reset to 0. This is required to allow proper stack traversal.
3792 void MacroAssembler::set_last_Java_frame(Register java_thread,
3793                                          Register last_java_sp,
3794                                          Register last_java_fp,
3795                                          address  last_java_pc) {
3796   vzeroupper();
3797   // determine java_thread register
3798   if (!java_thread->is_valid()) {
3799     java_thread = rdi;
3800     get_thread(java_thread);
3801   }
3802   // determine last_java_sp register
3803   if (!last_java_sp->is_valid()) {
3804     last_java_sp = rsp;
3805   }
3806 
3807   // last_java_fp is optional
3808 
3809   if (last_java_fp->is_valid()) {
3810     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3811   }
3812 
3813   // last_java_pc is optional
3814 
3815   if (last_java_pc != NULL) {
3816     lea(Address(java_thread,
3817                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3818         InternalAddress(last_java_pc));
3819 
3820   }
3821   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3822 }
3823 
3824 void MacroAssembler::shlptr(Register dst, int imm8) {
3825   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3826 }
3827 
3828 void MacroAssembler::shrptr(Register dst, int imm8) {
3829   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3830 }
3831 
3832 void MacroAssembler::sign_extend_byte(Register reg) {
3833   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3834     movsbl(reg, reg); // movsxb
3835   } else {
3836     shll(reg, 24);
3837     sarl(reg, 24);
3838   }
3839 }
3840 
3841 void MacroAssembler::sign_extend_short(Register reg) {
3842   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3843     movswl(reg, reg); // movsxw
3844   } else {
3845     shll(reg, 16);
3846     sarl(reg, 16);
3847   }
3848 }
3849 
3850 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3851   assert(reachable(src), "Address should be reachable");
3852   testl(dst, as_Address(src));
3853 }
3854 
3855 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3856   int dst_enc = dst->encoding();
3857   int src_enc = src->encoding();
3858   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3859     Assembler::pcmpeqb(dst, src);
3860   } else if ((dst_enc < 16) && (src_enc < 16)) {
3861     Assembler::pcmpeqb(dst, src);
3862   } else if (src_enc < 16) {
3863     subptr(rsp, 64);
3864     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3865     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3866     Assembler::pcmpeqb(xmm0, src);
3867     movdqu(dst, xmm0);
3868     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3869     addptr(rsp, 64);
3870   } else if (dst_enc < 16) {
3871     subptr(rsp, 64);
3872     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3873     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3874     Assembler::pcmpeqb(dst, xmm0);
3875     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3876     addptr(rsp, 64);
3877   } else {
3878     subptr(rsp, 64);
3879     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3880     subptr(rsp, 64);
3881     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3882     movdqu(xmm0, src);
3883     movdqu(xmm1, dst);
3884     Assembler::pcmpeqb(xmm1, xmm0);
3885     movdqu(dst, xmm1);
3886     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3887     addptr(rsp, 64);
3888     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3889     addptr(rsp, 64);
3890   }
3891 }
3892 
3893 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3894   int dst_enc = dst->encoding();
3895   int src_enc = src->encoding();
3896   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3897     Assembler::pcmpeqw(dst, src);
3898   } else if ((dst_enc < 16) && (src_enc < 16)) {
3899     Assembler::pcmpeqw(dst, src);
3900   } else if (src_enc < 16) {
3901     subptr(rsp, 64);
3902     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3903     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3904     Assembler::pcmpeqw(xmm0, src);
3905     movdqu(dst, xmm0);
3906     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3907     addptr(rsp, 64);
3908   } else if (dst_enc < 16) {
3909     subptr(rsp, 64);
3910     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3911     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3912     Assembler::pcmpeqw(dst, xmm0);
3913     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3914     addptr(rsp, 64);
3915   } else {
3916     subptr(rsp, 64);
3917     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3918     subptr(rsp, 64);
3919     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3920     movdqu(xmm0, src);
3921     movdqu(xmm1, dst);
3922     Assembler::pcmpeqw(xmm1, xmm0);
3923     movdqu(dst, xmm1);
3924     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3925     addptr(rsp, 64);
3926     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3927     addptr(rsp, 64);
3928   }
3929 }
3930 
3931 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3932   int dst_enc = dst->encoding();
3933   if (dst_enc < 16) {
3934     Assembler::pcmpestri(dst, src, imm8);
3935   } else {
3936     subptr(rsp, 64);
3937     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3938     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3939     Assembler::pcmpestri(xmm0, src, imm8);
3940     movdqu(dst, xmm0);
3941     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3942     addptr(rsp, 64);
3943   }
3944 }
3945 
3946 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3947   int dst_enc = dst->encoding();
3948   int src_enc = src->encoding();
3949   if ((dst_enc < 16) && (src_enc < 16)) {
3950     Assembler::pcmpestri(dst, src, imm8);
3951   } else if (src_enc < 16) {
3952     subptr(rsp, 64);
3953     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3954     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3955     Assembler::pcmpestri(xmm0, src, imm8);
3956     movdqu(dst, xmm0);
3957     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3958     addptr(rsp, 64);
3959   } else if (dst_enc < 16) {
3960     subptr(rsp, 64);
3961     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3962     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3963     Assembler::pcmpestri(dst, xmm0, imm8);
3964     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3965     addptr(rsp, 64);
3966   } else {
3967     subptr(rsp, 64);
3968     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3969     subptr(rsp, 64);
3970     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3971     movdqu(xmm0, src);
3972     movdqu(xmm1, dst);
3973     Assembler::pcmpestri(xmm1, xmm0, imm8);
3974     movdqu(dst, xmm1);
3975     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3976     addptr(rsp, 64);
3977     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3978     addptr(rsp, 64);
3979   }
3980 }
3981 
3982 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3983   int dst_enc = dst->encoding();
3984   int src_enc = src->encoding();
3985   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3986     Assembler::pmovzxbw(dst, src);
3987   } else if ((dst_enc < 16) && (src_enc < 16)) {
3988     Assembler::pmovzxbw(dst, src);
3989   } else if (src_enc < 16) {
3990     subptr(rsp, 64);
3991     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3992     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3993     Assembler::pmovzxbw(xmm0, src);
3994     movdqu(dst, xmm0);
3995     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3996     addptr(rsp, 64);
3997   } else if (dst_enc < 16) {
3998     subptr(rsp, 64);
3999     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4000     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4001     Assembler::pmovzxbw(dst, xmm0);
4002     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4003     addptr(rsp, 64);
4004   } else {
4005     subptr(rsp, 64);
4006     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4007     subptr(rsp, 64);
4008     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4009     movdqu(xmm0, src);
4010     movdqu(xmm1, dst);
4011     Assembler::pmovzxbw(xmm1, xmm0);
4012     movdqu(dst, xmm1);
4013     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4014     addptr(rsp, 64);
4015     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4016     addptr(rsp, 64);
4017   }
4018 }
4019 
4020 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4021   int dst_enc = dst->encoding();
4022   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4023     Assembler::pmovzxbw(dst, src);
4024   } else if (dst_enc < 16) {
4025     Assembler::pmovzxbw(dst, src);
4026   } else {
4027     subptr(rsp, 64);
4028     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4029     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4030     Assembler::pmovzxbw(xmm0, src);
4031     movdqu(dst, xmm0);
4032     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4033     addptr(rsp, 64);
4034   }
4035 }
4036 
4037 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4038   int src_enc = src->encoding();
4039   if (src_enc < 16) {
4040     Assembler::pmovmskb(dst, src);
4041   } else {
4042     subptr(rsp, 64);
4043     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4044     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4045     Assembler::pmovmskb(dst, xmm0);
4046     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4047     addptr(rsp, 64);
4048   }
4049 }
4050 
4051 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4052   int dst_enc = dst->encoding();
4053   int src_enc = src->encoding();
4054   if ((dst_enc < 16) && (src_enc < 16)) {
4055     Assembler::ptest(dst, src);
4056   } else if (src_enc < 16) {
4057     subptr(rsp, 64);
4058     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4059     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4060     Assembler::ptest(xmm0, src);
4061     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4062     addptr(rsp, 64);
4063   } else if (dst_enc < 16) {
4064     subptr(rsp, 64);
4065     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4066     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4067     Assembler::ptest(dst, xmm0);
4068     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4069     addptr(rsp, 64);
4070   } else {
4071     subptr(rsp, 64);
4072     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4073     subptr(rsp, 64);
4074     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4075     movdqu(xmm0, src);
4076     movdqu(xmm1, dst);
4077     Assembler::ptest(xmm1, xmm0);
4078     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4079     addptr(rsp, 64);
4080     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4081     addptr(rsp, 64);
4082   }
4083 }
4084 
4085 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4086   if (reachable(src)) {
4087     Assembler::sqrtsd(dst, as_Address(src));
4088   } else {
4089     lea(rscratch1, src);
4090     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4091   }
4092 }
4093 
4094 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4095   if (reachable(src)) {
4096     Assembler::sqrtss(dst, as_Address(src));
4097   } else {
4098     lea(rscratch1, src);
4099     Assembler::sqrtss(dst, Address(rscratch1, 0));
4100   }
4101 }
4102 
4103 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4104   if (reachable(src)) {
4105     Assembler::subsd(dst, as_Address(src));
4106   } else {
4107     lea(rscratch1, src);
4108     Assembler::subsd(dst, Address(rscratch1, 0));
4109   }
4110 }
4111 
4112 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4113   if (reachable(src)) {
4114     Assembler::subss(dst, as_Address(src));
4115   } else {
4116     lea(rscratch1, src);
4117     Assembler::subss(dst, Address(rscratch1, 0));
4118   }
4119 }
4120 
4121 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4122   if (reachable(src)) {
4123     Assembler::ucomisd(dst, as_Address(src));
4124   } else {
4125     lea(rscratch1, src);
4126     Assembler::ucomisd(dst, Address(rscratch1, 0));
4127   }
4128 }
4129 
4130 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4131   if (reachable(src)) {
4132     Assembler::ucomiss(dst, as_Address(src));
4133   } else {
4134     lea(rscratch1, src);
4135     Assembler::ucomiss(dst, Address(rscratch1, 0));
4136   }
4137 }
4138 
4139 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4140   // Used in sign-bit flipping with aligned address.
4141   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4142   if (reachable(src)) {
4143     Assembler::xorpd(dst, as_Address(src));
4144   } else {
4145     lea(rscratch1, src);
4146     Assembler::xorpd(dst, Address(rscratch1, 0));
4147   }
4148 }
4149 
4150 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4151   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4152     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4153   }
4154   else {
4155     Assembler::xorpd(dst, src);
4156   }
4157 }
4158 
4159 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4160   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4161     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4162   } else {
4163     Assembler::xorps(dst, src);
4164   }
4165 }
4166 
4167 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4168   // Used in sign-bit flipping with aligned address.
4169   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4170   if (reachable(src)) {
4171     Assembler::xorps(dst, as_Address(src));
4172   } else {
4173     lea(rscratch1, src);
4174     Assembler::xorps(dst, Address(rscratch1, 0));
4175   }
4176 }
4177 
4178 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4179   // Used in sign-bit flipping with aligned address.
4180   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4181   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4182   if (reachable(src)) {
4183     Assembler::pshufb(dst, as_Address(src));
4184   } else {
4185     lea(rscratch1, src);
4186     Assembler::pshufb(dst, Address(rscratch1, 0));
4187   }
4188 }
4189 
4190 // AVX 3-operands instructions
4191 
4192 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4193   if (reachable(src)) {
4194     vaddsd(dst, nds, as_Address(src));
4195   } else {
4196     lea(rscratch1, src);
4197     vaddsd(dst, nds, Address(rscratch1, 0));
4198   }
4199 }
4200 
4201 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4202   if (reachable(src)) {
4203     vaddss(dst, nds, as_Address(src));
4204   } else {
4205     lea(rscratch1, src);
4206     vaddss(dst, nds, Address(rscratch1, 0));
4207   }
4208 }
4209 
4210 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4211   int dst_enc = dst->encoding();
4212   int nds_enc = nds->encoding();
4213   int src_enc = src->encoding();
4214   if ((dst_enc < 16) && (nds_enc < 16)) {
4215     vandps(dst, nds, negate_field, vector_len);
4216   } else if ((src_enc < 16) && (dst_enc < 16)) {
4217     evmovdqul(src, nds, Assembler::AVX_512bit);
4218     vandps(dst, src, negate_field, vector_len);
4219   } else if (src_enc < 16) {
4220     evmovdqul(src, nds, Assembler::AVX_512bit);
4221     vandps(src, src, negate_field, vector_len);
4222     evmovdqul(dst, src, Assembler::AVX_512bit);
4223   } else if (dst_enc < 16) {
4224     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4225     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4226     vandps(dst, xmm0, negate_field, vector_len);
4227     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4228   } else {
4229     if (src_enc != dst_enc) {
4230       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4231       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4232       vandps(xmm0, xmm0, negate_field, vector_len);
4233       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4234       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4235     } else {
4236       subptr(rsp, 64);
4237       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4238       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4239       vandps(xmm0, xmm0, negate_field, vector_len);
4240       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4241       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4242       addptr(rsp, 64);
4243     }
4244   }
4245 }
4246 
4247 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4248   int dst_enc = dst->encoding();
4249   int nds_enc = nds->encoding();
4250   int src_enc = src->encoding();
4251   if ((dst_enc < 16) && (nds_enc < 16)) {
4252     vandpd(dst, nds, negate_field, vector_len);
4253   } else if ((src_enc < 16) && (dst_enc < 16)) {
4254     evmovdqul(src, nds, Assembler::AVX_512bit);
4255     vandpd(dst, src, negate_field, vector_len);
4256   } else if (src_enc < 16) {
4257     evmovdqul(src, nds, Assembler::AVX_512bit);
4258     vandpd(src, src, negate_field, vector_len);
4259     evmovdqul(dst, src, Assembler::AVX_512bit);
4260   } else if (dst_enc < 16) {
4261     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4262     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4263     vandpd(dst, xmm0, negate_field, vector_len);
4264     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4265   } else {
4266     if (src_enc != dst_enc) {
4267       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4268       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4269       vandpd(xmm0, xmm0, negate_field, vector_len);
4270       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4271       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4272     } else {
4273       subptr(rsp, 64);
4274       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4275       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4276       vandpd(xmm0, xmm0, negate_field, vector_len);
4277       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4278       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4279       addptr(rsp, 64);
4280     }
4281   }
4282 }
4283 
4284 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4285   int dst_enc = dst->encoding();
4286   int nds_enc = nds->encoding();
4287   int src_enc = src->encoding();
4288   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4289     Assembler::vpaddb(dst, nds, src, vector_len);
4290   } else if ((dst_enc < 16) && (src_enc < 16)) {
4291     Assembler::vpaddb(dst, dst, src, vector_len);
4292   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4293     // use nds as scratch for src
4294     evmovdqul(nds, src, Assembler::AVX_512bit);
4295     Assembler::vpaddb(dst, dst, nds, vector_len);
4296   } else if ((src_enc < 16) && (nds_enc < 16)) {
4297     // use nds as scratch for dst
4298     evmovdqul(nds, dst, Assembler::AVX_512bit);
4299     Assembler::vpaddb(nds, nds, src, vector_len);
4300     evmovdqul(dst, nds, Assembler::AVX_512bit);
4301   } else if (dst_enc < 16) {
4302     // use nds as scatch for xmm0 to hold src
4303     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4304     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4305     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4306     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4307   } else {
4308     // worse case scenario, all regs are in the upper bank
4309     subptr(rsp, 64);
4310     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4311     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4312     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4313     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4314     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4315     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4316     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4317     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4318     addptr(rsp, 64);
4319   }
4320 }
4321 
4322 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4323   int dst_enc = dst->encoding();
4324   int nds_enc = nds->encoding();
4325   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4326     Assembler::vpaddb(dst, nds, src, vector_len);
4327   } else if (dst_enc < 16) {
4328     Assembler::vpaddb(dst, dst, src, vector_len);
4329   } else if (nds_enc < 16) {
4330     // implies dst_enc in upper bank with src as scratch
4331     evmovdqul(nds, dst, Assembler::AVX_512bit);
4332     Assembler::vpaddb(nds, nds, src, vector_len);
4333     evmovdqul(dst, nds, Assembler::AVX_512bit);
4334   } else {
4335     // worse case scenario, all regs in upper bank
4336     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4337     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4338     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4339     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4340   }
4341 }
4342 
4343 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4344   int dst_enc = dst->encoding();
4345   int nds_enc = nds->encoding();
4346   int src_enc = src->encoding();
4347   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4348     Assembler::vpaddw(dst, nds, src, vector_len);
4349   } else if ((dst_enc < 16) && (src_enc < 16)) {
4350     Assembler::vpaddw(dst, dst, src, vector_len);
4351   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4352     // use nds as scratch for src
4353     evmovdqul(nds, src, Assembler::AVX_512bit);
4354     Assembler::vpaddw(dst, dst, nds, vector_len);
4355   } else if ((src_enc < 16) && (nds_enc < 16)) {
4356     // use nds as scratch for dst
4357     evmovdqul(nds, dst, Assembler::AVX_512bit);
4358     Assembler::vpaddw(nds, nds, src, vector_len);
4359     evmovdqul(dst, nds, Assembler::AVX_512bit);
4360   } else if (dst_enc < 16) {
4361     // use nds as scatch for xmm0 to hold src
4362     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4363     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4364     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4365     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4366   } else {
4367     // worse case scenario, all regs are in the upper bank
4368     subptr(rsp, 64);
4369     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4370     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4371     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4372     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4373     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4374     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4375     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4376     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4377     addptr(rsp, 64);
4378   }
4379 }
4380 
4381 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4382   int dst_enc = dst->encoding();
4383   int nds_enc = nds->encoding();
4384   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4385     Assembler::vpaddw(dst, nds, src, vector_len);
4386   } else if (dst_enc < 16) {
4387     Assembler::vpaddw(dst, dst, src, vector_len);
4388   } else if (nds_enc < 16) {
4389     // implies dst_enc in upper bank with src as scratch
4390     evmovdqul(nds, dst, Assembler::AVX_512bit);
4391     Assembler::vpaddw(nds, nds, src, vector_len);
4392     evmovdqul(dst, nds, Assembler::AVX_512bit);
4393   } else {
4394     // worse case scenario, all regs in upper bank
4395     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4396     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4397     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4398     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4399   }
4400 }
4401 
4402 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4403   if (reachable(src)) {
4404     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4405   } else {
4406     lea(rscratch1, src);
4407     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4408   }
4409 }
4410 
4411 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4412   int dst_enc = dst->encoding();
4413   int src_enc = src->encoding();
4414   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4415     Assembler::vpbroadcastw(dst, src);
4416   } else if ((dst_enc < 16) && (src_enc < 16)) {
4417     Assembler::vpbroadcastw(dst, src);
4418   } else if (src_enc < 16) {
4419     subptr(rsp, 64);
4420     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4421     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4422     Assembler::vpbroadcastw(xmm0, src);
4423     movdqu(dst, xmm0);
4424     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4425     addptr(rsp, 64);
4426   } else if (dst_enc < 16) {
4427     subptr(rsp, 64);
4428     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4429     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4430     Assembler::vpbroadcastw(dst, xmm0);
4431     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4432     addptr(rsp, 64);
4433   } else {
4434     subptr(rsp, 64);
4435     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4436     subptr(rsp, 64);
4437     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4438     movdqu(xmm0, src);
4439     movdqu(xmm1, dst);
4440     Assembler::vpbroadcastw(xmm1, xmm0);
4441     movdqu(dst, xmm1);
4442     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4443     addptr(rsp, 64);
4444     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4445     addptr(rsp, 64);
4446   }
4447 }
4448 
4449 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4450   int dst_enc = dst->encoding();
4451   int nds_enc = nds->encoding();
4452   int src_enc = src->encoding();
4453   assert(dst_enc == nds_enc, "");
4454   if ((dst_enc < 16) && (src_enc < 16)) {
4455     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4456   } else if (src_enc < 16) {
4457     subptr(rsp, 64);
4458     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4459     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4460     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4461     movdqu(dst, xmm0);
4462     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4463     addptr(rsp, 64);
4464   } else if (dst_enc < 16) {
4465     subptr(rsp, 64);
4466     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4467     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4468     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4469     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4470     addptr(rsp, 64);
4471   } else {
4472     subptr(rsp, 64);
4473     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4474     subptr(rsp, 64);
4475     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4476     movdqu(xmm0, src);
4477     movdqu(xmm1, dst);
4478     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4479     movdqu(dst, xmm1);
4480     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4481     addptr(rsp, 64);
4482     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4483     addptr(rsp, 64);
4484   }
4485 }
4486 
4487 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4488   int dst_enc = dst->encoding();
4489   int nds_enc = nds->encoding();
4490   int src_enc = src->encoding();
4491   assert(dst_enc == nds_enc, "");
4492   if ((dst_enc < 16) && (src_enc < 16)) {
4493     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4494   } else if (src_enc < 16) {
4495     subptr(rsp, 64);
4496     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4497     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4498     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4499     movdqu(dst, xmm0);
4500     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4501     addptr(rsp, 64);
4502   } else if (dst_enc < 16) {
4503     subptr(rsp, 64);
4504     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4505     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4506     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4507     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4508     addptr(rsp, 64);
4509   } else {
4510     subptr(rsp, 64);
4511     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4512     subptr(rsp, 64);
4513     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4514     movdqu(xmm0, src);
4515     movdqu(xmm1, dst);
4516     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4517     movdqu(dst, xmm1);
4518     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4519     addptr(rsp, 64);
4520     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4521     addptr(rsp, 64);
4522   }
4523 }
4524 
4525 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4526   int dst_enc = dst->encoding();
4527   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4528     Assembler::vpmovzxbw(dst, src, vector_len);
4529   } else if (dst_enc < 16) {
4530     Assembler::vpmovzxbw(dst, src, vector_len);
4531   } else {
4532     subptr(rsp, 64);
4533     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4534     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4535     Assembler::vpmovzxbw(xmm0, src, vector_len);
4536     movdqu(dst, xmm0);
4537     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4538     addptr(rsp, 64);
4539   }
4540 }
4541 
4542 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4543   int src_enc = src->encoding();
4544   if (src_enc < 16) {
4545     Assembler::vpmovmskb(dst, src);
4546   } else {
4547     subptr(rsp, 64);
4548     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4549     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4550     Assembler::vpmovmskb(dst, xmm0);
4551     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4552     addptr(rsp, 64);
4553   }
4554 }
4555 
4556 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4557   int dst_enc = dst->encoding();
4558   int nds_enc = nds->encoding();
4559   int src_enc = src->encoding();
4560   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4561     Assembler::vpmullw(dst, nds, src, vector_len);
4562   } else if ((dst_enc < 16) && (src_enc < 16)) {
4563     Assembler::vpmullw(dst, dst, src, vector_len);
4564   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4565     // use nds as scratch for src
4566     evmovdqul(nds, src, Assembler::AVX_512bit);
4567     Assembler::vpmullw(dst, dst, nds, vector_len);
4568   } else if ((src_enc < 16) && (nds_enc < 16)) {
4569     // use nds as scratch for dst
4570     evmovdqul(nds, dst, Assembler::AVX_512bit);
4571     Assembler::vpmullw(nds, nds, src, vector_len);
4572     evmovdqul(dst, nds, Assembler::AVX_512bit);
4573   } else if (dst_enc < 16) {
4574     // use nds as scatch for xmm0 to hold src
4575     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4576     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4577     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4578     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4579   } else {
4580     // worse case scenario, all regs are in the upper bank
4581     subptr(rsp, 64);
4582     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4583     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4584     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4585     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4586     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4587     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4588     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4589     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4590     addptr(rsp, 64);
4591   }
4592 }
4593 
4594 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4595   int dst_enc = dst->encoding();
4596   int nds_enc = nds->encoding();
4597   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4598     Assembler::vpmullw(dst, nds, src, vector_len);
4599   } else if (dst_enc < 16) {
4600     Assembler::vpmullw(dst, dst, src, vector_len);
4601   } else if (nds_enc < 16) {
4602     // implies dst_enc in upper bank with src as scratch
4603     evmovdqul(nds, dst, Assembler::AVX_512bit);
4604     Assembler::vpmullw(nds, nds, src, vector_len);
4605     evmovdqul(dst, nds, Assembler::AVX_512bit);
4606   } else {
4607     // worse case scenario, all regs in upper bank
4608     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4609     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4610     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4611     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4612   }
4613 }
4614 
4615 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4616   int dst_enc = dst->encoding();
4617   int nds_enc = nds->encoding();
4618   int src_enc = src->encoding();
4619   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4620     Assembler::vpsubb(dst, nds, src, vector_len);
4621   } else if ((dst_enc < 16) && (src_enc < 16)) {
4622     Assembler::vpsubb(dst, dst, src, vector_len);
4623   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4624     // use nds as scratch for src
4625     evmovdqul(nds, src, Assembler::AVX_512bit);
4626     Assembler::vpsubb(dst, dst, nds, vector_len);
4627   } else if ((src_enc < 16) && (nds_enc < 16)) {
4628     // use nds as scratch for dst
4629     evmovdqul(nds, dst, Assembler::AVX_512bit);
4630     Assembler::vpsubb(nds, nds, src, vector_len);
4631     evmovdqul(dst, nds, Assembler::AVX_512bit);
4632   } else if (dst_enc < 16) {
4633     // use nds as scatch for xmm0 to hold src
4634     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4635     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4636     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4637     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4638   } else {
4639     // worse case scenario, all regs are in the upper bank
4640     subptr(rsp, 64);
4641     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4642     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4643     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4644     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4645     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4646     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4647     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4648     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4649     addptr(rsp, 64);
4650   }
4651 }
4652 
4653 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4654   int dst_enc = dst->encoding();
4655   int nds_enc = nds->encoding();
4656   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4657     Assembler::vpsubb(dst, nds, src, vector_len);
4658   } else if (dst_enc < 16) {
4659     Assembler::vpsubb(dst, dst, src, vector_len);
4660   } else if (nds_enc < 16) {
4661     // implies dst_enc in upper bank with src as scratch
4662     evmovdqul(nds, dst, Assembler::AVX_512bit);
4663     Assembler::vpsubb(nds, nds, src, vector_len);
4664     evmovdqul(dst, nds, Assembler::AVX_512bit);
4665   } else {
4666     // worse case scenario, all regs in upper bank
4667     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4668     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4669     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4670     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4671   }
4672 }
4673 
4674 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4675   int dst_enc = dst->encoding();
4676   int nds_enc = nds->encoding();
4677   int src_enc = src->encoding();
4678   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4679     Assembler::vpsubw(dst, nds, src, vector_len);
4680   } else if ((dst_enc < 16) && (src_enc < 16)) {
4681     Assembler::vpsubw(dst, dst, src, vector_len);
4682   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4683     // use nds as scratch for src
4684     evmovdqul(nds, src, Assembler::AVX_512bit);
4685     Assembler::vpsubw(dst, dst, nds, vector_len);
4686   } else if ((src_enc < 16) && (nds_enc < 16)) {
4687     // use nds as scratch for dst
4688     evmovdqul(nds, dst, Assembler::AVX_512bit);
4689     Assembler::vpsubw(nds, nds, src, vector_len);
4690     evmovdqul(dst, nds, Assembler::AVX_512bit);
4691   } else if (dst_enc < 16) {
4692     // use nds as scatch for xmm0 to hold src
4693     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4694     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4695     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4696     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4697   } else {
4698     // worse case scenario, all regs are in the upper bank
4699     subptr(rsp, 64);
4700     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4701     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4702     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4703     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4704     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4705     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4706     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4707     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4708     addptr(rsp, 64);
4709   }
4710 }
4711 
4712 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4713   int dst_enc = dst->encoding();
4714   int nds_enc = nds->encoding();
4715   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4716     Assembler::vpsubw(dst, nds, src, vector_len);
4717   } else if (dst_enc < 16) {
4718     Assembler::vpsubw(dst, dst, src, vector_len);
4719   } else if (nds_enc < 16) {
4720     // implies dst_enc in upper bank with src as scratch
4721     evmovdqul(nds, dst, Assembler::AVX_512bit);
4722     Assembler::vpsubw(nds, nds, src, vector_len);
4723     evmovdqul(dst, nds, Assembler::AVX_512bit);
4724   } else {
4725     // worse case scenario, all regs in upper bank
4726     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4727     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4728     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4729     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4730   }
4731 }
4732 
4733 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4734   int dst_enc = dst->encoding();
4735   int nds_enc = nds->encoding();
4736   int shift_enc = shift->encoding();
4737   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4738     Assembler::vpsraw(dst, nds, shift, vector_len);
4739   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4740     Assembler::vpsraw(dst, dst, shift, vector_len);
4741   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4742     // use nds_enc as scratch with shift
4743     evmovdqul(nds, shift, Assembler::AVX_512bit);
4744     Assembler::vpsraw(dst, dst, nds, vector_len);
4745   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4746     // use nds as scratch with dst
4747     evmovdqul(nds, dst, Assembler::AVX_512bit);
4748     Assembler::vpsraw(nds, nds, shift, vector_len);
4749     evmovdqul(dst, nds, Assembler::AVX_512bit);
4750   } else if (dst_enc < 16) {
4751     // use nds to save a copy of xmm0 and hold shift
4752     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4753     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4754     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4755     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4756   } else if (nds_enc < 16) {
4757     // use nds as dest as temps
4758     evmovdqul(nds, dst, Assembler::AVX_512bit);
4759     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4760     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4761     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4762     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4763     evmovdqul(dst, nds, Assembler::AVX_512bit);
4764   } else {
4765     // worse case scenario, all regs are in the upper bank
4766     subptr(rsp, 64);
4767     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4768     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4769     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4770     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4771     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4772     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4773     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4774     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4775     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4776     addptr(rsp, 64);
4777   }
4778 }
4779 
4780 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4781   int dst_enc = dst->encoding();
4782   int nds_enc = nds->encoding();
4783   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4784     Assembler::vpsraw(dst, nds, shift, vector_len);
4785   } else if (dst_enc < 16) {
4786     Assembler::vpsraw(dst, dst, shift, vector_len);
4787   } else if (nds_enc < 16) {
4788     // use nds as scratch
4789     evmovdqul(nds, dst, Assembler::AVX_512bit);
4790     Assembler::vpsraw(nds, nds, shift, vector_len);
4791     evmovdqul(dst, nds, Assembler::AVX_512bit);
4792   } else {
4793     // use nds as scratch for xmm0
4794     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4795     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4796     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4797     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4798   }
4799 }
4800 
4801 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4802   int dst_enc = dst->encoding();
4803   int nds_enc = nds->encoding();
4804   int shift_enc = shift->encoding();
4805   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4806     Assembler::vpsrlw(dst, nds, shift, vector_len);
4807   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4808     Assembler::vpsrlw(dst, dst, shift, vector_len);
4809   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4810     // use nds_enc as scratch with shift
4811     evmovdqul(nds, shift, Assembler::AVX_512bit);
4812     Assembler::vpsrlw(dst, dst, nds, vector_len);
4813   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4814     // use nds as scratch with dst
4815     evmovdqul(nds, dst, Assembler::AVX_512bit);
4816     Assembler::vpsrlw(nds, nds, shift, vector_len);
4817     evmovdqul(dst, nds, Assembler::AVX_512bit);
4818   } else if (dst_enc < 16) {
4819     // use nds to save a copy of xmm0 and hold shift
4820     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4821     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4822     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4823     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4824   } else if (nds_enc < 16) {
4825     // use nds as dest as temps
4826     evmovdqul(nds, dst, Assembler::AVX_512bit);
4827     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4828     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4829     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4830     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4831     evmovdqul(dst, nds, Assembler::AVX_512bit);
4832   } else {
4833     // worse case scenario, all regs are in the upper bank
4834     subptr(rsp, 64);
4835     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4836     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4837     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4838     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4839     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4840     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4841     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4842     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4843     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4844     addptr(rsp, 64);
4845   }
4846 }
4847 
4848 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4849   int dst_enc = dst->encoding();
4850   int nds_enc = nds->encoding();
4851   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4852     Assembler::vpsrlw(dst, nds, shift, vector_len);
4853   } else if (dst_enc < 16) {
4854     Assembler::vpsrlw(dst, dst, shift, vector_len);
4855   } else if (nds_enc < 16) {
4856     // use nds as scratch
4857     evmovdqul(nds, dst, Assembler::AVX_512bit);
4858     Assembler::vpsrlw(nds, nds, shift, vector_len);
4859     evmovdqul(dst, nds, Assembler::AVX_512bit);
4860   } else {
4861     // use nds as scratch for xmm0
4862     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4863     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4864     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4865     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4866   }
4867 }
4868 
4869 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4870   int dst_enc = dst->encoding();
4871   int nds_enc = nds->encoding();
4872   int shift_enc = shift->encoding();
4873   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4874     Assembler::vpsllw(dst, nds, shift, vector_len);
4875   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4876     Assembler::vpsllw(dst, dst, shift, vector_len);
4877   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4878     // use nds_enc as scratch with shift
4879     evmovdqul(nds, shift, Assembler::AVX_512bit);
4880     Assembler::vpsllw(dst, dst, nds, vector_len);
4881   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4882     // use nds as scratch with dst
4883     evmovdqul(nds, dst, Assembler::AVX_512bit);
4884     Assembler::vpsllw(nds, nds, shift, vector_len);
4885     evmovdqul(dst, nds, Assembler::AVX_512bit);
4886   } else if (dst_enc < 16) {
4887     // use nds to save a copy of xmm0 and hold shift
4888     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4889     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4890     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4891     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4892   } else if (nds_enc < 16) {
4893     // use nds as dest as temps
4894     evmovdqul(nds, dst, Assembler::AVX_512bit);
4895     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4896     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4897     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4898     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4899     evmovdqul(dst, nds, Assembler::AVX_512bit);
4900   } else {
4901     // worse case scenario, all regs are in the upper bank
4902     subptr(rsp, 64);
4903     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4904     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4905     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4906     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4907     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4908     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4909     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4910     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4911     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4912     addptr(rsp, 64);
4913   }
4914 }
4915 
4916 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4917   int dst_enc = dst->encoding();
4918   int nds_enc = nds->encoding();
4919   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4920     Assembler::vpsllw(dst, nds, shift, vector_len);
4921   } else if (dst_enc < 16) {
4922     Assembler::vpsllw(dst, dst, shift, vector_len);
4923   } else if (nds_enc < 16) {
4924     // use nds as scratch
4925     evmovdqul(nds, dst, Assembler::AVX_512bit);
4926     Assembler::vpsllw(nds, nds, shift, vector_len);
4927     evmovdqul(dst, nds, Assembler::AVX_512bit);
4928   } else {
4929     // use nds as scratch for xmm0
4930     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4931     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4932     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4933     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4934   }
4935 }
4936 
4937 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4938   int dst_enc = dst->encoding();
4939   int src_enc = src->encoding();
4940   if ((dst_enc < 16) && (src_enc < 16)) {
4941     Assembler::vptest(dst, src);
4942   } else if (src_enc < 16) {
4943     subptr(rsp, 64);
4944     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4945     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4946     Assembler::vptest(xmm0, src);
4947     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4948     addptr(rsp, 64);
4949   } else if (dst_enc < 16) {
4950     subptr(rsp, 64);
4951     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4952     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4953     Assembler::vptest(dst, xmm0);
4954     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4955     addptr(rsp, 64);
4956   } else {
4957     subptr(rsp, 64);
4958     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4959     subptr(rsp, 64);
4960     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4961     movdqu(xmm0, src);
4962     movdqu(xmm1, dst);
4963     Assembler::vptest(xmm1, xmm0);
4964     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4965     addptr(rsp, 64);
4966     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4967     addptr(rsp, 64);
4968   }
4969 }
4970 
4971 // This instruction exists within macros, ergo we cannot control its input
4972 // when emitted through those patterns.
4973 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4974   if (VM_Version::supports_avx512nobw()) {
4975     int dst_enc = dst->encoding();
4976     int src_enc = src->encoding();
4977     if (dst_enc == src_enc) {
4978       if (dst_enc < 16) {
4979         Assembler::punpcklbw(dst, src);
4980       } else {
4981         subptr(rsp, 64);
4982         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4983         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4984         Assembler::punpcklbw(xmm0, xmm0);
4985         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4986         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4987         addptr(rsp, 64);
4988       }
4989     } else {
4990       if ((src_enc < 16) && (dst_enc < 16)) {
4991         Assembler::punpcklbw(dst, src);
4992       } else if (src_enc < 16) {
4993         subptr(rsp, 64);
4994         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4995         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4996         Assembler::punpcklbw(xmm0, src);
4997         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4998         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4999         addptr(rsp, 64);
5000       } else if (dst_enc < 16) {
5001         subptr(rsp, 64);
5002         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5003         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5004         Assembler::punpcklbw(dst, xmm0);
5005         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5006         addptr(rsp, 64);
5007       } else {
5008         subptr(rsp, 64);
5009         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5010         subptr(rsp, 64);
5011         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5012         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5013         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5014         Assembler::punpcklbw(xmm0, xmm1);
5015         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5016         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5017         addptr(rsp, 64);
5018         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5019         addptr(rsp, 64);
5020       }
5021     }
5022   } else {
5023     Assembler::punpcklbw(dst, src);
5024   }
5025 }
5026 
5027 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
5028   if (VM_Version::supports_avx512vl()) {
5029     Assembler::pshufd(dst, src, mode);
5030   } else {
5031     int dst_enc = dst->encoding();
5032     if (dst_enc < 16) {
5033       Assembler::pshufd(dst, src, mode);
5034     } else {
5035       subptr(rsp, 64);
5036       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5037       Assembler::pshufd(xmm0, src, mode);
5038       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5039       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5040       addptr(rsp, 64);
5041     }
5042   }
5043 }
5044 
5045 // This instruction exists within macros, ergo we cannot control its input
5046 // when emitted through those patterns.
5047 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5048   if (VM_Version::supports_avx512nobw()) {
5049     int dst_enc = dst->encoding();
5050     int src_enc = src->encoding();
5051     if (dst_enc == src_enc) {
5052       if (dst_enc < 16) {
5053         Assembler::pshuflw(dst, src, mode);
5054       } else {
5055         subptr(rsp, 64);
5056         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5057         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5058         Assembler::pshuflw(xmm0, xmm0, mode);
5059         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5060         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5061         addptr(rsp, 64);
5062       }
5063     } else {
5064       if ((src_enc < 16) && (dst_enc < 16)) {
5065         Assembler::pshuflw(dst, src, mode);
5066       } else if (src_enc < 16) {
5067         subptr(rsp, 64);
5068         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5069         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5070         Assembler::pshuflw(xmm0, src, mode);
5071         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5072         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5073         addptr(rsp, 64);
5074       } else if (dst_enc < 16) {
5075         subptr(rsp, 64);
5076         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5077         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5078         Assembler::pshuflw(dst, xmm0, mode);
5079         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5080         addptr(rsp, 64);
5081       } else {
5082         subptr(rsp, 64);
5083         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5084         subptr(rsp, 64);
5085         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5086         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5087         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5088         Assembler::pshuflw(xmm0, xmm1, mode);
5089         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5090         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5091         addptr(rsp, 64);
5092         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5093         addptr(rsp, 64);
5094       }
5095     }
5096   } else {
5097     Assembler::pshuflw(dst, src, mode);
5098   }
5099 }
5100 
5101 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5102   if (reachable(src)) {
5103     vandpd(dst, nds, as_Address(src), vector_len);
5104   } else {
5105     lea(rscratch1, src);
5106     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5107   }
5108 }
5109 
5110 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5111   if (reachable(src)) {
5112     vandps(dst, nds, as_Address(src), vector_len);
5113   } else {
5114     lea(rscratch1, src);
5115     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5116   }
5117 }
5118 
5119 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5120   if (reachable(src)) {
5121     vdivsd(dst, nds, as_Address(src));
5122   } else {
5123     lea(rscratch1, src);
5124     vdivsd(dst, nds, Address(rscratch1, 0));
5125   }
5126 }
5127 
5128 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5129   if (reachable(src)) {
5130     vdivss(dst, nds, as_Address(src));
5131   } else {
5132     lea(rscratch1, src);
5133     vdivss(dst, nds, Address(rscratch1, 0));
5134   }
5135 }
5136 
5137 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5138   if (reachable(src)) {
5139     vmulsd(dst, nds, as_Address(src));
5140   } else {
5141     lea(rscratch1, src);
5142     vmulsd(dst, nds, Address(rscratch1, 0));
5143   }
5144 }
5145 
5146 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5147   if (reachable(src)) {
5148     vmulss(dst, nds, as_Address(src));
5149   } else {
5150     lea(rscratch1, src);
5151     vmulss(dst, nds, Address(rscratch1, 0));
5152   }
5153 }
5154 
5155 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5156   if (reachable(src)) {
5157     vsubsd(dst, nds, as_Address(src));
5158   } else {
5159     lea(rscratch1, src);
5160     vsubsd(dst, nds, Address(rscratch1, 0));
5161   }
5162 }
5163 
5164 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5165   if (reachable(src)) {
5166     vsubss(dst, nds, as_Address(src));
5167   } else {
5168     lea(rscratch1, src);
5169     vsubss(dst, nds, Address(rscratch1, 0));
5170   }
5171 }
5172 
5173 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5174   int nds_enc = nds->encoding();
5175   int dst_enc = dst->encoding();
5176   bool dst_upper_bank = (dst_enc > 15);
5177   bool nds_upper_bank = (nds_enc > 15);
5178   if (VM_Version::supports_avx512novl() &&
5179       (nds_upper_bank || dst_upper_bank)) {
5180     if (dst_upper_bank) {
5181       subptr(rsp, 64);
5182       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5183       movflt(xmm0, nds);
5184       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5185       movflt(dst, xmm0);
5186       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5187       addptr(rsp, 64);
5188     } else {
5189       movflt(dst, nds);
5190       vxorps(dst, dst, src, Assembler::AVX_128bit);
5191     }
5192   } else {
5193     vxorps(dst, nds, src, Assembler::AVX_128bit);
5194   }
5195 }
5196 
5197 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5198   int nds_enc = nds->encoding();
5199   int dst_enc = dst->encoding();
5200   bool dst_upper_bank = (dst_enc > 15);
5201   bool nds_upper_bank = (nds_enc > 15);
5202   if (VM_Version::supports_avx512novl() &&
5203       (nds_upper_bank || dst_upper_bank)) {
5204     if (dst_upper_bank) {
5205       subptr(rsp, 64);
5206       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5207       movdbl(xmm0, nds);
5208       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5209       movdbl(dst, xmm0);
5210       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5211       addptr(rsp, 64);
5212     } else {
5213       movdbl(dst, nds);
5214       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5215     }
5216   } else {
5217     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5218   }
5219 }
5220 
5221 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5222   if (reachable(src)) {
5223     vxorpd(dst, nds, as_Address(src), vector_len);
5224   } else {
5225     lea(rscratch1, src);
5226     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5227   }
5228 }
5229 
5230 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5231   if (reachable(src)) {
5232     vxorps(dst, nds, as_Address(src), vector_len);
5233   } else {
5234     lea(rscratch1, src);
5235     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5236   }
5237 }
5238 
5239 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5240   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5241   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5242   // The inverted mask is sign-extended
5243   andptr(possibly_jweak, inverted_jweak_mask);
5244 }
5245 
5246 void MacroAssembler::resolve_jobject(Register value,
5247                                      Register thread,
5248                                      Register tmp) {
5249   assert_different_registers(value, thread, tmp);
5250   Label done, not_weak;
5251   testptr(value, value);
5252   jcc(Assembler::zero, done);                // Use NULL as-is.
5253   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5254   jcc(Assembler::zero, not_weak);
5255   // Resolve jweak.
5256   access_load_at(T_OBJECT, IN_ROOT | ON_PHANTOM_OOP_REF,
5257                  value, Address(value, -JNIHandles::weak_tag_value), tmp, thread);
5258   verify_oop(value);
5259   jmp(done);
5260   bind(not_weak);
5261   // Resolve (untagged) jobject.
5262   access_load_at(T_OBJECT, IN_CONCURRENT_ROOT,
5263                  value, Address(value, 0), tmp, thread);
5264   verify_oop(value);
5265   bind(done);
5266 }
5267 
5268 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5269   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5270 }
5271 
5272 // Force generation of a 4 byte immediate value even if it fits into 8bit
5273 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5274   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5275 }
5276 
5277 void MacroAssembler::subptr(Register dst, Register src) {
5278   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5279 }
5280 
5281 // C++ bool manipulation
5282 void MacroAssembler::testbool(Register dst) {
5283   if(sizeof(bool) == 1)
5284     testb(dst, 0xff);
5285   else if(sizeof(bool) == 2) {
5286     // testw implementation needed for two byte bools
5287     ShouldNotReachHere();
5288   } else if(sizeof(bool) == 4)
5289     testl(dst, dst);
5290   else
5291     // unsupported
5292     ShouldNotReachHere();
5293 }
5294 
5295 void MacroAssembler::testptr(Register dst, Register src) {
5296   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5297 }
5298 
5299 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5300 void MacroAssembler::tlab_allocate(Register obj,
5301                                    Register var_size_in_bytes,
5302                                    int con_size_in_bytes,
5303                                    Register t1,
5304                                    Register t2,
5305                                    Label& slow_case) {
5306   assert_different_registers(obj, t1, t2);
5307   assert_different_registers(obj, var_size_in_bytes, t1);
5308   Register end = t2;
5309   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5310 
5311   verify_tlab();
5312 
5313   NOT_LP64(get_thread(thread));
5314 
5315   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5316   if (var_size_in_bytes == noreg) {
5317     lea(end, Address(obj, con_size_in_bytes));
5318   } else {
5319     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5320   }
5321   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5322   jcc(Assembler::above, slow_case);
5323 
5324   // update the tlab top pointer
5325   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5326 
5327   // recover var_size_in_bytes if necessary
5328   if (var_size_in_bytes == end) {
5329     subptr(var_size_in_bytes, obj);
5330   }
5331   verify_tlab();
5332 }
5333 
5334 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5335 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5336   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5337   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5338   Label done;
5339 
5340   testptr(length_in_bytes, length_in_bytes);
5341   jcc(Assembler::zero, done);
5342 
5343   // initialize topmost word, divide index by 2, check if odd and test if zero
5344   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5345 #ifdef ASSERT
5346   {
5347     Label L;
5348     testptr(length_in_bytes, BytesPerWord - 1);
5349     jcc(Assembler::zero, L);
5350     stop("length must be a multiple of BytesPerWord");
5351     bind(L);
5352   }
5353 #endif
5354   Register index = length_in_bytes;
5355   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5356   if (UseIncDec) {
5357     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5358   } else {
5359     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5360     shrptr(index, 1);
5361   }
5362 #ifndef _LP64
5363   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5364   {
5365     Label even;
5366     // note: if index was a multiple of 8, then it cannot
5367     //       be 0 now otherwise it must have been 0 before
5368     //       => if it is even, we don't need to check for 0 again
5369     jcc(Assembler::carryClear, even);
5370     // clear topmost word (no jump would be needed if conditional assignment worked here)
5371     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5372     // index could be 0 now, must check again
5373     jcc(Assembler::zero, done);
5374     bind(even);
5375   }
5376 #endif // !_LP64
5377   // initialize remaining object fields: index is a multiple of 2 now
5378   {
5379     Label loop;
5380     bind(loop);
5381     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5382     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5383     decrement(index);
5384     jcc(Assembler::notZero, loop);
5385   }
5386 
5387   bind(done);
5388 }
5389 
5390 void MacroAssembler::incr_allocated_bytes(Register thread,
5391                                           Register var_size_in_bytes,
5392                                           int con_size_in_bytes,
5393                                           Register t1) {
5394   if (!thread->is_valid()) {
5395 #ifdef _LP64
5396     thread = r15_thread;
5397 #else
5398     assert(t1->is_valid(), "need temp reg");
5399     thread = t1;
5400     get_thread(thread);
5401 #endif
5402   }
5403 
5404 #ifdef _LP64
5405   if (var_size_in_bytes->is_valid()) {
5406     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5407   } else {
5408     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5409   }
5410 #else
5411   if (var_size_in_bytes->is_valid()) {
5412     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5413   } else {
5414     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5415   }
5416   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5417 #endif
5418 }
5419 
5420 // Look up the method for a megamorphic invokeinterface call.
5421 // The target method is determined by <intf_klass, itable_index>.
5422 // The receiver klass is in recv_klass.
5423 // On success, the result will be in method_result, and execution falls through.
5424 // On failure, execution transfers to the given label.
5425 void MacroAssembler::lookup_interface_method(Register recv_klass,
5426                                              Register intf_klass,
5427                                              RegisterOrConstant itable_index,
5428                                              Register method_result,
5429                                              Register scan_temp,
5430                                              Label& L_no_such_interface,
5431                                              bool return_method) {
5432   assert_different_registers(recv_klass, intf_klass, scan_temp);
5433   assert_different_registers(method_result, intf_klass, scan_temp);
5434   assert(recv_klass != method_result || !return_method,
5435          "recv_klass can be destroyed when method isn't needed");
5436 
5437   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5438          "caller must use same register for non-constant itable index as for method");
5439 
5440   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5441   int vtable_base = in_bytes(Klass::vtable_start_offset());
5442   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5443   int scan_step   = itableOffsetEntry::size() * wordSize;
5444   int vte_size    = vtableEntry::size_in_bytes();
5445   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5446   assert(vte_size == wordSize, "else adjust times_vte_scale");
5447 
5448   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5449 
5450   // %%% Could store the aligned, prescaled offset in the klassoop.
5451   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5452 
5453   if (return_method) {
5454     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5455     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5456     lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5457   }
5458 
5459   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5460   //   if (scan->interface() == intf) {
5461   //     result = (klass + scan->offset() + itable_index);
5462   //   }
5463   // }
5464   Label search, found_method;
5465 
5466   for (int peel = 1; peel >= 0; peel--) {
5467     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5468     cmpptr(intf_klass, method_result);
5469 
5470     if (peel) {
5471       jccb(Assembler::equal, found_method);
5472     } else {
5473       jccb(Assembler::notEqual, search);
5474       // (invert the test to fall through to found_method...)
5475     }
5476 
5477     if (!peel)  break;
5478 
5479     bind(search);
5480 
5481     // Check that the previous entry is non-null.  A null entry means that
5482     // the receiver class doesn't implement the interface, and wasn't the
5483     // same as when the caller was compiled.
5484     testptr(method_result, method_result);
5485     jcc(Assembler::zero, L_no_such_interface);
5486     addptr(scan_temp, scan_step);
5487   }
5488 
5489   bind(found_method);
5490 
5491   if (return_method) {
5492     // Got a hit.
5493     movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5494     movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5495   }
5496 }
5497 
5498 
5499 // virtual method calling
5500 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5501                                            RegisterOrConstant vtable_index,
5502                                            Register method_result) {
5503   const int base = in_bytes(Klass::vtable_start_offset());
5504   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5505   Address vtable_entry_addr(recv_klass,
5506                             vtable_index, Address::times_ptr,
5507                             base + vtableEntry::method_offset_in_bytes());
5508   movptr(method_result, vtable_entry_addr);
5509 }
5510 
5511 
5512 void MacroAssembler::check_klass_subtype(Register sub_klass,
5513                            Register super_klass,
5514                            Register temp_reg,
5515                            Label& L_success) {
5516   Label L_failure;
5517   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5518   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5519   bind(L_failure);
5520 }
5521 
5522 
5523 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5524                                                    Register super_klass,
5525                                                    Register temp_reg,
5526                                                    Label* L_success,
5527                                                    Label* L_failure,
5528                                                    Label* L_slow_path,
5529                                         RegisterOrConstant super_check_offset) {
5530   assert_different_registers(sub_klass, super_klass, temp_reg);
5531   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5532   if (super_check_offset.is_register()) {
5533     assert_different_registers(sub_klass, super_klass,
5534                                super_check_offset.as_register());
5535   } else if (must_load_sco) {
5536     assert(temp_reg != noreg, "supply either a temp or a register offset");
5537   }
5538 
5539   Label L_fallthrough;
5540   int label_nulls = 0;
5541   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5542   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5543   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5544   assert(label_nulls <= 1, "at most one NULL in the batch");
5545 
5546   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5547   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5548   Address super_check_offset_addr(super_klass, sco_offset);
5549 
5550   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5551   // range of a jccb.  If this routine grows larger, reconsider at
5552   // least some of these.
5553 #define local_jcc(assembler_cond, label)                                \
5554   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5555   else                             jcc( assembler_cond, label) /*omit semi*/
5556 
5557   // Hacked jmp, which may only be used just before L_fallthrough.
5558 #define final_jmp(label)                                                \
5559   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5560   else                            jmp(label)                /*omit semi*/
5561 
5562   // If the pointers are equal, we are done (e.g., String[] elements).
5563   // This self-check enables sharing of secondary supertype arrays among
5564   // non-primary types such as array-of-interface.  Otherwise, each such
5565   // type would need its own customized SSA.
5566   // We move this check to the front of the fast path because many
5567   // type checks are in fact trivially successful in this manner,
5568   // so we get a nicely predicted branch right at the start of the check.
5569   cmpptr(sub_klass, super_klass);
5570   local_jcc(Assembler::equal, *L_success);
5571 
5572   // Check the supertype display:
5573   if (must_load_sco) {
5574     // Positive movl does right thing on LP64.
5575     movl(temp_reg, super_check_offset_addr);
5576     super_check_offset = RegisterOrConstant(temp_reg);
5577   }
5578   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5579   cmpptr(super_klass, super_check_addr); // load displayed supertype
5580 
5581   // This check has worked decisively for primary supers.
5582   // Secondary supers are sought in the super_cache ('super_cache_addr').
5583   // (Secondary supers are interfaces and very deeply nested subtypes.)
5584   // This works in the same check above because of a tricky aliasing
5585   // between the super_cache and the primary super display elements.
5586   // (The 'super_check_addr' can address either, as the case requires.)
5587   // Note that the cache is updated below if it does not help us find
5588   // what we need immediately.
5589   // So if it was a primary super, we can just fail immediately.
5590   // Otherwise, it's the slow path for us (no success at this point).
5591 
5592   if (super_check_offset.is_register()) {
5593     local_jcc(Assembler::equal, *L_success);
5594     cmpl(super_check_offset.as_register(), sc_offset);
5595     if (L_failure == &L_fallthrough) {
5596       local_jcc(Assembler::equal, *L_slow_path);
5597     } else {
5598       local_jcc(Assembler::notEqual, *L_failure);
5599       final_jmp(*L_slow_path);
5600     }
5601   } else if (super_check_offset.as_constant() == sc_offset) {
5602     // Need a slow path; fast failure is impossible.
5603     if (L_slow_path == &L_fallthrough) {
5604       local_jcc(Assembler::equal, *L_success);
5605     } else {
5606       local_jcc(Assembler::notEqual, *L_slow_path);
5607       final_jmp(*L_success);
5608     }
5609   } else {
5610     // No slow path; it's a fast decision.
5611     if (L_failure == &L_fallthrough) {
5612       local_jcc(Assembler::equal, *L_success);
5613     } else {
5614       local_jcc(Assembler::notEqual, *L_failure);
5615       final_jmp(*L_success);
5616     }
5617   }
5618 
5619   bind(L_fallthrough);
5620 
5621 #undef local_jcc
5622 #undef final_jmp
5623 }
5624 
5625 
5626 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5627                                                    Register super_klass,
5628                                                    Register temp_reg,
5629                                                    Register temp2_reg,
5630                                                    Label* L_success,
5631                                                    Label* L_failure,
5632                                                    bool set_cond_codes) {
5633   assert_different_registers(sub_klass, super_klass, temp_reg);
5634   if (temp2_reg != noreg)
5635     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5636 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5637 
5638   Label L_fallthrough;
5639   int label_nulls = 0;
5640   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5641   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5642   assert(label_nulls <= 1, "at most one NULL in the batch");
5643 
5644   // a couple of useful fields in sub_klass:
5645   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5646   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5647   Address secondary_supers_addr(sub_klass, ss_offset);
5648   Address super_cache_addr(     sub_klass, sc_offset);
5649 
5650   // Do a linear scan of the secondary super-klass chain.
5651   // This code is rarely used, so simplicity is a virtue here.
5652   // The repne_scan instruction uses fixed registers, which we must spill.
5653   // Don't worry too much about pre-existing connections with the input regs.
5654 
5655   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5656   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5657 
5658   // Get super_klass value into rax (even if it was in rdi or rcx).
5659   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5660   if (super_klass != rax || UseCompressedOops) {
5661     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5662     mov(rax, super_klass);
5663   }
5664   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5665   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5666 
5667 #ifndef PRODUCT
5668   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5669   ExternalAddress pst_counter_addr((address) pst_counter);
5670   NOT_LP64(  incrementl(pst_counter_addr) );
5671   LP64_ONLY( lea(rcx, pst_counter_addr) );
5672   LP64_ONLY( incrementl(Address(rcx, 0)) );
5673 #endif //PRODUCT
5674 
5675   // We will consult the secondary-super array.
5676   movptr(rdi, secondary_supers_addr);
5677   // Load the array length.  (Positive movl does right thing on LP64.)
5678   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
5679   // Skip to start of data.
5680   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
5681 
5682   // Scan RCX words at [RDI] for an occurrence of RAX.
5683   // Set NZ/Z based on last compare.
5684   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
5685   // not change flags (only scas instruction which is repeated sets flags).
5686   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
5687 
5688     testptr(rax,rax); // Set Z = 0
5689     repne_scan();
5690 
5691   // Unspill the temp. registers:
5692   if (pushed_rdi)  pop(rdi);
5693   if (pushed_rcx)  pop(rcx);
5694   if (pushed_rax)  pop(rax);
5695 
5696   if (set_cond_codes) {
5697     // Special hack for the AD files:  rdi is guaranteed non-zero.
5698     assert(!pushed_rdi, "rdi must be left non-NULL");
5699     // Also, the condition codes are properly set Z/NZ on succeed/failure.
5700   }
5701 
5702   if (L_failure == &L_fallthrough)
5703         jccb(Assembler::notEqual, *L_failure);
5704   else  jcc(Assembler::notEqual, *L_failure);
5705 
5706   // Success.  Cache the super we found and proceed in triumph.
5707   movptr(super_cache_addr, super_klass);
5708 
5709   if (L_success != &L_fallthrough) {
5710     jmp(*L_success);
5711   }
5712 
5713 #undef IS_A_TEMP
5714 
5715   bind(L_fallthrough);
5716 }
5717 
5718 
5719 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
5720   if (VM_Version::supports_cmov()) {
5721     cmovl(cc, dst, src);
5722   } else {
5723     Label L;
5724     jccb(negate_condition(cc), L);
5725     movl(dst, src);
5726     bind(L);
5727   }
5728 }
5729 
5730 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
5731   if (VM_Version::supports_cmov()) {
5732     cmovl(cc, dst, src);
5733   } else {
5734     Label L;
5735     jccb(negate_condition(cc), L);
5736     movl(dst, src);
5737     bind(L);
5738   }
5739 }
5740 
5741 void MacroAssembler::verify_oop(Register reg, const char* s) {
5742   if (!VerifyOops) return;
5743 
5744   // Pass register number to verify_oop_subroutine
5745   const char* b = NULL;
5746   {
5747     ResourceMark rm;
5748     stringStream ss;
5749     ss.print("verify_oop: %s: %s", reg->name(), s);
5750     b = code_string(ss.as_string());
5751   }
5752   BLOCK_COMMENT("verify_oop {");
5753 #ifdef _LP64
5754   push(rscratch1);                    // save r10, trashed by movptr()
5755 #endif
5756   push(rax);                          // save rax,
5757   push(reg);                          // pass register argument
5758   ExternalAddress buffer((address) b);
5759   // avoid using pushptr, as it modifies scratch registers
5760   // and our contract is not to modify anything
5761   movptr(rax, buffer.addr());
5762   push(rax);
5763   // call indirectly to solve generation ordering problem
5764   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5765   call(rax);
5766   // Caller pops the arguments (oop, message) and restores rax, r10
5767   BLOCK_COMMENT("} verify_oop");
5768 }
5769 
5770 
5771 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
5772                                                       Register tmp,
5773                                                       int offset) {
5774   intptr_t value = *delayed_value_addr;
5775   if (value != 0)
5776     return RegisterOrConstant(value + offset);
5777 
5778   // load indirectly to solve generation ordering problem
5779   movptr(tmp, ExternalAddress((address) delayed_value_addr));
5780 
5781 #ifdef ASSERT
5782   { Label L;
5783     testptr(tmp, tmp);
5784     if (WizardMode) {
5785       const char* buf = NULL;
5786       {
5787         ResourceMark rm;
5788         stringStream ss;
5789         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
5790         buf = code_string(ss.as_string());
5791       }
5792       jcc(Assembler::notZero, L);
5793       STOP(buf);
5794     } else {
5795       jccb(Assembler::notZero, L);
5796       hlt();
5797     }
5798     bind(L);
5799   }
5800 #endif
5801 
5802   if (offset != 0)
5803     addptr(tmp, offset);
5804 
5805   return RegisterOrConstant(tmp);
5806 }
5807 
5808 
5809 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
5810                                          int extra_slot_offset) {
5811   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
5812   int stackElementSize = Interpreter::stackElementSize;
5813   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
5814 #ifdef ASSERT
5815   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
5816   assert(offset1 - offset == stackElementSize, "correct arithmetic");
5817 #endif
5818   Register             scale_reg    = noreg;
5819   Address::ScaleFactor scale_factor = Address::no_scale;
5820   if (arg_slot.is_constant()) {
5821     offset += arg_slot.as_constant() * stackElementSize;
5822   } else {
5823     scale_reg    = arg_slot.as_register();
5824     scale_factor = Address::times(stackElementSize);
5825   }
5826   offset += wordSize;           // return PC is on stack
5827   return Address(rsp, scale_reg, scale_factor, offset);
5828 }
5829 
5830 
5831 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
5832   if (!VerifyOops) return;
5833 
5834   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
5835   // Pass register number to verify_oop_subroutine
5836   const char* b = NULL;
5837   {
5838     ResourceMark rm;
5839     stringStream ss;
5840     ss.print("verify_oop_addr: %s", s);
5841     b = code_string(ss.as_string());
5842   }
5843 #ifdef _LP64
5844   push(rscratch1);                    // save r10, trashed by movptr()
5845 #endif
5846   push(rax);                          // save rax,
5847   // addr may contain rsp so we will have to adjust it based on the push
5848   // we just did (and on 64 bit we do two pushes)
5849   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
5850   // stores rax into addr which is backwards of what was intended.
5851   if (addr.uses(rsp)) {
5852     lea(rax, addr);
5853     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
5854   } else {
5855     pushptr(addr);
5856   }
5857 
5858   ExternalAddress buffer((address) b);
5859   // pass msg argument
5860   // avoid using pushptr, as it modifies scratch registers
5861   // and our contract is not to modify anything
5862   movptr(rax, buffer.addr());
5863   push(rax);
5864 
5865   // call indirectly to solve generation ordering problem
5866   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5867   call(rax);
5868   // Caller pops the arguments (addr, message) and restores rax, r10.
5869 }
5870 
5871 void MacroAssembler::verify_tlab() {
5872 #ifdef ASSERT
5873   if (UseTLAB && VerifyOops) {
5874     Label next, ok;
5875     Register t1 = rsi;
5876     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
5877 
5878     push(t1);
5879     NOT_LP64(push(thread_reg));
5880     NOT_LP64(get_thread(thread_reg));
5881 
5882     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5883     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5884     jcc(Assembler::aboveEqual, next);
5885     STOP("assert(top >= start)");
5886     should_not_reach_here();
5887 
5888     bind(next);
5889     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5890     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5891     jcc(Assembler::aboveEqual, ok);
5892     STOP("assert(top <= end)");
5893     should_not_reach_here();
5894 
5895     bind(ok);
5896     NOT_LP64(pop(thread_reg));
5897     pop(t1);
5898   }
5899 #endif
5900 }
5901 
5902 class ControlWord {
5903  public:
5904   int32_t _value;
5905 
5906   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
5907   int  precision_control() const       { return  (_value >>  8) & 3      ; }
5908   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5909   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5910   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5911   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5912   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5913   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5914 
5915   void print() const {
5916     // rounding control
5917     const char* rc;
5918     switch (rounding_control()) {
5919       case 0: rc = "round near"; break;
5920       case 1: rc = "round down"; break;
5921       case 2: rc = "round up  "; break;
5922       case 3: rc = "chop      "; break;
5923     };
5924     // precision control
5925     const char* pc;
5926     switch (precision_control()) {
5927       case 0: pc = "24 bits "; break;
5928       case 1: pc = "reserved"; break;
5929       case 2: pc = "53 bits "; break;
5930       case 3: pc = "64 bits "; break;
5931     };
5932     // flags
5933     char f[9];
5934     f[0] = ' ';
5935     f[1] = ' ';
5936     f[2] = (precision   ()) ? 'P' : 'p';
5937     f[3] = (underflow   ()) ? 'U' : 'u';
5938     f[4] = (overflow    ()) ? 'O' : 'o';
5939     f[5] = (zero_divide ()) ? 'Z' : 'z';
5940     f[6] = (denormalized()) ? 'D' : 'd';
5941     f[7] = (invalid     ()) ? 'I' : 'i';
5942     f[8] = '\x0';
5943     // output
5944     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
5945   }
5946 
5947 };
5948 
5949 class StatusWord {
5950  public:
5951   int32_t _value;
5952 
5953   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
5954   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
5955   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
5956   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
5957   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
5958   int  top() const                     { return  (_value >> 11) & 7      ; }
5959   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
5960   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
5961   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5962   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5963   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5964   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5965   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5966   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5967 
5968   void print() const {
5969     // condition codes
5970     char c[5];
5971     c[0] = (C3()) ? '3' : '-';
5972     c[1] = (C2()) ? '2' : '-';
5973     c[2] = (C1()) ? '1' : '-';
5974     c[3] = (C0()) ? '0' : '-';
5975     c[4] = '\x0';
5976     // flags
5977     char f[9];
5978     f[0] = (error_status()) ? 'E' : '-';
5979     f[1] = (stack_fault ()) ? 'S' : '-';
5980     f[2] = (precision   ()) ? 'P' : '-';
5981     f[3] = (underflow   ()) ? 'U' : '-';
5982     f[4] = (overflow    ()) ? 'O' : '-';
5983     f[5] = (zero_divide ()) ? 'Z' : '-';
5984     f[6] = (denormalized()) ? 'D' : '-';
5985     f[7] = (invalid     ()) ? 'I' : '-';
5986     f[8] = '\x0';
5987     // output
5988     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
5989   }
5990 
5991 };
5992 
5993 class TagWord {
5994  public:
5995   int32_t _value;
5996 
5997   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
5998 
5999   void print() const {
6000     printf("%04x", _value & 0xFFFF);
6001   }
6002 
6003 };
6004 
6005 class FPU_Register {
6006  public:
6007   int32_t _m0;
6008   int32_t _m1;
6009   int16_t _ex;
6010 
6011   bool is_indefinite() const           {
6012     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6013   }
6014 
6015   void print() const {
6016     char  sign = (_ex < 0) ? '-' : '+';
6017     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6018     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6019   };
6020 
6021 };
6022 
6023 class FPU_State {
6024  public:
6025   enum {
6026     register_size       = 10,
6027     number_of_registers =  8,
6028     register_mask       =  7
6029   };
6030 
6031   ControlWord  _control_word;
6032   StatusWord   _status_word;
6033   TagWord      _tag_word;
6034   int32_t      _error_offset;
6035   int32_t      _error_selector;
6036   int32_t      _data_offset;
6037   int32_t      _data_selector;
6038   int8_t       _register[register_size * number_of_registers];
6039 
6040   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6041   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6042 
6043   const char* tag_as_string(int tag) const {
6044     switch (tag) {
6045       case 0: return "valid";
6046       case 1: return "zero";
6047       case 2: return "special";
6048       case 3: return "empty";
6049     }
6050     ShouldNotReachHere();
6051     return NULL;
6052   }
6053 
6054   void print() const {
6055     // print computation registers
6056     { int t = _status_word.top();
6057       for (int i = 0; i < number_of_registers; i++) {
6058         int j = (i - t) & register_mask;
6059         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6060         st(j)->print();
6061         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6062       }
6063     }
6064     printf("\n");
6065     // print control registers
6066     printf("ctrl = "); _control_word.print(); printf("\n");
6067     printf("stat = "); _status_word .print(); printf("\n");
6068     printf("tags = "); _tag_word    .print(); printf("\n");
6069   }
6070 
6071 };
6072 
6073 class Flag_Register {
6074  public:
6075   int32_t _value;
6076 
6077   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6078   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6079   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6080   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6081   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6082   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6083   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6084 
6085   void print() const {
6086     // flags
6087     char f[8];
6088     f[0] = (overflow       ()) ? 'O' : '-';
6089     f[1] = (direction      ()) ? 'D' : '-';
6090     f[2] = (sign           ()) ? 'S' : '-';
6091     f[3] = (zero           ()) ? 'Z' : '-';
6092     f[4] = (auxiliary_carry()) ? 'A' : '-';
6093     f[5] = (parity         ()) ? 'P' : '-';
6094     f[6] = (carry          ()) ? 'C' : '-';
6095     f[7] = '\x0';
6096     // output
6097     printf("%08x  flags = %s", _value, f);
6098   }
6099 
6100 };
6101 
6102 class IU_Register {
6103  public:
6104   int32_t _value;
6105 
6106   void print() const {
6107     printf("%08x  %11d", _value, _value);
6108   }
6109 
6110 };
6111 
6112 class IU_State {
6113  public:
6114   Flag_Register _eflags;
6115   IU_Register   _rdi;
6116   IU_Register   _rsi;
6117   IU_Register   _rbp;
6118   IU_Register   _rsp;
6119   IU_Register   _rbx;
6120   IU_Register   _rdx;
6121   IU_Register   _rcx;
6122   IU_Register   _rax;
6123 
6124   void print() const {
6125     // computation registers
6126     printf("rax,  = "); _rax.print(); printf("\n");
6127     printf("rbx,  = "); _rbx.print(); printf("\n");
6128     printf("rcx  = "); _rcx.print(); printf("\n");
6129     printf("rdx  = "); _rdx.print(); printf("\n");
6130     printf("rdi  = "); _rdi.print(); printf("\n");
6131     printf("rsi  = "); _rsi.print(); printf("\n");
6132     printf("rbp,  = "); _rbp.print(); printf("\n");
6133     printf("rsp  = "); _rsp.print(); printf("\n");
6134     printf("\n");
6135     // control registers
6136     printf("flgs = "); _eflags.print(); printf("\n");
6137   }
6138 };
6139 
6140 
6141 class CPU_State {
6142  public:
6143   FPU_State _fpu_state;
6144   IU_State  _iu_state;
6145 
6146   void print() const {
6147     printf("--------------------------------------------------\n");
6148     _iu_state .print();
6149     printf("\n");
6150     _fpu_state.print();
6151     printf("--------------------------------------------------\n");
6152   }
6153 
6154 };
6155 
6156 
6157 static void _print_CPU_state(CPU_State* state) {
6158   state->print();
6159 };
6160 
6161 
6162 void MacroAssembler::print_CPU_state() {
6163   push_CPU_state();
6164   push(rsp);                // pass CPU state
6165   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6166   addptr(rsp, wordSize);       // discard argument
6167   pop_CPU_state();
6168 }
6169 
6170 
6171 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6172   static int counter = 0;
6173   FPU_State* fs = &state->_fpu_state;
6174   counter++;
6175   // For leaf calls, only verify that the top few elements remain empty.
6176   // We only need 1 empty at the top for C2 code.
6177   if( stack_depth < 0 ) {
6178     if( fs->tag_for_st(7) != 3 ) {
6179       printf("FPR7 not empty\n");
6180       state->print();
6181       assert(false, "error");
6182       return false;
6183     }
6184     return true;                // All other stack states do not matter
6185   }
6186 
6187   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6188          "bad FPU control word");
6189 
6190   // compute stack depth
6191   int i = 0;
6192   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6193   int d = i;
6194   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6195   // verify findings
6196   if (i != FPU_State::number_of_registers) {
6197     // stack not contiguous
6198     printf("%s: stack not contiguous at ST%d\n", s, i);
6199     state->print();
6200     assert(false, "error");
6201     return false;
6202   }
6203   // check if computed stack depth corresponds to expected stack depth
6204   if (stack_depth < 0) {
6205     // expected stack depth is -stack_depth or less
6206     if (d > -stack_depth) {
6207       // too many elements on the stack
6208       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6209       state->print();
6210       assert(false, "error");
6211       return false;
6212     }
6213   } else {
6214     // expected stack depth is stack_depth
6215     if (d != stack_depth) {
6216       // wrong stack depth
6217       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6218       state->print();
6219       assert(false, "error");
6220       return false;
6221     }
6222   }
6223   // everything is cool
6224   return true;
6225 }
6226 
6227 
6228 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6229   if (!VerifyFPU) return;
6230   push_CPU_state();
6231   push(rsp);                // pass CPU state
6232   ExternalAddress msg((address) s);
6233   // pass message string s
6234   pushptr(msg.addr());
6235   push(stack_depth);        // pass stack depth
6236   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6237   addptr(rsp, 3 * wordSize);   // discard arguments
6238   // check for error
6239   { Label L;
6240     testl(rax, rax);
6241     jcc(Assembler::notZero, L);
6242     int3();                  // break if error condition
6243     bind(L);
6244   }
6245   pop_CPU_state();
6246 }
6247 
6248 void MacroAssembler::restore_cpu_control_state_after_jni() {
6249   // Either restore the MXCSR register after returning from the JNI Call
6250   // or verify that it wasn't changed (with -Xcheck:jni flag).
6251   if (VM_Version::supports_sse()) {
6252     if (RestoreMXCSROnJNICalls) {
6253       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6254     } else if (CheckJNICalls) {
6255       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6256     }
6257   }
6258   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6259   vzeroupper();
6260   // Reset k1 to 0xffff.
6261   if (VM_Version::supports_evex()) {
6262     push(rcx);
6263     movl(rcx, 0xffff);
6264     kmovwl(k1, rcx);
6265     pop(rcx);
6266   }
6267 
6268 #ifndef _LP64
6269   // Either restore the x87 floating pointer control word after returning
6270   // from the JNI call or verify that it wasn't changed.
6271   if (CheckJNICalls) {
6272     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6273   }
6274 #endif // _LP64
6275 }
6276 
6277 // ((OopHandle)result).resolve();
6278 void MacroAssembler::resolve_oop_handle(Register result, Register tmp) {
6279   assert_different_registers(result, tmp);
6280 
6281   // Only 64 bit platforms support GCs that require a tmp register
6282   // Only IN_HEAP loads require a thread_tmp register
6283   // OopHandle::resolve is an indirection like jobject.
6284   access_load_at(T_OBJECT, IN_CONCURRENT_ROOT,
6285                  result, Address(result, 0), tmp, /*tmp_thread*/noreg);
6286 }
6287 
6288 void MacroAssembler::load_mirror(Register mirror, Register method, Register tmp) {
6289   // get mirror
6290   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6291   movptr(mirror, Address(method, Method::const_offset()));
6292   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6293   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6294   movptr(mirror, Address(mirror, mirror_offset));
6295   resolve_oop_handle(mirror, tmp);
6296 }
6297 
6298 void MacroAssembler::load_klass(Register dst, Register src) {
6299 #ifdef _LP64
6300   if (UseCompressedClassPointers) {
6301     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6302     decode_klass_not_null(dst);
6303   } else
6304 #endif
6305     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6306 }
6307 
6308 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6309   load_klass(dst, src);
6310   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6311 }
6312 
6313 void MacroAssembler::store_klass(Register dst, Register src) {
6314 #ifdef _LP64
6315   if (UseCompressedClassPointers) {
6316     encode_klass_not_null(src);
6317     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6318   } else
6319 #endif
6320     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6321 }
6322 
6323 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators, Register dst, Address src,
6324                                     Register tmp1, Register thread_tmp) {
6325   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6326   decorators = AccessInternal::decorator_fixup(decorators);
6327   bool as_raw = (decorators & AS_RAW) != 0;
6328   if (as_raw) {
6329     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
6330   } else {
6331     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
6332   }
6333 }
6334 
6335 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators, Address dst, Register src,
6336                                      Register tmp1, Register tmp2) {
6337   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6338   decorators = AccessInternal::decorator_fixup(decorators);
6339   bool as_raw = (decorators & AS_RAW) != 0;
6340   if (as_raw) {
6341     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, tmp2);
6342   } else {
6343     bs->store_at(this, decorators, type, dst, src, tmp1, tmp2);
6344   }
6345 }
6346 
6347 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
6348                                    Register thread_tmp, DecoratorSet decorators) {
6349   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
6350 }
6351 
6352 // Doesn't do verfication, generates fixed size code
6353 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
6354                                             Register thread_tmp, DecoratorSet decorators) {
6355   access_load_at(T_OBJECT, IN_HEAP | OOP_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
6356 }
6357 
6358 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
6359                                     Register tmp2, DecoratorSet decorators) {
6360   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
6361 }
6362 
6363 // Used for storing NULLs.
6364 void MacroAssembler::store_heap_oop_null(Address dst) {
6365   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg);
6366 }
6367 
6368 #ifdef _LP64
6369 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6370   if (UseCompressedClassPointers) {
6371     // Store to klass gap in destination
6372     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6373   }
6374 }
6375 
6376 #ifdef ASSERT
6377 void MacroAssembler::verify_heapbase(const char* msg) {
6378   assert (UseCompressedOops, "should be compressed");
6379   assert (Universe::heap() != NULL, "java heap should be initialized");
6380   if (CheckCompressedOops) {
6381     Label ok;
6382     push(rscratch1); // cmpptr trashes rscratch1
6383     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6384     jcc(Assembler::equal, ok);
6385     STOP(msg);
6386     bind(ok);
6387     pop(rscratch1);
6388   }
6389 }
6390 #endif
6391 
6392 // Algorithm must match oop.inline.hpp encode_heap_oop.
6393 void MacroAssembler::encode_heap_oop(Register r) {
6394 #ifdef ASSERT
6395   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6396 #endif
6397   verify_oop(r, "broken oop in encode_heap_oop");
6398   if (Universe::narrow_oop_base() == NULL) {
6399     if (Universe::narrow_oop_shift() != 0) {
6400       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6401       shrq(r, LogMinObjAlignmentInBytes);
6402     }
6403     return;
6404   }
6405   testq(r, r);
6406   cmovq(Assembler::equal, r, r12_heapbase);
6407   subq(r, r12_heapbase);
6408   shrq(r, LogMinObjAlignmentInBytes);
6409 }
6410 
6411 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6412 #ifdef ASSERT
6413   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6414   if (CheckCompressedOops) {
6415     Label ok;
6416     testq(r, r);
6417     jcc(Assembler::notEqual, ok);
6418     STOP("null oop passed to encode_heap_oop_not_null");
6419     bind(ok);
6420   }
6421 #endif
6422   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6423   if (Universe::narrow_oop_base() != NULL) {
6424     subq(r, r12_heapbase);
6425   }
6426   if (Universe::narrow_oop_shift() != 0) {
6427     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6428     shrq(r, LogMinObjAlignmentInBytes);
6429   }
6430 }
6431 
6432 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6433 #ifdef ASSERT
6434   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6435   if (CheckCompressedOops) {
6436     Label ok;
6437     testq(src, src);
6438     jcc(Assembler::notEqual, ok);
6439     STOP("null oop passed to encode_heap_oop_not_null2");
6440     bind(ok);
6441   }
6442 #endif
6443   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6444   if (dst != src) {
6445     movq(dst, src);
6446   }
6447   if (Universe::narrow_oop_base() != NULL) {
6448     subq(dst, r12_heapbase);
6449   }
6450   if (Universe::narrow_oop_shift() != 0) {
6451     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6452     shrq(dst, LogMinObjAlignmentInBytes);
6453   }
6454 }
6455 
6456 void  MacroAssembler::decode_heap_oop(Register r) {
6457 #ifdef ASSERT
6458   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6459 #endif
6460   if (Universe::narrow_oop_base() == NULL) {
6461     if (Universe::narrow_oop_shift() != 0) {
6462       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6463       shlq(r, LogMinObjAlignmentInBytes);
6464     }
6465   } else {
6466     Label done;
6467     shlq(r, LogMinObjAlignmentInBytes);
6468     jccb(Assembler::equal, done);
6469     addq(r, r12_heapbase);
6470     bind(done);
6471   }
6472   verify_oop(r, "broken oop in decode_heap_oop");
6473 }
6474 
6475 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6476   // Note: it will change flags
6477   assert (UseCompressedOops, "should only be used for compressed headers");
6478   assert (Universe::heap() != NULL, "java heap should be initialized");
6479   // Cannot assert, unverified entry point counts instructions (see .ad file)
6480   // vtableStubs also counts instructions in pd_code_size_limit.
6481   // Also do not verify_oop as this is called by verify_oop.
6482   if (Universe::narrow_oop_shift() != 0) {
6483     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6484     shlq(r, LogMinObjAlignmentInBytes);
6485     if (Universe::narrow_oop_base() != NULL) {
6486       addq(r, r12_heapbase);
6487     }
6488   } else {
6489     assert (Universe::narrow_oop_base() == NULL, "sanity");
6490   }
6491 }
6492 
6493 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6494   // Note: it will change flags
6495   assert (UseCompressedOops, "should only be used for compressed headers");
6496   assert (Universe::heap() != NULL, "java heap should be initialized");
6497   // Cannot assert, unverified entry point counts instructions (see .ad file)
6498   // vtableStubs also counts instructions in pd_code_size_limit.
6499   // Also do not verify_oop as this is called by verify_oop.
6500   if (Universe::narrow_oop_shift() != 0) {
6501     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6502     if (LogMinObjAlignmentInBytes == Address::times_8) {
6503       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6504     } else {
6505       if (dst != src) {
6506         movq(dst, src);
6507       }
6508       shlq(dst, LogMinObjAlignmentInBytes);
6509       if (Universe::narrow_oop_base() != NULL) {
6510         addq(dst, r12_heapbase);
6511       }
6512     }
6513   } else {
6514     assert (Universe::narrow_oop_base() == NULL, "sanity");
6515     if (dst != src) {
6516       movq(dst, src);
6517     }
6518   }
6519 }
6520 
6521 void MacroAssembler::encode_klass_not_null(Register r) {
6522   if (Universe::narrow_klass_base() != NULL) {
6523     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6524     assert(r != r12_heapbase, "Encoding a klass in r12");
6525     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6526     subq(r, r12_heapbase);
6527   }
6528   if (Universe::narrow_klass_shift() != 0) {
6529     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6530     shrq(r, LogKlassAlignmentInBytes);
6531   }
6532   if (Universe::narrow_klass_base() != NULL) {
6533     reinit_heapbase();
6534   }
6535 }
6536 
6537 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6538   if (dst == src) {
6539     encode_klass_not_null(src);
6540   } else {
6541     if (Universe::narrow_klass_base() != NULL) {
6542       mov64(dst, (int64_t)Universe::narrow_klass_base());
6543       negq(dst);
6544       addq(dst, src);
6545     } else {
6546       movptr(dst, src);
6547     }
6548     if (Universe::narrow_klass_shift() != 0) {
6549       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6550       shrq(dst, LogKlassAlignmentInBytes);
6551     }
6552   }
6553 }
6554 
6555 // Function instr_size_for_decode_klass_not_null() counts the instructions
6556 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6557 // when (Universe::heap() != NULL).  Hence, if the instructions they
6558 // generate change, then this method needs to be updated.
6559 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6560   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6561   if (Universe::narrow_klass_base() != NULL) {
6562     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6563     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6564   } else {
6565     // longest load decode klass function, mov64, leaq
6566     return 16;
6567   }
6568 }
6569 
6570 // !!! If the instructions that get generated here change then function
6571 // instr_size_for_decode_klass_not_null() needs to get updated.
6572 void  MacroAssembler::decode_klass_not_null(Register r) {
6573   // Note: it will change flags
6574   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6575   assert(r != r12_heapbase, "Decoding a klass in r12");
6576   // Cannot assert, unverified entry point counts instructions (see .ad file)
6577   // vtableStubs also counts instructions in pd_code_size_limit.
6578   // Also do not verify_oop as this is called by verify_oop.
6579   if (Universe::narrow_klass_shift() != 0) {
6580     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6581     shlq(r, LogKlassAlignmentInBytes);
6582   }
6583   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6584   if (Universe::narrow_klass_base() != NULL) {
6585     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6586     addq(r, r12_heapbase);
6587     reinit_heapbase();
6588   }
6589 }
6590 
6591 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6592   // Note: it will change flags
6593   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6594   if (dst == src) {
6595     decode_klass_not_null(dst);
6596   } else {
6597     // Cannot assert, unverified entry point counts instructions (see .ad file)
6598     // vtableStubs also counts instructions in pd_code_size_limit.
6599     // Also do not verify_oop as this is called by verify_oop.
6600     mov64(dst, (int64_t)Universe::narrow_klass_base());
6601     if (Universe::narrow_klass_shift() != 0) {
6602       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6603       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6604       leaq(dst, Address(dst, src, Address::times_8, 0));
6605     } else {
6606       addq(dst, src);
6607     }
6608   }
6609 }
6610 
6611 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6612   assert (UseCompressedOops, "should only be used for compressed headers");
6613   assert (Universe::heap() != NULL, "java heap should be initialized");
6614   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6615   int oop_index = oop_recorder()->find_index(obj);
6616   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6617   mov_narrow_oop(dst, oop_index, rspec);
6618 }
6619 
6620 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6621   assert (UseCompressedOops, "should only be used for compressed headers");
6622   assert (Universe::heap() != NULL, "java heap should be initialized");
6623   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6624   int oop_index = oop_recorder()->find_index(obj);
6625   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6626   mov_narrow_oop(dst, oop_index, rspec);
6627 }
6628 
6629 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6630   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6631   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6632   int klass_index = oop_recorder()->find_index(k);
6633   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6634   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6635 }
6636 
6637 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
6638   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6639   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6640   int klass_index = oop_recorder()->find_index(k);
6641   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6642   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6643 }
6644 
6645 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
6646   assert (UseCompressedOops, "should only be used for compressed headers");
6647   assert (Universe::heap() != NULL, "java heap should be initialized");
6648   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6649   int oop_index = oop_recorder()->find_index(obj);
6650   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6651   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6652 }
6653 
6654 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
6655   assert (UseCompressedOops, "should only be used for compressed headers");
6656   assert (Universe::heap() != NULL, "java heap should be initialized");
6657   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6658   int oop_index = oop_recorder()->find_index(obj);
6659   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6660   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6661 }
6662 
6663 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
6664   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6665   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6666   int klass_index = oop_recorder()->find_index(k);
6667   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6668   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6669 }
6670 
6671 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
6672   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6673   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6674   int klass_index = oop_recorder()->find_index(k);
6675   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6676   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6677 }
6678 
6679 void MacroAssembler::reinit_heapbase() {
6680   if (UseCompressedOops || UseCompressedClassPointers) {
6681     if (Universe::heap() != NULL) {
6682       if (Universe::narrow_oop_base() == NULL) {
6683         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
6684       } else {
6685         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
6686       }
6687     } else {
6688       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6689     }
6690   }
6691 }
6692 
6693 #endif // _LP64
6694 
6695 // C2 compiled method's prolog code.
6696 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
6697 
6698   // WARNING: Initial instruction MUST be 5 bytes or longer so that
6699   // NativeJump::patch_verified_entry will be able to patch out the entry
6700   // code safely. The push to verify stack depth is ok at 5 bytes,
6701   // the frame allocation can be either 3 or 6 bytes. So if we don't do
6702   // stack bang then we must use the 6 byte frame allocation even if
6703   // we have no frame. :-(
6704   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
6705 
6706   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6707   // Remove word for return addr
6708   framesize -= wordSize;
6709   stack_bang_size -= wordSize;
6710 
6711   // Calls to C2R adapters often do not accept exceptional returns.
6712   // We require that their callers must bang for them.  But be careful, because
6713   // some VM calls (such as call site linkage) can use several kilobytes of
6714   // stack.  But the stack safety zone should account for that.
6715   // See bugs 4446381, 4468289, 4497237.
6716   if (stack_bang_size > 0) {
6717     generate_stack_overflow_check(stack_bang_size);
6718 
6719     // We always push rbp, so that on return to interpreter rbp, will be
6720     // restored correctly and we can correct the stack.
6721     push(rbp);
6722     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6723     if (PreserveFramePointer) {
6724       mov(rbp, rsp);
6725     }
6726     // Remove word for ebp
6727     framesize -= wordSize;
6728 
6729     // Create frame
6730     if (framesize) {
6731       subptr(rsp, framesize);
6732     }
6733   } else {
6734     // Create frame (force generation of a 4 byte immediate value)
6735     subptr_imm32(rsp, framesize);
6736 
6737     // Save RBP register now.
6738     framesize -= wordSize;
6739     movptr(Address(rsp, framesize), rbp);
6740     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6741     if (PreserveFramePointer) {
6742       movptr(rbp, rsp);
6743       if (framesize > 0) {
6744         addptr(rbp, framesize);
6745       }
6746     }
6747   }
6748 
6749   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
6750     framesize -= wordSize;
6751     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
6752   }
6753 
6754 #ifndef _LP64
6755   // If method sets FPU control word do it now
6756   if (fp_mode_24b) {
6757     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
6758   }
6759   if (UseSSE >= 2 && VerifyFPU) {
6760     verify_FPU(0, "FPU stack must be clean on entry");
6761   }
6762 #endif
6763 
6764 #ifdef ASSERT
6765   if (VerifyStackAtCalls) {
6766     Label L;
6767     push(rax);
6768     mov(rax, rsp);
6769     andptr(rax, StackAlignmentInBytes-1);
6770     cmpptr(rax, StackAlignmentInBytes-wordSize);
6771     pop(rax);
6772     jcc(Assembler::equal, L);
6773     STOP("Stack is not properly aligned!");
6774     bind(L);
6775   }
6776 #endif
6777 
6778 }
6779 
6780 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
6781   // cnt - number of qwords (8-byte words).
6782   // base - start address, qword aligned.
6783   // is_large - if optimizers know cnt is larger than InitArrayShortSize
6784   assert(base==rdi, "base register must be edi for rep stos");
6785   assert(tmp==rax,   "tmp register must be eax for rep stos");
6786   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
6787   assert(InitArrayShortSize % BytesPerLong == 0,
6788     "InitArrayShortSize should be the multiple of BytesPerLong");
6789 
6790   Label DONE;
6791 
6792   xorptr(tmp, tmp);
6793 
6794   if (!is_large) {
6795     Label LOOP, LONG;
6796     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
6797     jccb(Assembler::greater, LONG);
6798 
6799     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6800 
6801     decrement(cnt);
6802     jccb(Assembler::negative, DONE); // Zero length
6803 
6804     // Use individual pointer-sized stores for small counts:
6805     BIND(LOOP);
6806     movptr(Address(base, cnt, Address::times_ptr), tmp);
6807     decrement(cnt);
6808     jccb(Assembler::greaterEqual, LOOP);
6809     jmpb(DONE);
6810 
6811     BIND(LONG);
6812   }
6813 
6814   // Use longer rep-prefixed ops for non-small counts:
6815   if (UseFastStosb) {
6816     shlptr(cnt, 3); // convert to number of bytes
6817     rep_stosb();
6818   } else {
6819     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6820     rep_stos();
6821   }
6822 
6823   BIND(DONE);
6824 }
6825 
6826 #ifdef COMPILER2
6827 
6828 // IndexOf for constant substrings with size >= 8 chars
6829 // which don't need to be loaded through stack.
6830 void MacroAssembler::string_indexofC8(Register str1, Register str2,
6831                                       Register cnt1, Register cnt2,
6832                                       int int_cnt2,  Register result,
6833                                       XMMRegister vec, Register tmp,
6834                                       int ae) {
6835   ShortBranchVerifier sbv(this);
6836   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6837   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6838 
6839   // This method uses the pcmpestri instruction with bound registers
6840   //   inputs:
6841   //     xmm - substring
6842   //     rax - substring length (elements count)
6843   //     mem - scanned string
6844   //     rdx - string length (elements count)
6845   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6846   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6847   //   outputs:
6848   //     rcx - matched index in string
6849   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6850   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
6851   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
6852   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
6853   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
6854 
6855   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
6856         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
6857         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
6858 
6859   // Note, inline_string_indexOf() generates checks:
6860   // if (substr.count > string.count) return -1;
6861   // if (substr.count == 0) return 0;
6862   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
6863 
6864   // Load substring.
6865   if (ae == StrIntrinsicNode::UL) {
6866     pmovzxbw(vec, Address(str2, 0));
6867   } else {
6868     movdqu(vec, Address(str2, 0));
6869   }
6870   movl(cnt2, int_cnt2);
6871   movptr(result, str1); // string addr
6872 
6873   if (int_cnt2 > stride) {
6874     jmpb(SCAN_TO_SUBSTR);
6875 
6876     // Reload substr for rescan, this code
6877     // is executed only for large substrings (> 8 chars)
6878     bind(RELOAD_SUBSTR);
6879     if (ae == StrIntrinsicNode::UL) {
6880       pmovzxbw(vec, Address(str2, 0));
6881     } else {
6882       movdqu(vec, Address(str2, 0));
6883     }
6884     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
6885 
6886     bind(RELOAD_STR);
6887     // We came here after the beginning of the substring was
6888     // matched but the rest of it was not so we need to search
6889     // again. Start from the next element after the previous match.
6890 
6891     // cnt2 is number of substring reminding elements and
6892     // cnt1 is number of string reminding elements when cmp failed.
6893     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
6894     subl(cnt1, cnt2);
6895     addl(cnt1, int_cnt2);
6896     movl(cnt2, int_cnt2); // Now restore cnt2
6897 
6898     decrementl(cnt1);     // Shift to next element
6899     cmpl(cnt1, cnt2);
6900     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6901 
6902     addptr(result, (1<<scale1));
6903 
6904   } // (int_cnt2 > 8)
6905 
6906   // Scan string for start of substr in 16-byte vectors
6907   bind(SCAN_TO_SUBSTR);
6908   pcmpestri(vec, Address(result, 0), mode);
6909   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6910   subl(cnt1, stride);
6911   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6912   cmpl(cnt1, cnt2);
6913   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6914   addptr(result, 16);
6915   jmpb(SCAN_TO_SUBSTR);
6916 
6917   // Found a potential substr
6918   bind(FOUND_CANDIDATE);
6919   // Matched whole vector if first element matched (tmp(rcx) == 0).
6920   if (int_cnt2 == stride) {
6921     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
6922   } else { // int_cnt2 > 8
6923     jccb(Assembler::overflow, FOUND_SUBSTR);
6924   }
6925   // After pcmpestri tmp(rcx) contains matched element index
6926   // Compute start addr of substr
6927   lea(result, Address(result, tmp, scale1));
6928 
6929   // Make sure string is still long enough
6930   subl(cnt1, tmp);
6931   cmpl(cnt1, cnt2);
6932   if (int_cnt2 == stride) {
6933     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6934   } else { // int_cnt2 > 8
6935     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
6936   }
6937   // Left less then substring.
6938 
6939   bind(RET_NOT_FOUND);
6940   movl(result, -1);
6941   jmp(EXIT);
6942 
6943   if (int_cnt2 > stride) {
6944     // This code is optimized for the case when whole substring
6945     // is matched if its head is matched.
6946     bind(MATCH_SUBSTR_HEAD);
6947     pcmpestri(vec, Address(result, 0), mode);
6948     // Reload only string if does not match
6949     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
6950 
6951     Label CONT_SCAN_SUBSTR;
6952     // Compare the rest of substring (> 8 chars).
6953     bind(FOUND_SUBSTR);
6954     // First 8 chars are already matched.
6955     negptr(cnt2);
6956     addptr(cnt2, stride);
6957 
6958     bind(SCAN_SUBSTR);
6959     subl(cnt1, stride);
6960     cmpl(cnt2, -stride); // Do not read beyond substring
6961     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
6962     // Back-up strings to avoid reading beyond substring:
6963     // cnt1 = cnt1 - cnt2 + 8
6964     addl(cnt1, cnt2); // cnt2 is negative
6965     addl(cnt1, stride);
6966     movl(cnt2, stride); negptr(cnt2);
6967     bind(CONT_SCAN_SUBSTR);
6968     if (int_cnt2 < (int)G) {
6969       int tail_off1 = int_cnt2<<scale1;
6970       int tail_off2 = int_cnt2<<scale2;
6971       if (ae == StrIntrinsicNode::UL) {
6972         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
6973       } else {
6974         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
6975       }
6976       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
6977     } else {
6978       // calculate index in register to avoid integer overflow (int_cnt2*2)
6979       movl(tmp, int_cnt2);
6980       addptr(tmp, cnt2);
6981       if (ae == StrIntrinsicNode::UL) {
6982         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
6983       } else {
6984         movdqu(vec, Address(str2, tmp, scale2, 0));
6985       }
6986       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
6987     }
6988     // Need to reload strings pointers if not matched whole vector
6989     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
6990     addptr(cnt2, stride);
6991     jcc(Assembler::negative, SCAN_SUBSTR);
6992     // Fall through if found full substring
6993 
6994   } // (int_cnt2 > 8)
6995 
6996   bind(RET_FOUND);
6997   // Found result if we matched full small substring.
6998   // Compute substr offset
6999   subptr(result, str1);
7000   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7001     shrl(result, 1); // index
7002   }
7003   bind(EXIT);
7004 
7005 } // string_indexofC8
7006 
7007 // Small strings are loaded through stack if they cross page boundary.
7008 void MacroAssembler::string_indexof(Register str1, Register str2,
7009                                     Register cnt1, Register cnt2,
7010                                     int int_cnt2,  Register result,
7011                                     XMMRegister vec, Register tmp,
7012                                     int ae) {
7013   ShortBranchVerifier sbv(this);
7014   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7015   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7016 
7017   //
7018   // int_cnt2 is length of small (< 8 chars) constant substring
7019   // or (-1) for non constant substring in which case its length
7020   // is in cnt2 register.
7021   //
7022   // Note, inline_string_indexOf() generates checks:
7023   // if (substr.count > string.count) return -1;
7024   // if (substr.count == 0) return 0;
7025   //
7026   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7027   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7028   // This method uses the pcmpestri instruction with bound registers
7029   //   inputs:
7030   //     xmm - substring
7031   //     rax - substring length (elements count)
7032   //     mem - scanned string
7033   //     rdx - string length (elements count)
7034   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7035   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7036   //   outputs:
7037   //     rcx - matched index in string
7038   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7039   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7040   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7041   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7042 
7043   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7044         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7045         FOUND_CANDIDATE;
7046 
7047   { //========================================================
7048     // We don't know where these strings are located
7049     // and we can't read beyond them. Load them through stack.
7050     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7051 
7052     movptr(tmp, rsp); // save old SP
7053 
7054     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7055       if (int_cnt2 == (1>>scale2)) { // One byte
7056         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7057         load_unsigned_byte(result, Address(str2, 0));
7058         movdl(vec, result); // move 32 bits
7059       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7060         // Not enough header space in 32-bit VM: 12+3 = 15.
7061         movl(result, Address(str2, -1));
7062         shrl(result, 8);
7063         movdl(vec, result); // move 32 bits
7064       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7065         load_unsigned_short(result, Address(str2, 0));
7066         movdl(vec, result); // move 32 bits
7067       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7068         movdl(vec, Address(str2, 0)); // move 32 bits
7069       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7070         movq(vec, Address(str2, 0));  // move 64 bits
7071       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7072         // Array header size is 12 bytes in 32-bit VM
7073         // + 6 bytes for 3 chars == 18 bytes,
7074         // enough space to load vec and shift.
7075         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7076         if (ae == StrIntrinsicNode::UL) {
7077           int tail_off = int_cnt2-8;
7078           pmovzxbw(vec, Address(str2, tail_off));
7079           psrldq(vec, -2*tail_off);
7080         }
7081         else {
7082           int tail_off = int_cnt2*(1<<scale2);
7083           movdqu(vec, Address(str2, tail_off-16));
7084           psrldq(vec, 16-tail_off);
7085         }
7086       }
7087     } else { // not constant substring
7088       cmpl(cnt2, stride);
7089       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7090 
7091       // We can read beyond string if srt+16 does not cross page boundary
7092       // since heaps are aligned and mapped by pages.
7093       assert(os::vm_page_size() < (int)G, "default page should be small");
7094       movl(result, str2); // We need only low 32 bits
7095       andl(result, (os::vm_page_size()-1));
7096       cmpl(result, (os::vm_page_size()-16));
7097       jccb(Assembler::belowEqual, CHECK_STR);
7098 
7099       // Move small strings to stack to allow load 16 bytes into vec.
7100       subptr(rsp, 16);
7101       int stk_offset = wordSize-(1<<scale2);
7102       push(cnt2);
7103 
7104       bind(COPY_SUBSTR);
7105       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7106         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7107         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7108       } else if (ae == StrIntrinsicNode::UU) {
7109         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7110         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7111       }
7112       decrement(cnt2);
7113       jccb(Assembler::notZero, COPY_SUBSTR);
7114 
7115       pop(cnt2);
7116       movptr(str2, rsp);  // New substring address
7117     } // non constant
7118 
7119     bind(CHECK_STR);
7120     cmpl(cnt1, stride);
7121     jccb(Assembler::aboveEqual, BIG_STRINGS);
7122 
7123     // Check cross page boundary.
7124     movl(result, str1); // We need only low 32 bits
7125     andl(result, (os::vm_page_size()-1));
7126     cmpl(result, (os::vm_page_size()-16));
7127     jccb(Assembler::belowEqual, BIG_STRINGS);
7128 
7129     subptr(rsp, 16);
7130     int stk_offset = -(1<<scale1);
7131     if (int_cnt2 < 0) { // not constant
7132       push(cnt2);
7133       stk_offset += wordSize;
7134     }
7135     movl(cnt2, cnt1);
7136 
7137     bind(COPY_STR);
7138     if (ae == StrIntrinsicNode::LL) {
7139       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7140       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7141     } else {
7142       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7143       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7144     }
7145     decrement(cnt2);
7146     jccb(Assembler::notZero, COPY_STR);
7147 
7148     if (int_cnt2 < 0) { // not constant
7149       pop(cnt2);
7150     }
7151     movptr(str1, rsp);  // New string address
7152 
7153     bind(BIG_STRINGS);
7154     // Load substring.
7155     if (int_cnt2 < 0) { // -1
7156       if (ae == StrIntrinsicNode::UL) {
7157         pmovzxbw(vec, Address(str2, 0));
7158       } else {
7159         movdqu(vec, Address(str2, 0));
7160       }
7161       push(cnt2);       // substr count
7162       push(str2);       // substr addr
7163       push(str1);       // string addr
7164     } else {
7165       // Small (< 8 chars) constant substrings are loaded already.
7166       movl(cnt2, int_cnt2);
7167     }
7168     push(tmp);  // original SP
7169 
7170   } // Finished loading
7171 
7172   //========================================================
7173   // Start search
7174   //
7175 
7176   movptr(result, str1); // string addr
7177 
7178   if (int_cnt2  < 0) {  // Only for non constant substring
7179     jmpb(SCAN_TO_SUBSTR);
7180 
7181     // SP saved at sp+0
7182     // String saved at sp+1*wordSize
7183     // Substr saved at sp+2*wordSize
7184     // Substr count saved at sp+3*wordSize
7185 
7186     // Reload substr for rescan, this code
7187     // is executed only for large substrings (> 8 chars)
7188     bind(RELOAD_SUBSTR);
7189     movptr(str2, Address(rsp, 2*wordSize));
7190     movl(cnt2, Address(rsp, 3*wordSize));
7191     if (ae == StrIntrinsicNode::UL) {
7192       pmovzxbw(vec, Address(str2, 0));
7193     } else {
7194       movdqu(vec, Address(str2, 0));
7195     }
7196     // We came here after the beginning of the substring was
7197     // matched but the rest of it was not so we need to search
7198     // again. Start from the next element after the previous match.
7199     subptr(str1, result); // Restore counter
7200     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7201       shrl(str1, 1);
7202     }
7203     addl(cnt1, str1);
7204     decrementl(cnt1);   // Shift to next element
7205     cmpl(cnt1, cnt2);
7206     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7207 
7208     addptr(result, (1<<scale1));
7209   } // non constant
7210 
7211   // Scan string for start of substr in 16-byte vectors
7212   bind(SCAN_TO_SUBSTR);
7213   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7214   pcmpestri(vec, Address(result, 0), mode);
7215   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7216   subl(cnt1, stride);
7217   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7218   cmpl(cnt1, cnt2);
7219   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7220   addptr(result, 16);
7221 
7222   bind(ADJUST_STR);
7223   cmpl(cnt1, stride); // Do not read beyond string
7224   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7225   // Back-up string to avoid reading beyond string.
7226   lea(result, Address(result, cnt1, scale1, -16));
7227   movl(cnt1, stride);
7228   jmpb(SCAN_TO_SUBSTR);
7229 
7230   // Found a potential substr
7231   bind(FOUND_CANDIDATE);
7232   // After pcmpestri tmp(rcx) contains matched element index
7233 
7234   // Make sure string is still long enough
7235   subl(cnt1, tmp);
7236   cmpl(cnt1, cnt2);
7237   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7238   // Left less then substring.
7239 
7240   bind(RET_NOT_FOUND);
7241   movl(result, -1);
7242   jmpb(CLEANUP);
7243 
7244   bind(FOUND_SUBSTR);
7245   // Compute start addr of substr
7246   lea(result, Address(result, tmp, scale1));
7247   if (int_cnt2 > 0) { // Constant substring
7248     // Repeat search for small substring (< 8 chars)
7249     // from new point without reloading substring.
7250     // Have to check that we don't read beyond string.
7251     cmpl(tmp, stride-int_cnt2);
7252     jccb(Assembler::greater, ADJUST_STR);
7253     // Fall through if matched whole substring.
7254   } else { // non constant
7255     assert(int_cnt2 == -1, "should be != 0");
7256 
7257     addl(tmp, cnt2);
7258     // Found result if we matched whole substring.
7259     cmpl(tmp, stride);
7260     jccb(Assembler::lessEqual, RET_FOUND);
7261 
7262     // Repeat search for small substring (<= 8 chars)
7263     // from new point 'str1' without reloading substring.
7264     cmpl(cnt2, stride);
7265     // Have to check that we don't read beyond string.
7266     jccb(Assembler::lessEqual, ADJUST_STR);
7267 
7268     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7269     // Compare the rest of substring (> 8 chars).
7270     movptr(str1, result);
7271 
7272     cmpl(tmp, cnt2);
7273     // First 8 chars are already matched.
7274     jccb(Assembler::equal, CHECK_NEXT);
7275 
7276     bind(SCAN_SUBSTR);
7277     pcmpestri(vec, Address(str1, 0), mode);
7278     // Need to reload strings pointers if not matched whole vector
7279     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7280 
7281     bind(CHECK_NEXT);
7282     subl(cnt2, stride);
7283     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7284     addptr(str1, 16);
7285     if (ae == StrIntrinsicNode::UL) {
7286       addptr(str2, 8);
7287     } else {
7288       addptr(str2, 16);
7289     }
7290     subl(cnt1, stride);
7291     cmpl(cnt2, stride); // Do not read beyond substring
7292     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7293     // Back-up strings to avoid reading beyond substring.
7294 
7295     if (ae == StrIntrinsicNode::UL) {
7296       lea(str2, Address(str2, cnt2, scale2, -8));
7297       lea(str1, Address(str1, cnt2, scale1, -16));
7298     } else {
7299       lea(str2, Address(str2, cnt2, scale2, -16));
7300       lea(str1, Address(str1, cnt2, scale1, -16));
7301     }
7302     subl(cnt1, cnt2);
7303     movl(cnt2, stride);
7304     addl(cnt1, stride);
7305     bind(CONT_SCAN_SUBSTR);
7306     if (ae == StrIntrinsicNode::UL) {
7307       pmovzxbw(vec, Address(str2, 0));
7308     } else {
7309       movdqu(vec, Address(str2, 0));
7310     }
7311     jmp(SCAN_SUBSTR);
7312 
7313     bind(RET_FOUND_LONG);
7314     movptr(str1, Address(rsp, wordSize));
7315   } // non constant
7316 
7317   bind(RET_FOUND);
7318   // Compute substr offset
7319   subptr(result, str1);
7320   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7321     shrl(result, 1); // index
7322   }
7323   bind(CLEANUP);
7324   pop(rsp); // restore SP
7325 
7326 } // string_indexof
7327 
7328 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7329                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7330   ShortBranchVerifier sbv(this);
7331   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7332 
7333   int stride = 8;
7334 
7335   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7336         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7337         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7338         FOUND_SEQ_CHAR, DONE_LABEL;
7339 
7340   movptr(result, str1);
7341   if (UseAVX >= 2) {
7342     cmpl(cnt1, stride);
7343     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7344     cmpl(cnt1, 2*stride);
7345     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7346     movdl(vec1, ch);
7347     vpbroadcastw(vec1, vec1);
7348     vpxor(vec2, vec2);
7349     movl(tmp, cnt1);
7350     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7351     andl(cnt1,0x0000000F);  //tail count (in chars)
7352 
7353     bind(SCAN_TO_16_CHAR_LOOP);
7354     vmovdqu(vec3, Address(result, 0));
7355     vpcmpeqw(vec3, vec3, vec1, 1);
7356     vptest(vec2, vec3);
7357     jcc(Assembler::carryClear, FOUND_CHAR);
7358     addptr(result, 32);
7359     subl(tmp, 2*stride);
7360     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7361     jmp(SCAN_TO_8_CHAR);
7362     bind(SCAN_TO_8_CHAR_INIT);
7363     movdl(vec1, ch);
7364     pshuflw(vec1, vec1, 0x00);
7365     pshufd(vec1, vec1, 0);
7366     pxor(vec2, vec2);
7367   }
7368   bind(SCAN_TO_8_CHAR);
7369   cmpl(cnt1, stride);
7370   if (UseAVX >= 2) {
7371     jcc(Assembler::less, SCAN_TO_CHAR);
7372   } else {
7373     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7374     movdl(vec1, ch);
7375     pshuflw(vec1, vec1, 0x00);
7376     pshufd(vec1, vec1, 0);
7377     pxor(vec2, vec2);
7378   }
7379   movl(tmp, cnt1);
7380   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7381   andl(cnt1,0x00000007);  //tail count (in chars)
7382 
7383   bind(SCAN_TO_8_CHAR_LOOP);
7384   movdqu(vec3, Address(result, 0));
7385   pcmpeqw(vec3, vec1);
7386   ptest(vec2, vec3);
7387   jcc(Assembler::carryClear, FOUND_CHAR);
7388   addptr(result, 16);
7389   subl(tmp, stride);
7390   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7391   bind(SCAN_TO_CHAR);
7392   testl(cnt1, cnt1);
7393   jcc(Assembler::zero, RET_NOT_FOUND);
7394   bind(SCAN_TO_CHAR_LOOP);
7395   load_unsigned_short(tmp, Address(result, 0));
7396   cmpl(ch, tmp);
7397   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7398   addptr(result, 2);
7399   subl(cnt1, 1);
7400   jccb(Assembler::zero, RET_NOT_FOUND);
7401   jmp(SCAN_TO_CHAR_LOOP);
7402 
7403   bind(RET_NOT_FOUND);
7404   movl(result, -1);
7405   jmpb(DONE_LABEL);
7406 
7407   bind(FOUND_CHAR);
7408   if (UseAVX >= 2) {
7409     vpmovmskb(tmp, vec3);
7410   } else {
7411     pmovmskb(tmp, vec3);
7412   }
7413   bsfl(ch, tmp);
7414   addl(result, ch);
7415 
7416   bind(FOUND_SEQ_CHAR);
7417   subptr(result, str1);
7418   shrl(result, 1);
7419 
7420   bind(DONE_LABEL);
7421 } // string_indexof_char
7422 
7423 // helper function for string_compare
7424 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7425                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7426                                         Address::ScaleFactor scale2, Register index, int ae) {
7427   if (ae == StrIntrinsicNode::LL) {
7428     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7429     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7430   } else if (ae == StrIntrinsicNode::UU) {
7431     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7432     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7433   } else {
7434     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7435     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7436   }
7437 }
7438 
7439 // Compare strings, used for char[] and byte[].
7440 void MacroAssembler::string_compare(Register str1, Register str2,
7441                                     Register cnt1, Register cnt2, Register result,
7442                                     XMMRegister vec1, int ae) {
7443   ShortBranchVerifier sbv(this);
7444   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7445   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7446   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7447   int stride2x2 = 0x40;
7448   Address::ScaleFactor scale = Address::no_scale;
7449   Address::ScaleFactor scale1 = Address::no_scale;
7450   Address::ScaleFactor scale2 = Address::no_scale;
7451 
7452   if (ae != StrIntrinsicNode::LL) {
7453     stride2x2 = 0x20;
7454   }
7455 
7456   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7457     shrl(cnt2, 1);
7458   }
7459   // Compute the minimum of the string lengths and the
7460   // difference of the string lengths (stack).
7461   // Do the conditional move stuff
7462   movl(result, cnt1);
7463   subl(cnt1, cnt2);
7464   push(cnt1);
7465   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7466 
7467   // Is the minimum length zero?
7468   testl(cnt2, cnt2);
7469   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7470   if (ae == StrIntrinsicNode::LL) {
7471     // Load first bytes
7472     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7473     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7474   } else if (ae == StrIntrinsicNode::UU) {
7475     // Load first characters
7476     load_unsigned_short(result, Address(str1, 0));
7477     load_unsigned_short(cnt1, Address(str2, 0));
7478   } else {
7479     load_unsigned_byte(result, Address(str1, 0));
7480     load_unsigned_short(cnt1, Address(str2, 0));
7481   }
7482   subl(result, cnt1);
7483   jcc(Assembler::notZero,  POP_LABEL);
7484 
7485   if (ae == StrIntrinsicNode::UU) {
7486     // Divide length by 2 to get number of chars
7487     shrl(cnt2, 1);
7488   }
7489   cmpl(cnt2, 1);
7490   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7491 
7492   // Check if the strings start at the same location and setup scale and stride
7493   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7494     cmpptr(str1, str2);
7495     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7496     if (ae == StrIntrinsicNode::LL) {
7497       scale = Address::times_1;
7498       stride = 16;
7499     } else {
7500       scale = Address::times_2;
7501       stride = 8;
7502     }
7503   } else {
7504     scale1 = Address::times_1;
7505     scale2 = Address::times_2;
7506     // scale not used
7507     stride = 8;
7508   }
7509 
7510   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7511     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7512     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7513     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7514     Label COMPARE_TAIL_LONG;
7515     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7516 
7517     int pcmpmask = 0x19;
7518     if (ae == StrIntrinsicNode::LL) {
7519       pcmpmask &= ~0x01;
7520     }
7521 
7522     // Setup to compare 16-chars (32-bytes) vectors,
7523     // start from first character again because it has aligned address.
7524     if (ae == StrIntrinsicNode::LL) {
7525       stride2 = 32;
7526     } else {
7527       stride2 = 16;
7528     }
7529     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7530       adr_stride = stride << scale;
7531     } else {
7532       adr_stride1 = 8;  //stride << scale1;
7533       adr_stride2 = 16; //stride << scale2;
7534     }
7535 
7536     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7537     // rax and rdx are used by pcmpestri as elements counters
7538     movl(result, cnt2);
7539     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7540     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7541 
7542     // fast path : compare first 2 8-char vectors.
7543     bind(COMPARE_16_CHARS);
7544     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7545       movdqu(vec1, Address(str1, 0));
7546     } else {
7547       pmovzxbw(vec1, Address(str1, 0));
7548     }
7549     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7550     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7551 
7552     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7553       movdqu(vec1, Address(str1, adr_stride));
7554       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7555     } else {
7556       pmovzxbw(vec1, Address(str1, adr_stride1));
7557       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7558     }
7559     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7560     addl(cnt1, stride);
7561 
7562     // Compare the characters at index in cnt1
7563     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7564     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7565     subl(result, cnt2);
7566     jmp(POP_LABEL);
7567 
7568     // Setup the registers to start vector comparison loop
7569     bind(COMPARE_WIDE_VECTORS);
7570     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7571       lea(str1, Address(str1, result, scale));
7572       lea(str2, Address(str2, result, scale));
7573     } else {
7574       lea(str1, Address(str1, result, scale1));
7575       lea(str2, Address(str2, result, scale2));
7576     }
7577     subl(result, stride2);
7578     subl(cnt2, stride2);
7579     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7580     negptr(result);
7581 
7582     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7583     bind(COMPARE_WIDE_VECTORS_LOOP);
7584 
7585 #ifdef _LP64
7586     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7587       cmpl(cnt2, stride2x2);
7588       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7589       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7590       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7591 
7592       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7593       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7594         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7595         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7596       } else {
7597         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7598         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7599       }
7600       kortestql(k7, k7);
7601       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7602       addptr(result, stride2x2);  // update since we already compared at this addr
7603       subl(cnt2, stride2x2);      // and sub the size too
7604       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7605 
7606       vpxor(vec1, vec1);
7607       jmpb(COMPARE_WIDE_TAIL);
7608     }//if (VM_Version::supports_avx512vlbw())
7609 #endif // _LP64
7610 
7611 
7612     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7613     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7614       vmovdqu(vec1, Address(str1, result, scale));
7615       vpxor(vec1, Address(str2, result, scale));
7616     } else {
7617       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7618       vpxor(vec1, Address(str2, result, scale2));
7619     }
7620     vptest(vec1, vec1);
7621     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7622     addptr(result, stride2);
7623     subl(cnt2, stride2);
7624     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7625     // clean upper bits of YMM registers
7626     vpxor(vec1, vec1);
7627 
7628     // compare wide vectors tail
7629     bind(COMPARE_WIDE_TAIL);
7630     testptr(result, result);
7631     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7632 
7633     movl(result, stride2);
7634     movl(cnt2, result);
7635     negptr(result);
7636     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7637 
7638     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7639     bind(VECTOR_NOT_EQUAL);
7640     // clean upper bits of YMM registers
7641     vpxor(vec1, vec1);
7642     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7643       lea(str1, Address(str1, result, scale));
7644       lea(str2, Address(str2, result, scale));
7645     } else {
7646       lea(str1, Address(str1, result, scale1));
7647       lea(str2, Address(str2, result, scale2));
7648     }
7649     jmp(COMPARE_16_CHARS);
7650 
7651     // Compare tail chars, length between 1 to 15 chars
7652     bind(COMPARE_TAIL_LONG);
7653     movl(cnt2, result);
7654     cmpl(cnt2, stride);
7655     jcc(Assembler::less, COMPARE_SMALL_STR);
7656 
7657     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7658       movdqu(vec1, Address(str1, 0));
7659     } else {
7660       pmovzxbw(vec1, Address(str1, 0));
7661     }
7662     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7663     jcc(Assembler::below, COMPARE_INDEX_CHAR);
7664     subptr(cnt2, stride);
7665     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7666     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7667       lea(str1, Address(str1, result, scale));
7668       lea(str2, Address(str2, result, scale));
7669     } else {
7670       lea(str1, Address(str1, result, scale1));
7671       lea(str2, Address(str2, result, scale2));
7672     }
7673     negptr(cnt2);
7674     jmpb(WHILE_HEAD_LABEL);
7675 
7676     bind(COMPARE_SMALL_STR);
7677   } else if (UseSSE42Intrinsics) {
7678     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
7679     int pcmpmask = 0x19;
7680     // Setup to compare 8-char (16-byte) vectors,
7681     // start from first character again because it has aligned address.
7682     movl(result, cnt2);
7683     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
7684     if (ae == StrIntrinsicNode::LL) {
7685       pcmpmask &= ~0x01;
7686     }
7687     jcc(Assembler::zero, COMPARE_TAIL);
7688     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7689       lea(str1, Address(str1, result, scale));
7690       lea(str2, Address(str2, result, scale));
7691     } else {
7692       lea(str1, Address(str1, result, scale1));
7693       lea(str2, Address(str2, result, scale2));
7694     }
7695     negptr(result);
7696 
7697     // pcmpestri
7698     //   inputs:
7699     //     vec1- substring
7700     //     rax - negative string length (elements count)
7701     //     mem - scanned string
7702     //     rdx - string length (elements count)
7703     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
7704     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
7705     //   outputs:
7706     //     rcx - first mismatched element index
7707     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7708 
7709     bind(COMPARE_WIDE_VECTORS);
7710     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7711       movdqu(vec1, Address(str1, result, scale));
7712       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7713     } else {
7714       pmovzxbw(vec1, Address(str1, result, scale1));
7715       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7716     }
7717     // After pcmpestri cnt1(rcx) contains mismatched element index
7718 
7719     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
7720     addptr(result, stride);
7721     subptr(cnt2, stride);
7722     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
7723 
7724     // compare wide vectors tail
7725     testptr(result, result);
7726     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7727 
7728     movl(cnt2, stride);
7729     movl(result, stride);
7730     negptr(result);
7731     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7732       movdqu(vec1, Address(str1, result, scale));
7733       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7734     } else {
7735       pmovzxbw(vec1, Address(str1, result, scale1));
7736       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7737     }
7738     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
7739 
7740     // Mismatched characters in the vectors
7741     bind(VECTOR_NOT_EQUAL);
7742     addptr(cnt1, result);
7743     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7744     subl(result, cnt2);
7745     jmpb(POP_LABEL);
7746 
7747     bind(COMPARE_TAIL); // limit is zero
7748     movl(cnt2, result);
7749     // Fallthru to tail compare
7750   }
7751   // Shift str2 and str1 to the end of the arrays, negate min
7752   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7753     lea(str1, Address(str1, cnt2, scale));
7754     lea(str2, Address(str2, cnt2, scale));
7755   } else {
7756     lea(str1, Address(str1, cnt2, scale1));
7757     lea(str2, Address(str2, cnt2, scale2));
7758   }
7759   decrementl(cnt2);  // first character was compared already
7760   negptr(cnt2);
7761 
7762   // Compare the rest of the elements
7763   bind(WHILE_HEAD_LABEL);
7764   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
7765   subl(result, cnt1);
7766   jccb(Assembler::notZero, POP_LABEL);
7767   increment(cnt2);
7768   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
7769 
7770   // Strings are equal up to min length.  Return the length difference.
7771   bind(LENGTH_DIFF_LABEL);
7772   pop(result);
7773   if (ae == StrIntrinsicNode::UU) {
7774     // Divide diff by 2 to get number of chars
7775     sarl(result, 1);
7776   }
7777   jmpb(DONE_LABEL);
7778 
7779 #ifdef _LP64
7780   if (VM_Version::supports_avx512vlbw()) {
7781 
7782     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
7783 
7784     kmovql(cnt1, k7);
7785     notq(cnt1);
7786     bsfq(cnt2, cnt1);
7787     if (ae != StrIntrinsicNode::LL) {
7788       // Divide diff by 2 to get number of chars
7789       sarl(cnt2, 1);
7790     }
7791     addq(result, cnt2);
7792     if (ae == StrIntrinsicNode::LL) {
7793       load_unsigned_byte(cnt1, Address(str2, result));
7794       load_unsigned_byte(result, Address(str1, result));
7795     } else if (ae == StrIntrinsicNode::UU) {
7796       load_unsigned_short(cnt1, Address(str2, result, scale));
7797       load_unsigned_short(result, Address(str1, result, scale));
7798     } else {
7799       load_unsigned_short(cnt1, Address(str2, result, scale2));
7800       load_unsigned_byte(result, Address(str1, result, scale1));
7801     }
7802     subl(result, cnt1);
7803     jmpb(POP_LABEL);
7804   }//if (VM_Version::supports_avx512vlbw())
7805 #endif // _LP64
7806 
7807   // Discard the stored length difference
7808   bind(POP_LABEL);
7809   pop(cnt1);
7810 
7811   // That's it
7812   bind(DONE_LABEL);
7813   if(ae == StrIntrinsicNode::UL) {
7814     negl(result);
7815   }
7816 
7817 }
7818 
7819 // Search for Non-ASCII character (Negative byte value) in a byte array,
7820 // return true if it has any and false otherwise.
7821 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
7822 //   @HotSpotIntrinsicCandidate
7823 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
7824 //     for (int i = off; i < off + len; i++) {
7825 //       if (ba[i] < 0) {
7826 //         return true;
7827 //       }
7828 //     }
7829 //     return false;
7830 //   }
7831 void MacroAssembler::has_negatives(Register ary1, Register len,
7832   Register result, Register tmp1,
7833   XMMRegister vec1, XMMRegister vec2) {
7834   // rsi: byte array
7835   // rcx: len
7836   // rax: result
7837   ShortBranchVerifier sbv(this);
7838   assert_different_registers(ary1, len, result, tmp1);
7839   assert_different_registers(vec1, vec2);
7840   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
7841 
7842   // len == 0
7843   testl(len, len);
7844   jcc(Assembler::zero, FALSE_LABEL);
7845 
7846   if ((UseAVX > 2) && // AVX512
7847     VM_Version::supports_avx512vlbw() &&
7848     VM_Version::supports_bmi2()) {
7849 
7850     set_vector_masking();  // opening of the stub context for programming mask registers
7851 
7852     Label test_64_loop, test_tail;
7853     Register tmp3_aliased = len;
7854 
7855     movl(tmp1, len);
7856     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
7857 
7858     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
7859     andl(len, ~(64 - 1));    // vector count (in chars)
7860     jccb(Assembler::zero, test_tail);
7861 
7862     lea(ary1, Address(ary1, len, Address::times_1));
7863     negptr(len);
7864 
7865     bind(test_64_loop);
7866     // Check whether our 64 elements of size byte contain negatives
7867     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
7868     kortestql(k2, k2);
7869     jcc(Assembler::notZero, TRUE_LABEL);
7870 
7871     addptr(len, 64);
7872     jccb(Assembler::notZero, test_64_loop);
7873 
7874 
7875     bind(test_tail);
7876     // bail out when there is nothing to be done
7877     testl(tmp1, -1);
7878     jcc(Assembler::zero, FALSE_LABEL);
7879 
7880     // Save k1
7881     kmovql(k3, k1);
7882 
7883     // ~(~0 << len) applied up to two times (for 32-bit scenario)
7884 #ifdef _LP64
7885     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
7886     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
7887     notq(tmp3_aliased);
7888     kmovql(k1, tmp3_aliased);
7889 #else
7890     Label k_init;
7891     jmp(k_init);
7892 
7893     // We could not read 64-bits from a general purpose register thus we move
7894     // data required to compose 64 1's to the instruction stream
7895     // We emit 64 byte wide series of elements from 0..63 which later on would
7896     // be used as a compare targets with tail count contained in tmp1 register.
7897     // Result would be a k1 register having tmp1 consecutive number or 1
7898     // counting from least significant bit.
7899     address tmp = pc();
7900     emit_int64(0x0706050403020100);
7901     emit_int64(0x0F0E0D0C0B0A0908);
7902     emit_int64(0x1716151413121110);
7903     emit_int64(0x1F1E1D1C1B1A1918);
7904     emit_int64(0x2726252423222120);
7905     emit_int64(0x2F2E2D2C2B2A2928);
7906     emit_int64(0x3736353433323130);
7907     emit_int64(0x3F3E3D3C3B3A3938);
7908 
7909     bind(k_init);
7910     lea(len, InternalAddress(tmp));
7911     // create mask to test for negative byte inside a vector
7912     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
7913     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
7914 
7915 #endif
7916     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
7917     ktestq(k2, k1);
7918     // Restore k1
7919     kmovql(k1, k3);
7920     jcc(Assembler::notZero, TRUE_LABEL);
7921 
7922     jmp(FALSE_LABEL);
7923 
7924     clear_vector_masking();   // closing of the stub context for programming mask registers
7925   } else {
7926     movl(result, len); // copy
7927 
7928     if (UseAVX == 2 && UseSSE >= 2) {
7929       // With AVX2, use 32-byte vector compare
7930       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7931 
7932       // Compare 32-byte vectors
7933       andl(result, 0x0000001f);  //   tail count (in bytes)
7934       andl(len, 0xffffffe0);   // vector count (in bytes)
7935       jccb(Assembler::zero, COMPARE_TAIL);
7936 
7937       lea(ary1, Address(ary1, len, Address::times_1));
7938       negptr(len);
7939 
7940       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
7941       movdl(vec2, tmp1);
7942       vpbroadcastd(vec2, vec2);
7943 
7944       bind(COMPARE_WIDE_VECTORS);
7945       vmovdqu(vec1, Address(ary1, len, Address::times_1));
7946       vptest(vec1, vec2);
7947       jccb(Assembler::notZero, TRUE_LABEL);
7948       addptr(len, 32);
7949       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7950 
7951       testl(result, result);
7952       jccb(Assembler::zero, FALSE_LABEL);
7953 
7954       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7955       vptest(vec1, vec2);
7956       jccb(Assembler::notZero, TRUE_LABEL);
7957       jmpb(FALSE_LABEL);
7958 
7959       bind(COMPARE_TAIL); // len is zero
7960       movl(len, result);
7961       // Fallthru to tail compare
7962     } else if (UseSSE42Intrinsics) {
7963       // With SSE4.2, use double quad vector compare
7964       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7965 
7966       // Compare 16-byte vectors
7967       andl(result, 0x0000000f);  //   tail count (in bytes)
7968       andl(len, 0xfffffff0);   // vector count (in bytes)
7969       jccb(Assembler::zero, COMPARE_TAIL);
7970 
7971       lea(ary1, Address(ary1, len, Address::times_1));
7972       negptr(len);
7973 
7974       movl(tmp1, 0x80808080);
7975       movdl(vec2, tmp1);
7976       pshufd(vec2, vec2, 0);
7977 
7978       bind(COMPARE_WIDE_VECTORS);
7979       movdqu(vec1, Address(ary1, len, Address::times_1));
7980       ptest(vec1, vec2);
7981       jccb(Assembler::notZero, TRUE_LABEL);
7982       addptr(len, 16);
7983       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7984 
7985       testl(result, result);
7986       jccb(Assembler::zero, FALSE_LABEL);
7987 
7988       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
7989       ptest(vec1, vec2);
7990       jccb(Assembler::notZero, TRUE_LABEL);
7991       jmpb(FALSE_LABEL);
7992 
7993       bind(COMPARE_TAIL); // len is zero
7994       movl(len, result);
7995       // Fallthru to tail compare
7996     }
7997   }
7998   // Compare 4-byte vectors
7999   andl(len, 0xfffffffc); // vector count (in bytes)
8000   jccb(Assembler::zero, COMPARE_CHAR);
8001 
8002   lea(ary1, Address(ary1, len, Address::times_1));
8003   negptr(len);
8004 
8005   bind(COMPARE_VECTORS);
8006   movl(tmp1, Address(ary1, len, Address::times_1));
8007   andl(tmp1, 0x80808080);
8008   jccb(Assembler::notZero, TRUE_LABEL);
8009   addptr(len, 4);
8010   jcc(Assembler::notZero, COMPARE_VECTORS);
8011 
8012   // Compare trailing char (final 2 bytes), if any
8013   bind(COMPARE_CHAR);
8014   testl(result, 0x2);   // tail  char
8015   jccb(Assembler::zero, COMPARE_BYTE);
8016   load_unsigned_short(tmp1, Address(ary1, 0));
8017   andl(tmp1, 0x00008080);
8018   jccb(Assembler::notZero, TRUE_LABEL);
8019   subptr(result, 2);
8020   lea(ary1, Address(ary1, 2));
8021 
8022   bind(COMPARE_BYTE);
8023   testl(result, 0x1);   // tail  byte
8024   jccb(Assembler::zero, FALSE_LABEL);
8025   load_unsigned_byte(tmp1, Address(ary1, 0));
8026   andl(tmp1, 0x00000080);
8027   jccb(Assembler::notEqual, TRUE_LABEL);
8028   jmpb(FALSE_LABEL);
8029 
8030   bind(TRUE_LABEL);
8031   movl(result, 1);   // return true
8032   jmpb(DONE);
8033 
8034   bind(FALSE_LABEL);
8035   xorl(result, result); // return false
8036 
8037   // That's it
8038   bind(DONE);
8039   if (UseAVX >= 2 && UseSSE >= 2) {
8040     // clean upper bits of YMM registers
8041     vpxor(vec1, vec1);
8042     vpxor(vec2, vec2);
8043   }
8044 }
8045 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8046 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8047                                    Register limit, Register result, Register chr,
8048                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8049   ShortBranchVerifier sbv(this);
8050   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8051 
8052   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8053   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8054 
8055   if (is_array_equ) {
8056     // Check the input args
8057     cmpoop(ary1, ary2);
8058     jcc(Assembler::equal, TRUE_LABEL);
8059 
8060     // Need additional checks for arrays_equals.
8061     testptr(ary1, ary1);
8062     jcc(Assembler::zero, FALSE_LABEL);
8063     testptr(ary2, ary2);
8064     jcc(Assembler::zero, FALSE_LABEL);
8065 
8066     // Check the lengths
8067     movl(limit, Address(ary1, length_offset));
8068     cmpl(limit, Address(ary2, length_offset));
8069     jcc(Assembler::notEqual, FALSE_LABEL);
8070   }
8071 
8072   // count == 0
8073   testl(limit, limit);
8074   jcc(Assembler::zero, TRUE_LABEL);
8075 
8076   if (is_array_equ) {
8077     // Load array address
8078     lea(ary1, Address(ary1, base_offset));
8079     lea(ary2, Address(ary2, base_offset));
8080   }
8081 
8082   if (is_array_equ && is_char) {
8083     // arrays_equals when used for char[].
8084     shll(limit, 1);      // byte count != 0
8085   }
8086   movl(result, limit); // copy
8087 
8088   if (UseAVX >= 2) {
8089     // With AVX2, use 32-byte vector compare
8090     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8091 
8092     // Compare 32-byte vectors
8093     andl(result, 0x0000001f);  //   tail count (in bytes)
8094     andl(limit, 0xffffffe0);   // vector count (in bytes)
8095     jcc(Assembler::zero, COMPARE_TAIL);
8096 
8097     lea(ary1, Address(ary1, limit, Address::times_1));
8098     lea(ary2, Address(ary2, limit, Address::times_1));
8099     negptr(limit);
8100 
8101     bind(COMPARE_WIDE_VECTORS);
8102 
8103 #ifdef _LP64
8104     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8105       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8106 
8107       cmpl(limit, -64);
8108       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8109 
8110       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8111 
8112       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8113       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8114       kortestql(k7, k7);
8115       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8116       addptr(limit, 64);  // update since we already compared at this addr
8117       cmpl(limit, -64);
8118       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8119 
8120       // At this point we may still need to compare -limit+result bytes.
8121       // We could execute the next two instruction and just continue via non-wide path:
8122       //  cmpl(limit, 0);
8123       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8124       // But since we stopped at the points ary{1,2}+limit which are
8125       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8126       // (|limit| <= 32 and result < 32),
8127       // we may just compare the last 64 bytes.
8128       //
8129       addptr(result, -64);   // it is safe, bc we just came from this area
8130       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8131       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8132       kortestql(k7, k7);
8133       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8134 
8135       jmp(TRUE_LABEL);
8136 
8137       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8138 
8139     }//if (VM_Version::supports_avx512vlbw())
8140 #endif //_LP64
8141 
8142     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8143     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8144     vpxor(vec1, vec2);
8145 
8146     vptest(vec1, vec1);
8147     jcc(Assembler::notZero, FALSE_LABEL);
8148     addptr(limit, 32);
8149     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8150 
8151     testl(result, result);
8152     jcc(Assembler::zero, TRUE_LABEL);
8153 
8154     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8155     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8156     vpxor(vec1, vec2);
8157 
8158     vptest(vec1, vec1);
8159     jccb(Assembler::notZero, FALSE_LABEL);
8160     jmpb(TRUE_LABEL);
8161 
8162     bind(COMPARE_TAIL); // limit is zero
8163     movl(limit, result);
8164     // Fallthru to tail compare
8165   } else if (UseSSE42Intrinsics) {
8166     // With SSE4.2, use double quad vector compare
8167     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8168 
8169     // Compare 16-byte vectors
8170     andl(result, 0x0000000f);  //   tail count (in bytes)
8171     andl(limit, 0xfffffff0);   // vector count (in bytes)
8172     jcc(Assembler::zero, COMPARE_TAIL);
8173 
8174     lea(ary1, Address(ary1, limit, Address::times_1));
8175     lea(ary2, Address(ary2, limit, Address::times_1));
8176     negptr(limit);
8177 
8178     bind(COMPARE_WIDE_VECTORS);
8179     movdqu(vec1, Address(ary1, limit, Address::times_1));
8180     movdqu(vec2, Address(ary2, limit, Address::times_1));
8181     pxor(vec1, vec2);
8182 
8183     ptest(vec1, vec1);
8184     jcc(Assembler::notZero, FALSE_LABEL);
8185     addptr(limit, 16);
8186     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8187 
8188     testl(result, result);
8189     jcc(Assembler::zero, TRUE_LABEL);
8190 
8191     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8192     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8193     pxor(vec1, vec2);
8194 
8195     ptest(vec1, vec1);
8196     jccb(Assembler::notZero, FALSE_LABEL);
8197     jmpb(TRUE_LABEL);
8198 
8199     bind(COMPARE_TAIL); // limit is zero
8200     movl(limit, result);
8201     // Fallthru to tail compare
8202   }
8203 
8204   // Compare 4-byte vectors
8205   andl(limit, 0xfffffffc); // vector count (in bytes)
8206   jccb(Assembler::zero, COMPARE_CHAR);
8207 
8208   lea(ary1, Address(ary1, limit, Address::times_1));
8209   lea(ary2, Address(ary2, limit, Address::times_1));
8210   negptr(limit);
8211 
8212   bind(COMPARE_VECTORS);
8213   movl(chr, Address(ary1, limit, Address::times_1));
8214   cmpl(chr, Address(ary2, limit, Address::times_1));
8215   jccb(Assembler::notEqual, FALSE_LABEL);
8216   addptr(limit, 4);
8217   jcc(Assembler::notZero, COMPARE_VECTORS);
8218 
8219   // Compare trailing char (final 2 bytes), if any
8220   bind(COMPARE_CHAR);
8221   testl(result, 0x2);   // tail  char
8222   jccb(Assembler::zero, COMPARE_BYTE);
8223   load_unsigned_short(chr, Address(ary1, 0));
8224   load_unsigned_short(limit, Address(ary2, 0));
8225   cmpl(chr, limit);
8226   jccb(Assembler::notEqual, FALSE_LABEL);
8227 
8228   if (is_array_equ && is_char) {
8229     bind(COMPARE_BYTE);
8230   } else {
8231     lea(ary1, Address(ary1, 2));
8232     lea(ary2, Address(ary2, 2));
8233 
8234     bind(COMPARE_BYTE);
8235     testl(result, 0x1);   // tail  byte
8236     jccb(Assembler::zero, TRUE_LABEL);
8237     load_unsigned_byte(chr, Address(ary1, 0));
8238     load_unsigned_byte(limit, Address(ary2, 0));
8239     cmpl(chr, limit);
8240     jccb(Assembler::notEqual, FALSE_LABEL);
8241   }
8242   bind(TRUE_LABEL);
8243   movl(result, 1);   // return true
8244   jmpb(DONE);
8245 
8246   bind(FALSE_LABEL);
8247   xorl(result, result); // return false
8248 
8249   // That's it
8250   bind(DONE);
8251   if (UseAVX >= 2) {
8252     // clean upper bits of YMM registers
8253     vpxor(vec1, vec1);
8254     vpxor(vec2, vec2);
8255   }
8256 }
8257 
8258 #endif
8259 
8260 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8261                                    Register to, Register value, Register count,
8262                                    Register rtmp, XMMRegister xtmp) {
8263   ShortBranchVerifier sbv(this);
8264   assert_different_registers(to, value, count, rtmp);
8265   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8266   Label L_fill_2_bytes, L_fill_4_bytes;
8267 
8268   int shift = -1;
8269   switch (t) {
8270     case T_BYTE:
8271       shift = 2;
8272       break;
8273     case T_SHORT:
8274       shift = 1;
8275       break;
8276     case T_INT:
8277       shift = 0;
8278       break;
8279     default: ShouldNotReachHere();
8280   }
8281 
8282   if (t == T_BYTE) {
8283     andl(value, 0xff);
8284     movl(rtmp, value);
8285     shll(rtmp, 8);
8286     orl(value, rtmp);
8287   }
8288   if (t == T_SHORT) {
8289     andl(value, 0xffff);
8290   }
8291   if (t == T_BYTE || t == T_SHORT) {
8292     movl(rtmp, value);
8293     shll(rtmp, 16);
8294     orl(value, rtmp);
8295   }
8296 
8297   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8298   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8299   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8300     // align source address at 4 bytes address boundary
8301     if (t == T_BYTE) {
8302       // One byte misalignment happens only for byte arrays
8303       testptr(to, 1);
8304       jccb(Assembler::zero, L_skip_align1);
8305       movb(Address(to, 0), value);
8306       increment(to);
8307       decrement(count);
8308       BIND(L_skip_align1);
8309     }
8310     // Two bytes misalignment happens only for byte and short (char) arrays
8311     testptr(to, 2);
8312     jccb(Assembler::zero, L_skip_align2);
8313     movw(Address(to, 0), value);
8314     addptr(to, 2);
8315     subl(count, 1<<(shift-1));
8316     BIND(L_skip_align2);
8317   }
8318   if (UseSSE < 2) {
8319     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8320     // Fill 32-byte chunks
8321     subl(count, 8 << shift);
8322     jcc(Assembler::less, L_check_fill_8_bytes);
8323     align(16);
8324 
8325     BIND(L_fill_32_bytes_loop);
8326 
8327     for (int i = 0; i < 32; i += 4) {
8328       movl(Address(to, i), value);
8329     }
8330 
8331     addptr(to, 32);
8332     subl(count, 8 << shift);
8333     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8334     BIND(L_check_fill_8_bytes);
8335     addl(count, 8 << shift);
8336     jccb(Assembler::zero, L_exit);
8337     jmpb(L_fill_8_bytes);
8338 
8339     //
8340     // length is too short, just fill qwords
8341     //
8342     BIND(L_fill_8_bytes_loop);
8343     movl(Address(to, 0), value);
8344     movl(Address(to, 4), value);
8345     addptr(to, 8);
8346     BIND(L_fill_8_bytes);
8347     subl(count, 1 << (shift + 1));
8348     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8349     // fall through to fill 4 bytes
8350   } else {
8351     Label L_fill_32_bytes;
8352     if (!UseUnalignedLoadStores) {
8353       // align to 8 bytes, we know we are 4 byte aligned to start
8354       testptr(to, 4);
8355       jccb(Assembler::zero, L_fill_32_bytes);
8356       movl(Address(to, 0), value);
8357       addptr(to, 4);
8358       subl(count, 1<<shift);
8359     }
8360     BIND(L_fill_32_bytes);
8361     {
8362       assert( UseSSE >= 2, "supported cpu only" );
8363       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8364       if (UseAVX > 2) {
8365         movl(rtmp, 0xffff);
8366         kmovwl(k1, rtmp);
8367       }
8368       movdl(xtmp, value);
8369       if (UseAVX > 2 && UseUnalignedLoadStores) {
8370         // Fill 64-byte chunks
8371         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8372         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8373 
8374         subl(count, 16 << shift);
8375         jcc(Assembler::less, L_check_fill_32_bytes);
8376         align(16);
8377 
8378         BIND(L_fill_64_bytes_loop);
8379         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8380         addptr(to, 64);
8381         subl(count, 16 << shift);
8382         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8383 
8384         BIND(L_check_fill_32_bytes);
8385         addl(count, 8 << shift);
8386         jccb(Assembler::less, L_check_fill_8_bytes);
8387         vmovdqu(Address(to, 0), xtmp);
8388         addptr(to, 32);
8389         subl(count, 8 << shift);
8390 
8391         BIND(L_check_fill_8_bytes);
8392       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8393         // Fill 64-byte chunks
8394         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8395         vpbroadcastd(xtmp, xtmp);
8396 
8397         subl(count, 16 << shift);
8398         jcc(Assembler::less, L_check_fill_32_bytes);
8399         align(16);
8400 
8401         BIND(L_fill_64_bytes_loop);
8402         vmovdqu(Address(to, 0), xtmp);
8403         vmovdqu(Address(to, 32), xtmp);
8404         addptr(to, 64);
8405         subl(count, 16 << shift);
8406         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8407 
8408         BIND(L_check_fill_32_bytes);
8409         addl(count, 8 << shift);
8410         jccb(Assembler::less, L_check_fill_8_bytes);
8411         vmovdqu(Address(to, 0), xtmp);
8412         addptr(to, 32);
8413         subl(count, 8 << shift);
8414 
8415         BIND(L_check_fill_8_bytes);
8416         // clean upper bits of YMM registers
8417         movdl(xtmp, value);
8418         pshufd(xtmp, xtmp, 0);
8419       } else {
8420         // Fill 32-byte chunks
8421         pshufd(xtmp, xtmp, 0);
8422 
8423         subl(count, 8 << shift);
8424         jcc(Assembler::less, L_check_fill_8_bytes);
8425         align(16);
8426 
8427         BIND(L_fill_32_bytes_loop);
8428 
8429         if (UseUnalignedLoadStores) {
8430           movdqu(Address(to, 0), xtmp);
8431           movdqu(Address(to, 16), xtmp);
8432         } else {
8433           movq(Address(to, 0), xtmp);
8434           movq(Address(to, 8), xtmp);
8435           movq(Address(to, 16), xtmp);
8436           movq(Address(to, 24), xtmp);
8437         }
8438 
8439         addptr(to, 32);
8440         subl(count, 8 << shift);
8441         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8442 
8443         BIND(L_check_fill_8_bytes);
8444       }
8445       addl(count, 8 << shift);
8446       jccb(Assembler::zero, L_exit);
8447       jmpb(L_fill_8_bytes);
8448 
8449       //
8450       // length is too short, just fill qwords
8451       //
8452       BIND(L_fill_8_bytes_loop);
8453       movq(Address(to, 0), xtmp);
8454       addptr(to, 8);
8455       BIND(L_fill_8_bytes);
8456       subl(count, 1 << (shift + 1));
8457       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8458     }
8459   }
8460   // fill trailing 4 bytes
8461   BIND(L_fill_4_bytes);
8462   testl(count, 1<<shift);
8463   jccb(Assembler::zero, L_fill_2_bytes);
8464   movl(Address(to, 0), value);
8465   if (t == T_BYTE || t == T_SHORT) {
8466     addptr(to, 4);
8467     BIND(L_fill_2_bytes);
8468     // fill trailing 2 bytes
8469     testl(count, 1<<(shift-1));
8470     jccb(Assembler::zero, L_fill_byte);
8471     movw(Address(to, 0), value);
8472     if (t == T_BYTE) {
8473       addptr(to, 2);
8474       BIND(L_fill_byte);
8475       // fill trailing byte
8476       testl(count, 1);
8477       jccb(Assembler::zero, L_exit);
8478       movb(Address(to, 0), value);
8479     } else {
8480       BIND(L_fill_byte);
8481     }
8482   } else {
8483     BIND(L_fill_2_bytes);
8484   }
8485   BIND(L_exit);
8486 }
8487 
8488 // encode char[] to byte[] in ISO_8859_1
8489    //@HotSpotIntrinsicCandidate
8490    //private static int implEncodeISOArray(byte[] sa, int sp,
8491    //byte[] da, int dp, int len) {
8492    //  int i = 0;
8493    //  for (; i < len; i++) {
8494    //    char c = StringUTF16.getChar(sa, sp++);
8495    //    if (c > '\u00FF')
8496    //      break;
8497    //    da[dp++] = (byte)c;
8498    //  }
8499    //  return i;
8500    //}
8501 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8502   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8503   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8504   Register tmp5, Register result) {
8505 
8506   // rsi: src
8507   // rdi: dst
8508   // rdx: len
8509   // rcx: tmp5
8510   // rax: result
8511   ShortBranchVerifier sbv(this);
8512   assert_different_registers(src, dst, len, tmp5, result);
8513   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8514 
8515   // set result
8516   xorl(result, result);
8517   // check for zero length
8518   testl(len, len);
8519   jcc(Assembler::zero, L_done);
8520 
8521   movl(result, len);
8522 
8523   // Setup pointers
8524   lea(src, Address(src, len, Address::times_2)); // char[]
8525   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8526   negptr(len);
8527 
8528   if (UseSSE42Intrinsics || UseAVX >= 2) {
8529     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8530     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8531 
8532     if (UseAVX >= 2) {
8533       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8534       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8535       movdl(tmp1Reg, tmp5);
8536       vpbroadcastd(tmp1Reg, tmp1Reg);
8537       jmp(L_chars_32_check);
8538 
8539       bind(L_copy_32_chars);
8540       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8541       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8542       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8543       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8544       jccb(Assembler::notZero, L_copy_32_chars_exit);
8545       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8546       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8547       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8548 
8549       bind(L_chars_32_check);
8550       addptr(len, 32);
8551       jcc(Assembler::lessEqual, L_copy_32_chars);
8552 
8553       bind(L_copy_32_chars_exit);
8554       subptr(len, 16);
8555       jccb(Assembler::greater, L_copy_16_chars_exit);
8556 
8557     } else if (UseSSE42Intrinsics) {
8558       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8559       movdl(tmp1Reg, tmp5);
8560       pshufd(tmp1Reg, tmp1Reg, 0);
8561       jmpb(L_chars_16_check);
8562     }
8563 
8564     bind(L_copy_16_chars);
8565     if (UseAVX >= 2) {
8566       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8567       vptest(tmp2Reg, tmp1Reg);
8568       jcc(Assembler::notZero, L_copy_16_chars_exit);
8569       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8570       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8571     } else {
8572       if (UseAVX > 0) {
8573         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8574         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8575         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8576       } else {
8577         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8578         por(tmp2Reg, tmp3Reg);
8579         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8580         por(tmp2Reg, tmp4Reg);
8581       }
8582       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8583       jccb(Assembler::notZero, L_copy_16_chars_exit);
8584       packuswb(tmp3Reg, tmp4Reg);
8585     }
8586     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8587 
8588     bind(L_chars_16_check);
8589     addptr(len, 16);
8590     jcc(Assembler::lessEqual, L_copy_16_chars);
8591 
8592     bind(L_copy_16_chars_exit);
8593     if (UseAVX >= 2) {
8594       // clean upper bits of YMM registers
8595       vpxor(tmp2Reg, tmp2Reg);
8596       vpxor(tmp3Reg, tmp3Reg);
8597       vpxor(tmp4Reg, tmp4Reg);
8598       movdl(tmp1Reg, tmp5);
8599       pshufd(tmp1Reg, tmp1Reg, 0);
8600     }
8601     subptr(len, 8);
8602     jccb(Assembler::greater, L_copy_8_chars_exit);
8603 
8604     bind(L_copy_8_chars);
8605     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8606     ptest(tmp3Reg, tmp1Reg);
8607     jccb(Assembler::notZero, L_copy_8_chars_exit);
8608     packuswb(tmp3Reg, tmp1Reg);
8609     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8610     addptr(len, 8);
8611     jccb(Assembler::lessEqual, L_copy_8_chars);
8612 
8613     bind(L_copy_8_chars_exit);
8614     subptr(len, 8);
8615     jccb(Assembler::zero, L_done);
8616   }
8617 
8618   bind(L_copy_1_char);
8619   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8620   testl(tmp5, 0xff00);      // check if Unicode char
8621   jccb(Assembler::notZero, L_copy_1_char_exit);
8622   movb(Address(dst, len, Address::times_1, 0), tmp5);
8623   addptr(len, 1);
8624   jccb(Assembler::less, L_copy_1_char);
8625 
8626   bind(L_copy_1_char_exit);
8627   addptr(result, len); // len is negative count of not processed elements
8628 
8629   bind(L_done);
8630 }
8631 
8632 #ifdef _LP64
8633 /**
8634  * Helper for multiply_to_len().
8635  */
8636 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8637   addq(dest_lo, src1);
8638   adcq(dest_hi, 0);
8639   addq(dest_lo, src2);
8640   adcq(dest_hi, 0);
8641 }
8642 
8643 /**
8644  * Multiply 64 bit by 64 bit first loop.
8645  */
8646 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8647                                            Register y, Register y_idx, Register z,
8648                                            Register carry, Register product,
8649                                            Register idx, Register kdx) {
8650   //
8651   //  jlong carry, x[], y[], z[];
8652   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8653   //    huge_128 product = y[idx] * x[xstart] + carry;
8654   //    z[kdx] = (jlong)product;
8655   //    carry  = (jlong)(product >>> 64);
8656   //  }
8657   //  z[xstart] = carry;
8658   //
8659 
8660   Label L_first_loop, L_first_loop_exit;
8661   Label L_one_x, L_one_y, L_multiply;
8662 
8663   decrementl(xstart);
8664   jcc(Assembler::negative, L_one_x);
8665 
8666   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8667   rorq(x_xstart, 32); // convert big-endian to little-endian
8668 
8669   bind(L_first_loop);
8670   decrementl(idx);
8671   jcc(Assembler::negative, L_first_loop_exit);
8672   decrementl(idx);
8673   jcc(Assembler::negative, L_one_y);
8674   movq(y_idx, Address(y, idx, Address::times_4,  0));
8675   rorq(y_idx, 32); // convert big-endian to little-endian
8676   bind(L_multiply);
8677   movq(product, x_xstart);
8678   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8679   addq(product, carry);
8680   adcq(rdx, 0);
8681   subl(kdx, 2);
8682   movl(Address(z, kdx, Address::times_4,  4), product);
8683   shrq(product, 32);
8684   movl(Address(z, kdx, Address::times_4,  0), product);
8685   movq(carry, rdx);
8686   jmp(L_first_loop);
8687 
8688   bind(L_one_y);
8689   movl(y_idx, Address(y,  0));
8690   jmp(L_multiply);
8691 
8692   bind(L_one_x);
8693   movl(x_xstart, Address(x,  0));
8694   jmp(L_first_loop);
8695 
8696   bind(L_first_loop_exit);
8697 }
8698 
8699 /**
8700  * Multiply 64 bit by 64 bit and add 128 bit.
8701  */
8702 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8703                                             Register yz_idx, Register idx,
8704                                             Register carry, Register product, int offset) {
8705   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8706   //     z[kdx] = (jlong)product;
8707 
8708   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8709   rorq(yz_idx, 32); // convert big-endian to little-endian
8710   movq(product, x_xstart);
8711   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8712   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8713   rorq(yz_idx, 32); // convert big-endian to little-endian
8714 
8715   add2_with_carry(rdx, product, carry, yz_idx);
8716 
8717   movl(Address(z, idx, Address::times_4,  offset+4), product);
8718   shrq(product, 32);
8719   movl(Address(z, idx, Address::times_4,  offset), product);
8720 
8721 }
8722 
8723 /**
8724  * Multiply 128 bit by 128 bit. Unrolled inner loop.
8725  */
8726 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
8727                                              Register yz_idx, Register idx, Register jdx,
8728                                              Register carry, Register product,
8729                                              Register carry2) {
8730   //   jlong carry, x[], y[], z[];
8731   //   int kdx = ystart+1;
8732   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8733   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
8734   //     z[kdx+idx+1] = (jlong)product;
8735   //     jlong carry2  = (jlong)(product >>> 64);
8736   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
8737   //     z[kdx+idx] = (jlong)product;
8738   //     carry  = (jlong)(product >>> 64);
8739   //   }
8740   //   idx += 2;
8741   //   if (idx > 0) {
8742   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
8743   //     z[kdx+idx] = (jlong)product;
8744   //     carry  = (jlong)(product >>> 64);
8745   //   }
8746   //
8747 
8748   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8749 
8750   movl(jdx, idx);
8751   andl(jdx, 0xFFFFFFFC);
8752   shrl(jdx, 2);
8753 
8754   bind(L_third_loop);
8755   subl(jdx, 1);
8756   jcc(Assembler::negative, L_third_loop_exit);
8757   subl(idx, 4);
8758 
8759   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
8760   movq(carry2, rdx);
8761 
8762   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
8763   movq(carry, rdx);
8764   jmp(L_third_loop);
8765 
8766   bind (L_third_loop_exit);
8767 
8768   andl (idx, 0x3);
8769   jcc(Assembler::zero, L_post_third_loop_done);
8770 
8771   Label L_check_1;
8772   subl(idx, 2);
8773   jcc(Assembler::negative, L_check_1);
8774 
8775   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
8776   movq(carry, rdx);
8777 
8778   bind (L_check_1);
8779   addl (idx, 0x2);
8780   andl (idx, 0x1);
8781   subl(idx, 1);
8782   jcc(Assembler::negative, L_post_third_loop_done);
8783 
8784   movl(yz_idx, Address(y, idx, Address::times_4,  0));
8785   movq(product, x_xstart);
8786   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
8787   movl(yz_idx, Address(z, idx, Address::times_4,  0));
8788 
8789   add2_with_carry(rdx, product, yz_idx, carry);
8790 
8791   movl(Address(z, idx, Address::times_4,  0), product);
8792   shrq(product, 32);
8793 
8794   shlq(rdx, 32);
8795   orq(product, rdx);
8796   movq(carry, product);
8797 
8798   bind(L_post_third_loop_done);
8799 }
8800 
8801 /**
8802  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
8803  *
8804  */
8805 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
8806                                                   Register carry, Register carry2,
8807                                                   Register idx, Register jdx,
8808                                                   Register yz_idx1, Register yz_idx2,
8809                                                   Register tmp, Register tmp3, Register tmp4) {
8810   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
8811 
8812   //   jlong carry, x[], y[], z[];
8813   //   int kdx = ystart+1;
8814   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8815   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
8816   //     jlong carry2  = (jlong)(tmp3 >>> 64);
8817   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
8818   //     carry  = (jlong)(tmp4 >>> 64);
8819   //     z[kdx+idx+1] = (jlong)tmp3;
8820   //     z[kdx+idx] = (jlong)tmp4;
8821   //   }
8822   //   idx += 2;
8823   //   if (idx > 0) {
8824   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
8825   //     z[kdx+idx] = (jlong)yz_idx1;
8826   //     carry  = (jlong)(yz_idx1 >>> 64);
8827   //   }
8828   //
8829 
8830   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8831 
8832   movl(jdx, idx);
8833   andl(jdx, 0xFFFFFFFC);
8834   shrl(jdx, 2);
8835 
8836   bind(L_third_loop);
8837   subl(jdx, 1);
8838   jcc(Assembler::negative, L_third_loop_exit);
8839   subl(idx, 4);
8840 
8841   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
8842   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
8843   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
8844   rorxq(yz_idx2, yz_idx2, 32);
8845 
8846   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
8847   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
8848 
8849   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
8850   rorxq(yz_idx1, yz_idx1, 32);
8851   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8852   rorxq(yz_idx2, yz_idx2, 32);
8853 
8854   if (VM_Version::supports_adx()) {
8855     adcxq(tmp3, carry);
8856     adoxq(tmp3, yz_idx1);
8857 
8858     adcxq(tmp4, tmp);
8859     adoxq(tmp4, yz_idx2);
8860 
8861     movl(carry, 0); // does not affect flags
8862     adcxq(carry2, carry);
8863     adoxq(carry2, carry);
8864   } else {
8865     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
8866     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
8867   }
8868   movq(carry, carry2);
8869 
8870   movl(Address(z, idx, Address::times_4, 12), tmp3);
8871   shrq(tmp3, 32);
8872   movl(Address(z, idx, Address::times_4,  8), tmp3);
8873 
8874   movl(Address(z, idx, Address::times_4,  4), tmp4);
8875   shrq(tmp4, 32);
8876   movl(Address(z, idx, Address::times_4,  0), tmp4);
8877 
8878   jmp(L_third_loop);
8879 
8880   bind (L_third_loop_exit);
8881 
8882   andl (idx, 0x3);
8883   jcc(Assembler::zero, L_post_third_loop_done);
8884 
8885   Label L_check_1;
8886   subl(idx, 2);
8887   jcc(Assembler::negative, L_check_1);
8888 
8889   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
8890   rorxq(yz_idx1, yz_idx1, 32);
8891   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
8892   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8893   rorxq(yz_idx2, yz_idx2, 32);
8894 
8895   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
8896 
8897   movl(Address(z, idx, Address::times_4,  4), tmp3);
8898   shrq(tmp3, 32);
8899   movl(Address(z, idx, Address::times_4,  0), tmp3);
8900   movq(carry, tmp4);
8901 
8902   bind (L_check_1);
8903   addl (idx, 0x2);
8904   andl (idx, 0x1);
8905   subl(idx, 1);
8906   jcc(Assembler::negative, L_post_third_loop_done);
8907   movl(tmp4, Address(y, idx, Address::times_4,  0));
8908   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
8909   movl(tmp4, Address(z, idx, Address::times_4,  0));
8910 
8911   add2_with_carry(carry2, tmp3, tmp4, carry);
8912 
8913   movl(Address(z, idx, Address::times_4,  0), tmp3);
8914   shrq(tmp3, 32);
8915 
8916   shlq(carry2, 32);
8917   orq(tmp3, carry2);
8918   movq(carry, tmp3);
8919 
8920   bind(L_post_third_loop_done);
8921 }
8922 
8923 /**
8924  * Code for BigInteger::multiplyToLen() instrinsic.
8925  *
8926  * rdi: x
8927  * rax: xlen
8928  * rsi: y
8929  * rcx: ylen
8930  * r8:  z
8931  * r11: zlen
8932  * r12: tmp1
8933  * r13: tmp2
8934  * r14: tmp3
8935  * r15: tmp4
8936  * rbx: tmp5
8937  *
8938  */
8939 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
8940                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
8941   ShortBranchVerifier sbv(this);
8942   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
8943 
8944   push(tmp1);
8945   push(tmp2);
8946   push(tmp3);
8947   push(tmp4);
8948   push(tmp5);
8949 
8950   push(xlen);
8951   push(zlen);
8952 
8953   const Register idx = tmp1;
8954   const Register kdx = tmp2;
8955   const Register xstart = tmp3;
8956 
8957   const Register y_idx = tmp4;
8958   const Register carry = tmp5;
8959   const Register product  = xlen;
8960   const Register x_xstart = zlen;  // reuse register
8961 
8962   // First Loop.
8963   //
8964   //  final static long LONG_MASK = 0xffffffffL;
8965   //  int xstart = xlen - 1;
8966   //  int ystart = ylen - 1;
8967   //  long carry = 0;
8968   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8969   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
8970   //    z[kdx] = (int)product;
8971   //    carry = product >>> 32;
8972   //  }
8973   //  z[xstart] = (int)carry;
8974   //
8975 
8976   movl(idx, ylen);      // idx = ylen;
8977   movl(kdx, zlen);      // kdx = xlen+ylen;
8978   xorq(carry, carry);   // carry = 0;
8979 
8980   Label L_done;
8981 
8982   movl(xstart, xlen);
8983   decrementl(xstart);
8984   jcc(Assembler::negative, L_done);
8985 
8986   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
8987 
8988   Label L_second_loop;
8989   testl(kdx, kdx);
8990   jcc(Assembler::zero, L_second_loop);
8991 
8992   Label L_carry;
8993   subl(kdx, 1);
8994   jcc(Assembler::zero, L_carry);
8995 
8996   movl(Address(z, kdx, Address::times_4,  0), carry);
8997   shrq(carry, 32);
8998   subl(kdx, 1);
8999 
9000   bind(L_carry);
9001   movl(Address(z, kdx, Address::times_4,  0), carry);
9002 
9003   // Second and third (nested) loops.
9004   //
9005   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9006   //   carry = 0;
9007   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9008   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9009   //                    (z[k] & LONG_MASK) + carry;
9010   //     z[k] = (int)product;
9011   //     carry = product >>> 32;
9012   //   }
9013   //   z[i] = (int)carry;
9014   // }
9015   //
9016   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9017 
9018   const Register jdx = tmp1;
9019 
9020   bind(L_second_loop);
9021   xorl(carry, carry);    // carry = 0;
9022   movl(jdx, ylen);       // j = ystart+1
9023 
9024   subl(xstart, 1);       // i = xstart-1;
9025   jcc(Assembler::negative, L_done);
9026 
9027   push (z);
9028 
9029   Label L_last_x;
9030   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9031   subl(xstart, 1);       // i = xstart-1;
9032   jcc(Assembler::negative, L_last_x);
9033 
9034   if (UseBMI2Instructions) {
9035     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9036     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9037   } else {
9038     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9039     rorq(x_xstart, 32);  // convert big-endian to little-endian
9040   }
9041 
9042   Label L_third_loop_prologue;
9043   bind(L_third_loop_prologue);
9044 
9045   push (x);
9046   push (xstart);
9047   push (ylen);
9048 
9049 
9050   if (UseBMI2Instructions) {
9051     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9052   } else { // !UseBMI2Instructions
9053     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9054   }
9055 
9056   pop(ylen);
9057   pop(xlen);
9058   pop(x);
9059   pop(z);
9060 
9061   movl(tmp3, xlen);
9062   addl(tmp3, 1);
9063   movl(Address(z, tmp3, Address::times_4,  0), carry);
9064   subl(tmp3, 1);
9065   jccb(Assembler::negative, L_done);
9066 
9067   shrq(carry, 32);
9068   movl(Address(z, tmp3, Address::times_4,  0), carry);
9069   jmp(L_second_loop);
9070 
9071   // Next infrequent code is moved outside loops.
9072   bind(L_last_x);
9073   if (UseBMI2Instructions) {
9074     movl(rdx, Address(x,  0));
9075   } else {
9076     movl(x_xstart, Address(x,  0));
9077   }
9078   jmp(L_third_loop_prologue);
9079 
9080   bind(L_done);
9081 
9082   pop(zlen);
9083   pop(xlen);
9084 
9085   pop(tmp5);
9086   pop(tmp4);
9087   pop(tmp3);
9088   pop(tmp2);
9089   pop(tmp1);
9090 }
9091 
9092 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9093   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9094   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9095   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9096   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9097   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9098   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9099   Label SAME_TILL_END, DONE;
9100   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9101 
9102   //scale is in rcx in both Win64 and Unix
9103   ShortBranchVerifier sbv(this);
9104 
9105   shlq(length);
9106   xorq(result, result);
9107 
9108   if ((UseAVX > 2) &&
9109       VM_Version::supports_avx512vlbw()) {
9110     set_vector_masking();  // opening of the stub context for programming mask registers
9111     cmpq(length, 64);
9112     jcc(Assembler::less, VECTOR32_TAIL);
9113     movq(tmp1, length);
9114     andq(tmp1, 0x3F);      // tail count
9115     andq(length, ~(0x3F)); //vector count
9116 
9117     bind(VECTOR64_LOOP);
9118     // AVX512 code to compare 64 byte vectors.
9119     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9120     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9121     kortestql(k7, k7);
9122     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9123     addq(result, 64);
9124     subq(length, 64);
9125     jccb(Assembler::notZero, VECTOR64_LOOP);
9126 
9127     //bind(VECTOR64_TAIL);
9128     testq(tmp1, tmp1);
9129     jcc(Assembler::zero, SAME_TILL_END);
9130 
9131     bind(VECTOR64_TAIL);
9132     // AVX512 code to compare upto 63 byte vectors.
9133     // Save k1
9134     kmovql(k3, k1);
9135     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9136     shlxq(tmp2, tmp2, tmp1);
9137     notq(tmp2);
9138     kmovql(k1, tmp2);
9139 
9140     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9141     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9142 
9143     ktestql(k7, k1);
9144     // Restore k1
9145     kmovql(k1, k3);
9146     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9147 
9148     bind(VECTOR64_NOT_EQUAL);
9149     kmovql(tmp1, k7);
9150     notq(tmp1);
9151     tzcntq(tmp1, tmp1);
9152     addq(result, tmp1);
9153     shrq(result);
9154     jmp(DONE);
9155     bind(VECTOR32_TAIL);
9156     clear_vector_masking();   // closing of the stub context for programming mask registers
9157   }
9158 
9159   cmpq(length, 8);
9160   jcc(Assembler::equal, VECTOR8_LOOP);
9161   jcc(Assembler::less, VECTOR4_TAIL);
9162 
9163   if (UseAVX >= 2) {
9164 
9165     cmpq(length, 16);
9166     jcc(Assembler::equal, VECTOR16_LOOP);
9167     jcc(Assembler::less, VECTOR8_LOOP);
9168 
9169     cmpq(length, 32);
9170     jccb(Assembler::less, VECTOR16_TAIL);
9171 
9172     subq(length, 32);
9173     bind(VECTOR32_LOOP);
9174     vmovdqu(rymm0, Address(obja, result));
9175     vmovdqu(rymm1, Address(objb, result));
9176     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9177     vptest(rymm2, rymm2);
9178     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9179     addq(result, 32);
9180     subq(length, 32);
9181     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9182     addq(length, 32);
9183     jcc(Assembler::equal, SAME_TILL_END);
9184     //falling through if less than 32 bytes left //close the branch here.
9185 
9186     bind(VECTOR16_TAIL);
9187     cmpq(length, 16);
9188     jccb(Assembler::less, VECTOR8_TAIL);
9189     bind(VECTOR16_LOOP);
9190     movdqu(rymm0, Address(obja, result));
9191     movdqu(rymm1, Address(objb, result));
9192     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9193     ptest(rymm2, rymm2);
9194     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9195     addq(result, 16);
9196     subq(length, 16);
9197     jcc(Assembler::equal, SAME_TILL_END);
9198     //falling through if less than 16 bytes left
9199   } else {//regular intrinsics
9200 
9201     cmpq(length, 16);
9202     jccb(Assembler::less, VECTOR8_TAIL);
9203 
9204     subq(length, 16);
9205     bind(VECTOR16_LOOP);
9206     movdqu(rymm0, Address(obja, result));
9207     movdqu(rymm1, Address(objb, result));
9208     pxor(rymm0, rymm1);
9209     ptest(rymm0, rymm0);
9210     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9211     addq(result, 16);
9212     subq(length, 16);
9213     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9214     addq(length, 16);
9215     jcc(Assembler::equal, SAME_TILL_END);
9216     //falling through if less than 16 bytes left
9217   }
9218 
9219   bind(VECTOR8_TAIL);
9220   cmpq(length, 8);
9221   jccb(Assembler::less, VECTOR4_TAIL);
9222   bind(VECTOR8_LOOP);
9223   movq(tmp1, Address(obja, result));
9224   movq(tmp2, Address(objb, result));
9225   xorq(tmp1, tmp2);
9226   testq(tmp1, tmp1);
9227   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9228   addq(result, 8);
9229   subq(length, 8);
9230   jcc(Assembler::equal, SAME_TILL_END);
9231   //falling through if less than 8 bytes left
9232 
9233   bind(VECTOR4_TAIL);
9234   cmpq(length, 4);
9235   jccb(Assembler::less, BYTES_TAIL);
9236   bind(VECTOR4_LOOP);
9237   movl(tmp1, Address(obja, result));
9238   xorl(tmp1, Address(objb, result));
9239   testl(tmp1, tmp1);
9240   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9241   addq(result, 4);
9242   subq(length, 4);
9243   jcc(Assembler::equal, SAME_TILL_END);
9244   //falling through if less than 4 bytes left
9245 
9246   bind(BYTES_TAIL);
9247   bind(BYTES_LOOP);
9248   load_unsigned_byte(tmp1, Address(obja, result));
9249   load_unsigned_byte(tmp2, Address(objb, result));
9250   xorl(tmp1, tmp2);
9251   testl(tmp1, tmp1);
9252   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9253   decq(length);
9254   jccb(Assembler::zero, SAME_TILL_END);
9255   incq(result);
9256   load_unsigned_byte(tmp1, Address(obja, result));
9257   load_unsigned_byte(tmp2, Address(objb, result));
9258   xorl(tmp1, tmp2);
9259   testl(tmp1, tmp1);
9260   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9261   decq(length);
9262   jccb(Assembler::zero, SAME_TILL_END);
9263   incq(result);
9264   load_unsigned_byte(tmp1, Address(obja, result));
9265   load_unsigned_byte(tmp2, Address(objb, result));
9266   xorl(tmp1, tmp2);
9267   testl(tmp1, tmp1);
9268   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9269   jmpb(SAME_TILL_END);
9270 
9271   if (UseAVX >= 2) {
9272     bind(VECTOR32_NOT_EQUAL);
9273     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9274     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9275     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9276     vpmovmskb(tmp1, rymm0);
9277     bsfq(tmp1, tmp1);
9278     addq(result, tmp1);
9279     shrq(result);
9280     jmpb(DONE);
9281   }
9282 
9283   bind(VECTOR16_NOT_EQUAL);
9284   if (UseAVX >= 2) {
9285     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9286     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9287     pxor(rymm0, rymm2);
9288   } else {
9289     pcmpeqb(rymm2, rymm2);
9290     pxor(rymm0, rymm1);
9291     pcmpeqb(rymm0, rymm1);
9292     pxor(rymm0, rymm2);
9293   }
9294   pmovmskb(tmp1, rymm0);
9295   bsfq(tmp1, tmp1);
9296   addq(result, tmp1);
9297   shrq(result);
9298   jmpb(DONE);
9299 
9300   bind(VECTOR8_NOT_EQUAL);
9301   bind(VECTOR4_NOT_EQUAL);
9302   bsfq(tmp1, tmp1);
9303   shrq(tmp1, 3);
9304   addq(result, tmp1);
9305   bind(BYTES_NOT_EQUAL);
9306   shrq(result);
9307   jmpb(DONE);
9308 
9309   bind(SAME_TILL_END);
9310   mov64(result, -1);
9311 
9312   bind(DONE);
9313 }
9314 
9315 //Helper functions for square_to_len()
9316 
9317 /**
9318  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9319  * Preserves x and z and modifies rest of the registers.
9320  */
9321 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9322   // Perform square and right shift by 1
9323   // Handle odd xlen case first, then for even xlen do the following
9324   // jlong carry = 0;
9325   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9326   //     huge_128 product = x[j:j+1] * x[j:j+1];
9327   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9328   //     z[i+2:i+3] = (jlong)(product >>> 1);
9329   //     carry = (jlong)product;
9330   // }
9331 
9332   xorq(tmp5, tmp5);     // carry
9333   xorq(rdxReg, rdxReg);
9334   xorl(tmp1, tmp1);     // index for x
9335   xorl(tmp4, tmp4);     // index for z
9336 
9337   Label L_first_loop, L_first_loop_exit;
9338 
9339   testl(xlen, 1);
9340   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9341 
9342   // Square and right shift by 1 the odd element using 32 bit multiply
9343   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9344   imulq(raxReg, raxReg);
9345   shrq(raxReg, 1);
9346   adcq(tmp5, 0);
9347   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9348   incrementl(tmp1);
9349   addl(tmp4, 2);
9350 
9351   // Square and  right shift by 1 the rest using 64 bit multiply
9352   bind(L_first_loop);
9353   cmpptr(tmp1, xlen);
9354   jccb(Assembler::equal, L_first_loop_exit);
9355 
9356   // Square
9357   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9358   rorq(raxReg, 32);    // convert big-endian to little-endian
9359   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9360 
9361   // Right shift by 1 and save carry
9362   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9363   rcrq(rdxReg, 1);
9364   rcrq(raxReg, 1);
9365   adcq(tmp5, 0);
9366 
9367   // Store result in z
9368   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9369   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9370 
9371   // Update indices for x and z
9372   addl(tmp1, 2);
9373   addl(tmp4, 4);
9374   jmp(L_first_loop);
9375 
9376   bind(L_first_loop_exit);
9377 }
9378 
9379 
9380 /**
9381  * Perform the following multiply add operation using BMI2 instructions
9382  * carry:sum = sum + op1*op2 + carry
9383  * op2 should be in rdx
9384  * op2 is preserved, all other registers are modified
9385  */
9386 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9387   // assert op2 is rdx
9388   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9389   addq(sum, carry);
9390   adcq(tmp2, 0);
9391   addq(sum, op1);
9392   adcq(tmp2, 0);
9393   movq(carry, tmp2);
9394 }
9395 
9396 /**
9397  * Perform the following multiply add operation:
9398  * carry:sum = sum + op1*op2 + carry
9399  * Preserves op1, op2 and modifies rest of registers
9400  */
9401 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9402   // rdx:rax = op1 * op2
9403   movq(raxReg, op2);
9404   mulq(op1);
9405 
9406   //  rdx:rax = sum + carry + rdx:rax
9407   addq(sum, carry);
9408   adcq(rdxReg, 0);
9409   addq(sum, raxReg);
9410   adcq(rdxReg, 0);
9411 
9412   // carry:sum = rdx:sum
9413   movq(carry, rdxReg);
9414 }
9415 
9416 /**
9417  * Add 64 bit long carry into z[] with carry propogation.
9418  * Preserves z and carry register values and modifies rest of registers.
9419  *
9420  */
9421 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9422   Label L_fourth_loop, L_fourth_loop_exit;
9423 
9424   movl(tmp1, 1);
9425   subl(zlen, 2);
9426   addq(Address(z, zlen, Address::times_4, 0), carry);
9427 
9428   bind(L_fourth_loop);
9429   jccb(Assembler::carryClear, L_fourth_loop_exit);
9430   subl(zlen, 2);
9431   jccb(Assembler::negative, L_fourth_loop_exit);
9432   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9433   jmp(L_fourth_loop);
9434   bind(L_fourth_loop_exit);
9435 }
9436 
9437 /**
9438  * Shift z[] left by 1 bit.
9439  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9440  *
9441  */
9442 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9443 
9444   Label L_fifth_loop, L_fifth_loop_exit;
9445 
9446   // Fifth loop
9447   // Perform primitiveLeftShift(z, zlen, 1)
9448 
9449   const Register prev_carry = tmp1;
9450   const Register new_carry = tmp4;
9451   const Register value = tmp2;
9452   const Register zidx = tmp3;
9453 
9454   // int zidx, carry;
9455   // long value;
9456   // carry = 0;
9457   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9458   //    (carry:value)  = (z[i] << 1) | carry ;
9459   //    z[i] = value;
9460   // }
9461 
9462   movl(zidx, zlen);
9463   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9464 
9465   bind(L_fifth_loop);
9466   decl(zidx);  // Use decl to preserve carry flag
9467   decl(zidx);
9468   jccb(Assembler::negative, L_fifth_loop_exit);
9469 
9470   if (UseBMI2Instructions) {
9471      movq(value, Address(z, zidx, Address::times_4, 0));
9472      rclq(value, 1);
9473      rorxq(value, value, 32);
9474      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9475   }
9476   else {
9477     // clear new_carry
9478     xorl(new_carry, new_carry);
9479 
9480     // Shift z[i] by 1, or in previous carry and save new carry
9481     movq(value, Address(z, zidx, Address::times_4, 0));
9482     shlq(value, 1);
9483     adcl(new_carry, 0);
9484 
9485     orq(value, prev_carry);
9486     rorq(value, 0x20);
9487     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9488 
9489     // Set previous carry = new carry
9490     movl(prev_carry, new_carry);
9491   }
9492   jmp(L_fifth_loop);
9493 
9494   bind(L_fifth_loop_exit);
9495 }
9496 
9497 
9498 /**
9499  * Code for BigInteger::squareToLen() intrinsic
9500  *
9501  * rdi: x
9502  * rsi: len
9503  * r8:  z
9504  * rcx: zlen
9505  * r12: tmp1
9506  * r13: tmp2
9507  * r14: tmp3
9508  * r15: tmp4
9509  * rbx: tmp5
9510  *
9511  */
9512 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) {
9513 
9514   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;
9515   push(tmp1);
9516   push(tmp2);
9517   push(tmp3);
9518   push(tmp4);
9519   push(tmp5);
9520 
9521   // First loop
9522   // Store the squares, right shifted one bit (i.e., divided by 2).
9523   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9524 
9525   // Add in off-diagonal sums.
9526   //
9527   // Second, third (nested) and fourth loops.
9528   // zlen +=2;
9529   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9530   //    carry = 0;
9531   //    long op2 = x[xidx:xidx+1];
9532   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9533   //       k -= 2;
9534   //       long op1 = x[j:j+1];
9535   //       long sum = z[k:k+1];
9536   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9537   //       z[k:k+1] = sum;
9538   //    }
9539   //    add_one_64(z, k, carry, tmp_regs);
9540   // }
9541 
9542   const Register carry = tmp5;
9543   const Register sum = tmp3;
9544   const Register op1 = tmp4;
9545   Register op2 = tmp2;
9546 
9547   push(zlen);
9548   push(len);
9549   addl(zlen,2);
9550   bind(L_second_loop);
9551   xorq(carry, carry);
9552   subl(zlen, 4);
9553   subl(len, 2);
9554   push(zlen);
9555   push(len);
9556   cmpl(len, 0);
9557   jccb(Assembler::lessEqual, L_second_loop_exit);
9558 
9559   // Multiply an array by one 64 bit long.
9560   if (UseBMI2Instructions) {
9561     op2 = rdxReg;
9562     movq(op2, Address(x, len, Address::times_4,  0));
9563     rorxq(op2, op2, 32);
9564   }
9565   else {
9566     movq(op2, Address(x, len, Address::times_4,  0));
9567     rorq(op2, 32);
9568   }
9569 
9570   bind(L_third_loop);
9571   decrementl(len);
9572   jccb(Assembler::negative, L_third_loop_exit);
9573   decrementl(len);
9574   jccb(Assembler::negative, L_last_x);
9575 
9576   movq(op1, Address(x, len, Address::times_4,  0));
9577   rorq(op1, 32);
9578 
9579   bind(L_multiply);
9580   subl(zlen, 2);
9581   movq(sum, Address(z, zlen, Address::times_4,  0));
9582 
9583   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9584   if (UseBMI2Instructions) {
9585     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9586   }
9587   else {
9588     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9589   }
9590 
9591   movq(Address(z, zlen, Address::times_4, 0), sum);
9592 
9593   jmp(L_third_loop);
9594   bind(L_third_loop_exit);
9595 
9596   // Fourth loop
9597   // Add 64 bit long carry into z with carry propogation.
9598   // Uses offsetted zlen.
9599   add_one_64(z, zlen, carry, tmp1);
9600 
9601   pop(len);
9602   pop(zlen);
9603   jmp(L_second_loop);
9604 
9605   // Next infrequent code is moved outside loops.
9606   bind(L_last_x);
9607   movl(op1, Address(x, 0));
9608   jmp(L_multiply);
9609 
9610   bind(L_second_loop_exit);
9611   pop(len);
9612   pop(zlen);
9613   pop(len);
9614   pop(zlen);
9615 
9616   // Fifth loop
9617   // Shift z left 1 bit.
9618   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9619 
9620   // z[zlen-1] |= x[len-1] & 1;
9621   movl(tmp3, Address(x, len, Address::times_4, -4));
9622   andl(tmp3, 1);
9623   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9624 
9625   pop(tmp5);
9626   pop(tmp4);
9627   pop(tmp3);
9628   pop(tmp2);
9629   pop(tmp1);
9630 }
9631 
9632 /**
9633  * Helper function for mul_add()
9634  * Multiply the in[] by int k and add to out[] starting at offset offs using
9635  * 128 bit by 32 bit multiply and return the carry in tmp5.
9636  * Only quad int aligned length of in[] is operated on in this function.
9637  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9638  * This function preserves out, in and k registers.
9639  * len and offset point to the appropriate index in "in" & "out" correspondingly
9640  * tmp5 has the carry.
9641  * other registers are temporary and are modified.
9642  *
9643  */
9644 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9645   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9646   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9647 
9648   Label L_first_loop, L_first_loop_exit;
9649 
9650   movl(tmp1, len);
9651   shrl(tmp1, 2);
9652 
9653   bind(L_first_loop);
9654   subl(tmp1, 1);
9655   jccb(Assembler::negative, L_first_loop_exit);
9656 
9657   subl(len, 4);
9658   subl(offset, 4);
9659 
9660   Register op2 = tmp2;
9661   const Register sum = tmp3;
9662   const Register op1 = tmp4;
9663   const Register carry = tmp5;
9664 
9665   if (UseBMI2Instructions) {
9666     op2 = rdxReg;
9667   }
9668 
9669   movq(op1, Address(in, len, Address::times_4,  8));
9670   rorq(op1, 32);
9671   movq(sum, Address(out, offset, Address::times_4,  8));
9672   rorq(sum, 32);
9673   if (UseBMI2Instructions) {
9674     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9675   }
9676   else {
9677     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9678   }
9679   // Store back in big endian from little endian
9680   rorq(sum, 0x20);
9681   movq(Address(out, offset, Address::times_4,  8), sum);
9682 
9683   movq(op1, Address(in, len, Address::times_4,  0));
9684   rorq(op1, 32);
9685   movq(sum, Address(out, offset, Address::times_4,  0));
9686   rorq(sum, 32);
9687   if (UseBMI2Instructions) {
9688     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9689   }
9690   else {
9691     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9692   }
9693   // Store back in big endian from little endian
9694   rorq(sum, 0x20);
9695   movq(Address(out, offset, Address::times_4,  0), sum);
9696 
9697   jmp(L_first_loop);
9698   bind(L_first_loop_exit);
9699 }
9700 
9701 /**
9702  * Code for BigInteger::mulAdd() intrinsic
9703  *
9704  * rdi: out
9705  * rsi: in
9706  * r11: offs (out.length - offset)
9707  * rcx: len
9708  * r8:  k
9709  * r12: tmp1
9710  * r13: tmp2
9711  * r14: tmp3
9712  * r15: tmp4
9713  * rbx: tmp5
9714  * Multiply the in[] by word k and add to out[], return the carry in rax
9715  */
9716 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9717    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9718    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9719 
9720   Label L_carry, L_last_in, L_done;
9721 
9722 // carry = 0;
9723 // for (int j=len-1; j >= 0; j--) {
9724 //    long product = (in[j] & LONG_MASK) * kLong +
9725 //                   (out[offs] & LONG_MASK) + carry;
9726 //    out[offs--] = (int)product;
9727 //    carry = product >>> 32;
9728 // }
9729 //
9730   push(tmp1);
9731   push(tmp2);
9732   push(tmp3);
9733   push(tmp4);
9734   push(tmp5);
9735 
9736   Register op2 = tmp2;
9737   const Register sum = tmp3;
9738   const Register op1 = tmp4;
9739   const Register carry =  tmp5;
9740 
9741   if (UseBMI2Instructions) {
9742     op2 = rdxReg;
9743     movl(op2, k);
9744   }
9745   else {
9746     movl(op2, k);
9747   }
9748 
9749   xorq(carry, carry);
9750 
9751   //First loop
9752 
9753   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9754   //The carry is in tmp5
9755   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9756 
9757   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9758   decrementl(len);
9759   jccb(Assembler::negative, L_carry);
9760   decrementl(len);
9761   jccb(Assembler::negative, L_last_in);
9762 
9763   movq(op1, Address(in, len, Address::times_4,  0));
9764   rorq(op1, 32);
9765 
9766   subl(offs, 2);
9767   movq(sum, Address(out, offs, Address::times_4,  0));
9768   rorq(sum, 32);
9769 
9770   if (UseBMI2Instructions) {
9771     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9772   }
9773   else {
9774     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9775   }
9776 
9777   // Store back in big endian from little endian
9778   rorq(sum, 0x20);
9779   movq(Address(out, offs, Address::times_4,  0), sum);
9780 
9781   testl(len, len);
9782   jccb(Assembler::zero, L_carry);
9783 
9784   //Multiply the last in[] entry, if any
9785   bind(L_last_in);
9786   movl(op1, Address(in, 0));
9787   movl(sum, Address(out, offs, Address::times_4,  -4));
9788 
9789   movl(raxReg, k);
9790   mull(op1); //tmp4 * eax -> edx:eax
9791   addl(sum, carry);
9792   adcl(rdxReg, 0);
9793   addl(sum, raxReg);
9794   adcl(rdxReg, 0);
9795   movl(carry, rdxReg);
9796 
9797   movl(Address(out, offs, Address::times_4,  -4), sum);
9798 
9799   bind(L_carry);
9800   //return tmp5/carry as carry in rax
9801   movl(rax, carry);
9802 
9803   bind(L_done);
9804   pop(tmp5);
9805   pop(tmp4);
9806   pop(tmp3);
9807   pop(tmp2);
9808   pop(tmp1);
9809 }
9810 #endif
9811 
9812 /**
9813  * Emits code to update CRC-32 with a byte value according to constants in table
9814  *
9815  * @param [in,out]crc   Register containing the crc.
9816  * @param [in]val       Register containing the byte to fold into the CRC.
9817  * @param [in]table     Register containing the table of crc constants.
9818  *
9819  * uint32_t crc;
9820  * val = crc_table[(val ^ crc) & 0xFF];
9821  * crc = val ^ (crc >> 8);
9822  *
9823  */
9824 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9825   xorl(val, crc);
9826   andl(val, 0xFF);
9827   shrl(crc, 8); // unsigned shift
9828   xorl(crc, Address(table, val, Address::times_4, 0));
9829 }
9830 
9831 /**
9832 * Fold four 128-bit data chunks
9833 */
9834 void MacroAssembler::fold_128bit_crc32_avx512(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9835   evpclmulhdq(xtmp, xK, xcrc, Assembler::AVX_512bit); // [123:64]
9836   evpclmulldq(xcrc, xK, xcrc, Assembler::AVX_512bit); // [63:0]
9837   evpxorq(xcrc, xcrc, Address(buf, offset), Assembler::AVX_512bit /* vector_len */);
9838   evpxorq(xcrc, xcrc, xtmp, Assembler::AVX_512bit /* vector_len */);
9839 }
9840 
9841 /**
9842  * Fold 128-bit data chunk
9843  */
9844 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9845   if (UseAVX > 0) {
9846     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9847     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9848     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9849     pxor(xcrc, xtmp);
9850   } else {
9851     movdqa(xtmp, xcrc);
9852     pclmulhdq(xtmp, xK);   // [123:64]
9853     pclmulldq(xcrc, xK);   // [63:0]
9854     pxor(xcrc, xtmp);
9855     movdqu(xtmp, Address(buf, offset));
9856     pxor(xcrc, xtmp);
9857   }
9858 }
9859 
9860 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9861   if (UseAVX > 0) {
9862     vpclmulhdq(xtmp, xK, xcrc);
9863     vpclmulldq(xcrc, xK, xcrc);
9864     pxor(xcrc, xbuf);
9865     pxor(xcrc, xtmp);
9866   } else {
9867     movdqa(xtmp, xcrc);
9868     pclmulhdq(xtmp, xK);
9869     pclmulldq(xcrc, xK);
9870     pxor(xcrc, xbuf);
9871     pxor(xcrc, xtmp);
9872   }
9873 }
9874 
9875 /**
9876  * 8-bit folds to compute 32-bit CRC
9877  *
9878  * uint64_t xcrc;
9879  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9880  */
9881 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9882   movdl(tmp, xcrc);
9883   andl(tmp, 0xFF);
9884   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
9885   psrldq(xcrc, 1); // unsigned shift one byte
9886   pxor(xcrc, xtmp);
9887 }
9888 
9889 /**
9890  * uint32_t crc;
9891  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
9892  */
9893 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
9894   movl(tmp, crc);
9895   andl(tmp, 0xFF);
9896   shrl(crc, 8);
9897   xorl(crc, Address(table, tmp, Address::times_4, 0));
9898 }
9899 
9900 /**
9901  * @param crc   register containing existing CRC (32-bit)
9902  * @param buf   register pointing to input byte buffer (byte*)
9903  * @param len   register containing number of bytes
9904  * @param table register that will contain address of CRC table
9905  * @param tmp   scratch register
9906  */
9907 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
9908   assert_different_registers(crc, buf, len, table, tmp, rax);
9909 
9910   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
9911   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
9912 
9913   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
9914   // context for the registers used, where all instructions below are using 128-bit mode
9915   // On EVEX without VL and BW, these instructions will all be AVX.
9916   if (VM_Version::supports_avx512vlbw()) {
9917     movl(tmp, 0xffff);
9918     kmovwl(k1, tmp);
9919   }
9920 
9921   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
9922   notl(crc); // ~crc
9923   cmpl(len, 16);
9924   jcc(Assembler::less, L_tail);
9925 
9926   // Align buffer to 16 bytes
9927   movl(tmp, buf);
9928   andl(tmp, 0xF);
9929   jccb(Assembler::zero, L_aligned);
9930   subl(tmp,  16);
9931   addl(len, tmp);
9932 
9933   align(4);
9934   BIND(L_align_loop);
9935   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9936   update_byte_crc32(crc, rax, table);
9937   increment(buf);
9938   incrementl(tmp);
9939   jccb(Assembler::less, L_align_loop);
9940 
9941   BIND(L_aligned);
9942   movl(tmp, len); // save
9943   shrl(len, 4);
9944   jcc(Assembler::zero, L_tail_restore);
9945 
9946   // Fold total 512 bits of polynomial on each iteration
9947   if (VM_Version::supports_vpclmulqdq()) {
9948     Label Parallel_loop, L_No_Parallel;
9949 
9950     cmpl(len, 8);
9951     jccb(Assembler::less, L_No_Parallel);
9952 
9953     movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9954     evmovdquq(xmm1, Address(buf, 0), Assembler::AVX_512bit);
9955     movdl(xmm5, crc);
9956     evpxorq(xmm1, xmm1, xmm5, Assembler::AVX_512bit);
9957     addptr(buf, 64);
9958     subl(len, 7);
9959     evshufi64x2(xmm0, xmm0, xmm0, 0x00, Assembler::AVX_512bit); //propagate the mask from 128 bits to 512 bits
9960 
9961     BIND(Parallel_loop);
9962     fold_128bit_crc32_avx512(xmm1, xmm0, xmm5, buf, 0);
9963     addptr(buf, 64);
9964     subl(len, 4);
9965     jcc(Assembler::greater, Parallel_loop);
9966 
9967     vextracti64x2(xmm2, xmm1, 0x01);
9968     vextracti64x2(xmm3, xmm1, 0x02);
9969     vextracti64x2(xmm4, xmm1, 0x03);
9970     jmp(L_fold_512b);
9971 
9972     BIND(L_No_Parallel);
9973   }
9974   // Fold crc into first bytes of vector
9975   movdqa(xmm1, Address(buf, 0));
9976   movdl(rax, xmm1);
9977   xorl(crc, rax);
9978   if (VM_Version::supports_sse4_1()) {
9979     pinsrd(xmm1, crc, 0);
9980   } else {
9981     pinsrw(xmm1, crc, 0);
9982     shrl(crc, 16);
9983     pinsrw(xmm1, crc, 1);
9984   }
9985   addptr(buf, 16);
9986   subl(len, 4); // len > 0
9987   jcc(Assembler::less, L_fold_tail);
9988 
9989   movdqa(xmm2, Address(buf,  0));
9990   movdqa(xmm3, Address(buf, 16));
9991   movdqa(xmm4, Address(buf, 32));
9992   addptr(buf, 48);
9993   subl(len, 3);
9994   jcc(Assembler::lessEqual, L_fold_512b);
9995 
9996   // Fold total 512 bits of polynomial on each iteration,
9997   // 128 bits per each of 4 parallel streams.
9998   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9999 
10000   align(32);
10001   BIND(L_fold_512b_loop);
10002   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10003   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10004   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10005   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10006   addptr(buf, 64);
10007   subl(len, 4);
10008   jcc(Assembler::greater, L_fold_512b_loop);
10009 
10010   // Fold 512 bits to 128 bits.
10011   BIND(L_fold_512b);
10012   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10013   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10014   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10015   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10016 
10017   // Fold the rest of 128 bits data chunks
10018   BIND(L_fold_tail);
10019   addl(len, 3);
10020   jccb(Assembler::lessEqual, L_fold_128b);
10021   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10022 
10023   BIND(L_fold_tail_loop);
10024   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10025   addptr(buf, 16);
10026   decrementl(len);
10027   jccb(Assembler::greater, L_fold_tail_loop);
10028 
10029   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10030   BIND(L_fold_128b);
10031   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10032   if (UseAVX > 0) {
10033     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10034     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10035     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10036   } else {
10037     movdqa(xmm2, xmm0);
10038     pclmulqdq(xmm2, xmm1, 0x1);
10039     movdqa(xmm3, xmm0);
10040     pand(xmm3, xmm2);
10041     pclmulqdq(xmm0, xmm3, 0x1);
10042   }
10043   psrldq(xmm1, 8);
10044   psrldq(xmm2, 4);
10045   pxor(xmm0, xmm1);
10046   pxor(xmm0, xmm2);
10047 
10048   // 8 8-bit folds to compute 32-bit CRC.
10049   for (int j = 0; j < 4; j++) {
10050     fold_8bit_crc32(xmm0, table, xmm1, rax);
10051   }
10052   movdl(crc, xmm0); // mov 32 bits to general register
10053   for (int j = 0; j < 4; j++) {
10054     fold_8bit_crc32(crc, table, rax);
10055   }
10056 
10057   BIND(L_tail_restore);
10058   movl(len, tmp); // restore
10059   BIND(L_tail);
10060   andl(len, 0xf);
10061   jccb(Assembler::zero, L_exit);
10062 
10063   // Fold the rest of bytes
10064   align(4);
10065   BIND(L_tail_loop);
10066   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10067   update_byte_crc32(crc, rax, table);
10068   increment(buf);
10069   decrementl(len);
10070   jccb(Assembler::greater, L_tail_loop);
10071 
10072   BIND(L_exit);
10073   notl(crc); // ~c
10074 }
10075 
10076 #ifdef _LP64
10077 // S. Gueron / Information Processing Letters 112 (2012) 184
10078 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10079 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10080 // Output: the 64-bit carry-less product of B * CONST
10081 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10082                                      Register tmp1, Register tmp2, Register tmp3) {
10083   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10084   if (n > 0) {
10085     addq(tmp3, n * 256 * 8);
10086   }
10087   //    Q1 = TABLEExt[n][B & 0xFF];
10088   movl(tmp1, in);
10089   andl(tmp1, 0x000000FF);
10090   shll(tmp1, 3);
10091   addq(tmp1, tmp3);
10092   movq(tmp1, Address(tmp1, 0));
10093 
10094   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10095   movl(tmp2, in);
10096   shrl(tmp2, 8);
10097   andl(tmp2, 0x000000FF);
10098   shll(tmp2, 3);
10099   addq(tmp2, tmp3);
10100   movq(tmp2, Address(tmp2, 0));
10101 
10102   shlq(tmp2, 8);
10103   xorq(tmp1, tmp2);
10104 
10105   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10106   movl(tmp2, in);
10107   shrl(tmp2, 16);
10108   andl(tmp2, 0x000000FF);
10109   shll(tmp2, 3);
10110   addq(tmp2, tmp3);
10111   movq(tmp2, Address(tmp2, 0));
10112 
10113   shlq(tmp2, 16);
10114   xorq(tmp1, tmp2);
10115 
10116   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10117   shrl(in, 24);
10118   andl(in, 0x000000FF);
10119   shll(in, 3);
10120   addq(in, tmp3);
10121   movq(in, Address(in, 0));
10122 
10123   shlq(in, 24);
10124   xorq(in, tmp1);
10125   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10126 }
10127 
10128 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10129                                       Register in_out,
10130                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10131                                       XMMRegister w_xtmp2,
10132                                       Register tmp1,
10133                                       Register n_tmp2, Register n_tmp3) {
10134   if (is_pclmulqdq_supported) {
10135     movdl(w_xtmp1, in_out); // modified blindly
10136 
10137     movl(tmp1, const_or_pre_comp_const_index);
10138     movdl(w_xtmp2, tmp1);
10139     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10140 
10141     movdq(in_out, w_xtmp1);
10142   } else {
10143     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10144   }
10145 }
10146 
10147 // Recombination Alternative 2: No bit-reflections
10148 // T1 = (CRC_A * U1) << 1
10149 // T2 = (CRC_B * U2) << 1
10150 // C1 = T1 >> 32
10151 // C2 = T2 >> 32
10152 // T1 = T1 & 0xFFFFFFFF
10153 // T2 = T2 & 0xFFFFFFFF
10154 // T1 = CRC32(0, T1)
10155 // T2 = CRC32(0, T2)
10156 // C1 = C1 ^ T1
10157 // C2 = C2 ^ T2
10158 // CRC = C1 ^ C2 ^ CRC_C
10159 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,
10160                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10161                                      Register tmp1, Register tmp2,
10162                                      Register n_tmp3) {
10163   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10164   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10165   shlq(in_out, 1);
10166   movl(tmp1, in_out);
10167   shrq(in_out, 32);
10168   xorl(tmp2, tmp2);
10169   crc32(tmp2, tmp1, 4);
10170   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10171   shlq(in1, 1);
10172   movl(tmp1, in1);
10173   shrq(in1, 32);
10174   xorl(tmp2, tmp2);
10175   crc32(tmp2, tmp1, 4);
10176   xorl(in1, tmp2);
10177   xorl(in_out, in1);
10178   xorl(in_out, in2);
10179 }
10180 
10181 // Set N to predefined value
10182 // Subtract from a lenght of a buffer
10183 // execute in a loop:
10184 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10185 // for i = 1 to N do
10186 //  CRC_A = CRC32(CRC_A, A[i])
10187 //  CRC_B = CRC32(CRC_B, B[i])
10188 //  CRC_C = CRC32(CRC_C, C[i])
10189 // end for
10190 // Recombine
10191 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,
10192                                        Register in_out1, Register in_out2, Register in_out3,
10193                                        Register tmp1, Register tmp2, Register tmp3,
10194                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10195                                        Register tmp4, Register tmp5,
10196                                        Register n_tmp6) {
10197   Label L_processPartitions;
10198   Label L_processPartition;
10199   Label L_exit;
10200 
10201   bind(L_processPartitions);
10202   cmpl(in_out1, 3 * size);
10203   jcc(Assembler::less, L_exit);
10204     xorl(tmp1, tmp1);
10205     xorl(tmp2, tmp2);
10206     movq(tmp3, in_out2);
10207     addq(tmp3, size);
10208 
10209     bind(L_processPartition);
10210       crc32(in_out3, Address(in_out2, 0), 8);
10211       crc32(tmp1, Address(in_out2, size), 8);
10212       crc32(tmp2, Address(in_out2, size * 2), 8);
10213       addq(in_out2, 8);
10214       cmpq(in_out2, tmp3);
10215       jcc(Assembler::less, L_processPartition);
10216     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10217             w_xtmp1, w_xtmp2, w_xtmp3,
10218             tmp4, tmp5,
10219             n_tmp6);
10220     addq(in_out2, 2 * size);
10221     subl(in_out1, 3 * size);
10222     jmp(L_processPartitions);
10223 
10224   bind(L_exit);
10225 }
10226 #else
10227 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10228                                      Register tmp1, Register tmp2, Register tmp3,
10229                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10230   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10231   if (n > 0) {
10232     addl(tmp3, n * 256 * 8);
10233   }
10234   //    Q1 = TABLEExt[n][B & 0xFF];
10235   movl(tmp1, in_out);
10236   andl(tmp1, 0x000000FF);
10237   shll(tmp1, 3);
10238   addl(tmp1, tmp3);
10239   movq(xtmp1, Address(tmp1, 0));
10240 
10241   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10242   movl(tmp2, in_out);
10243   shrl(tmp2, 8);
10244   andl(tmp2, 0x000000FF);
10245   shll(tmp2, 3);
10246   addl(tmp2, tmp3);
10247   movq(xtmp2, Address(tmp2, 0));
10248 
10249   psllq(xtmp2, 8);
10250   pxor(xtmp1, xtmp2);
10251 
10252   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10253   movl(tmp2, in_out);
10254   shrl(tmp2, 16);
10255   andl(tmp2, 0x000000FF);
10256   shll(tmp2, 3);
10257   addl(tmp2, tmp3);
10258   movq(xtmp2, Address(tmp2, 0));
10259 
10260   psllq(xtmp2, 16);
10261   pxor(xtmp1, xtmp2);
10262 
10263   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10264   shrl(in_out, 24);
10265   andl(in_out, 0x000000FF);
10266   shll(in_out, 3);
10267   addl(in_out, tmp3);
10268   movq(xtmp2, Address(in_out, 0));
10269 
10270   psllq(xtmp2, 24);
10271   pxor(xtmp1, xtmp2); // Result in CXMM
10272   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10273 }
10274 
10275 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10276                                       Register in_out,
10277                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10278                                       XMMRegister w_xtmp2,
10279                                       Register tmp1,
10280                                       Register n_tmp2, Register n_tmp3) {
10281   if (is_pclmulqdq_supported) {
10282     movdl(w_xtmp1, in_out);
10283 
10284     movl(tmp1, const_or_pre_comp_const_index);
10285     movdl(w_xtmp2, tmp1);
10286     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10287     // Keep result in XMM since GPR is 32 bit in length
10288   } else {
10289     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10290   }
10291 }
10292 
10293 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,
10294                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10295                                      Register tmp1, Register tmp2,
10296                                      Register n_tmp3) {
10297   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10298   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10299 
10300   psllq(w_xtmp1, 1);
10301   movdl(tmp1, w_xtmp1);
10302   psrlq(w_xtmp1, 32);
10303   movdl(in_out, w_xtmp1);
10304 
10305   xorl(tmp2, tmp2);
10306   crc32(tmp2, tmp1, 4);
10307   xorl(in_out, tmp2);
10308 
10309   psllq(w_xtmp2, 1);
10310   movdl(tmp1, w_xtmp2);
10311   psrlq(w_xtmp2, 32);
10312   movdl(in1, w_xtmp2);
10313 
10314   xorl(tmp2, tmp2);
10315   crc32(tmp2, tmp1, 4);
10316   xorl(in1, tmp2);
10317   xorl(in_out, in1);
10318   xorl(in_out, in2);
10319 }
10320 
10321 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,
10322                                        Register in_out1, Register in_out2, Register in_out3,
10323                                        Register tmp1, Register tmp2, Register tmp3,
10324                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10325                                        Register tmp4, Register tmp5,
10326                                        Register n_tmp6) {
10327   Label L_processPartitions;
10328   Label L_processPartition;
10329   Label L_exit;
10330 
10331   bind(L_processPartitions);
10332   cmpl(in_out1, 3 * size);
10333   jcc(Assembler::less, L_exit);
10334     xorl(tmp1, tmp1);
10335     xorl(tmp2, tmp2);
10336     movl(tmp3, in_out2);
10337     addl(tmp3, size);
10338 
10339     bind(L_processPartition);
10340       crc32(in_out3, Address(in_out2, 0), 4);
10341       crc32(tmp1, Address(in_out2, size), 4);
10342       crc32(tmp2, Address(in_out2, size*2), 4);
10343       crc32(in_out3, Address(in_out2, 0+4), 4);
10344       crc32(tmp1, Address(in_out2, size+4), 4);
10345       crc32(tmp2, Address(in_out2, size*2+4), 4);
10346       addl(in_out2, 8);
10347       cmpl(in_out2, tmp3);
10348       jcc(Assembler::less, L_processPartition);
10349 
10350         push(tmp3);
10351         push(in_out1);
10352         push(in_out2);
10353         tmp4 = tmp3;
10354         tmp5 = in_out1;
10355         n_tmp6 = in_out2;
10356 
10357       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10358             w_xtmp1, w_xtmp2, w_xtmp3,
10359             tmp4, tmp5,
10360             n_tmp6);
10361 
10362         pop(in_out2);
10363         pop(in_out1);
10364         pop(tmp3);
10365 
10366     addl(in_out2, 2 * size);
10367     subl(in_out1, 3 * size);
10368     jmp(L_processPartitions);
10369 
10370   bind(L_exit);
10371 }
10372 #endif //LP64
10373 
10374 #ifdef _LP64
10375 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10376 // Input: A buffer I of L bytes.
10377 // Output: the CRC32C value of the buffer.
10378 // Notations:
10379 // Write L = 24N + r, with N = floor (L/24).
10380 // r = L mod 24 (0 <= r < 24).
10381 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10382 // N quadwords, and R consists of r bytes.
10383 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10384 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10385 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10386 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10387 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10388                                           Register tmp1, Register tmp2, Register tmp3,
10389                                           Register tmp4, Register tmp5, Register tmp6,
10390                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10391                                           bool is_pclmulqdq_supported) {
10392   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10393   Label L_wordByWord;
10394   Label L_byteByByteProlog;
10395   Label L_byteByByte;
10396   Label L_exit;
10397 
10398   if (is_pclmulqdq_supported ) {
10399     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10400     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10401 
10402     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10403     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10404 
10405     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10406     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10407     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10408   } else {
10409     const_or_pre_comp_const_index[0] = 1;
10410     const_or_pre_comp_const_index[1] = 0;
10411 
10412     const_or_pre_comp_const_index[2] = 3;
10413     const_or_pre_comp_const_index[3] = 2;
10414 
10415     const_or_pre_comp_const_index[4] = 5;
10416     const_or_pre_comp_const_index[5] = 4;
10417    }
10418   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10419                     in2, in1, in_out,
10420                     tmp1, tmp2, tmp3,
10421                     w_xtmp1, w_xtmp2, w_xtmp3,
10422                     tmp4, tmp5,
10423                     tmp6);
10424   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10425                     in2, in1, in_out,
10426                     tmp1, tmp2, tmp3,
10427                     w_xtmp1, w_xtmp2, w_xtmp3,
10428                     tmp4, tmp5,
10429                     tmp6);
10430   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10431                     in2, in1, in_out,
10432                     tmp1, tmp2, tmp3,
10433                     w_xtmp1, w_xtmp2, w_xtmp3,
10434                     tmp4, tmp5,
10435                     tmp6);
10436   movl(tmp1, in2);
10437   andl(tmp1, 0x00000007);
10438   negl(tmp1);
10439   addl(tmp1, in2);
10440   addq(tmp1, in1);
10441 
10442   BIND(L_wordByWord);
10443   cmpq(in1, tmp1);
10444   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10445     crc32(in_out, Address(in1, 0), 4);
10446     addq(in1, 4);
10447     jmp(L_wordByWord);
10448 
10449   BIND(L_byteByByteProlog);
10450   andl(in2, 0x00000007);
10451   movl(tmp2, 1);
10452 
10453   BIND(L_byteByByte);
10454   cmpl(tmp2, in2);
10455   jccb(Assembler::greater, L_exit);
10456     crc32(in_out, Address(in1, 0), 1);
10457     incq(in1);
10458     incl(tmp2);
10459     jmp(L_byteByByte);
10460 
10461   BIND(L_exit);
10462 }
10463 #else
10464 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10465                                           Register tmp1, Register  tmp2, Register tmp3,
10466                                           Register tmp4, Register  tmp5, Register tmp6,
10467                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10468                                           bool is_pclmulqdq_supported) {
10469   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10470   Label L_wordByWord;
10471   Label L_byteByByteProlog;
10472   Label L_byteByByte;
10473   Label L_exit;
10474 
10475   if (is_pclmulqdq_supported) {
10476     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10477     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10478 
10479     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10480     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10481 
10482     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10483     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10484   } else {
10485     const_or_pre_comp_const_index[0] = 1;
10486     const_or_pre_comp_const_index[1] = 0;
10487 
10488     const_or_pre_comp_const_index[2] = 3;
10489     const_or_pre_comp_const_index[3] = 2;
10490 
10491     const_or_pre_comp_const_index[4] = 5;
10492     const_or_pre_comp_const_index[5] = 4;
10493   }
10494   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10495                     in2, in1, in_out,
10496                     tmp1, tmp2, tmp3,
10497                     w_xtmp1, w_xtmp2, w_xtmp3,
10498                     tmp4, tmp5,
10499                     tmp6);
10500   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10501                     in2, in1, in_out,
10502                     tmp1, tmp2, tmp3,
10503                     w_xtmp1, w_xtmp2, w_xtmp3,
10504                     tmp4, tmp5,
10505                     tmp6);
10506   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10507                     in2, in1, in_out,
10508                     tmp1, tmp2, tmp3,
10509                     w_xtmp1, w_xtmp2, w_xtmp3,
10510                     tmp4, tmp5,
10511                     tmp6);
10512   movl(tmp1, in2);
10513   andl(tmp1, 0x00000007);
10514   negl(tmp1);
10515   addl(tmp1, in2);
10516   addl(tmp1, in1);
10517 
10518   BIND(L_wordByWord);
10519   cmpl(in1, tmp1);
10520   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10521     crc32(in_out, Address(in1,0), 4);
10522     addl(in1, 4);
10523     jmp(L_wordByWord);
10524 
10525   BIND(L_byteByByteProlog);
10526   andl(in2, 0x00000007);
10527   movl(tmp2, 1);
10528 
10529   BIND(L_byteByByte);
10530   cmpl(tmp2, in2);
10531   jccb(Assembler::greater, L_exit);
10532     movb(tmp1, Address(in1, 0));
10533     crc32(in_out, tmp1, 1);
10534     incl(in1);
10535     incl(tmp2);
10536     jmp(L_byteByByte);
10537 
10538   BIND(L_exit);
10539 }
10540 #endif // LP64
10541 #undef BIND
10542 #undef BLOCK_COMMENT
10543 
10544 // Compress char[] array to byte[].
10545 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10546 //   @HotSpotIntrinsicCandidate
10547 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10548 //     for (int i = 0; i < len; i++) {
10549 //       int c = src[srcOff++];
10550 //       if (c >>> 8 != 0) {
10551 //         return 0;
10552 //       }
10553 //       dst[dstOff++] = (byte)c;
10554 //     }
10555 //     return len;
10556 //   }
10557 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10558   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10559   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10560   Register tmp5, Register result) {
10561   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10562 
10563   // rsi: src
10564   // rdi: dst
10565   // rdx: len
10566   // rcx: tmp5
10567   // rax: result
10568 
10569   // rsi holds start addr of source char[] to be compressed
10570   // rdi holds start addr of destination byte[]
10571   // rdx holds length
10572 
10573   assert(len != result, "");
10574 
10575   // save length for return
10576   push(len);
10577 
10578   if ((UseAVX > 2) && // AVX512
10579     VM_Version::supports_avx512vlbw() &&
10580     VM_Version::supports_bmi2()) {
10581 
10582     set_vector_masking();  // opening of the stub context for programming mask registers
10583 
10584     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10585 
10586     // alignement
10587     Label post_alignement;
10588 
10589     // if length of the string is less than 16, handle it in an old fashioned
10590     // way
10591     testl(len, -32);
10592     jcc(Assembler::zero, below_threshold);
10593 
10594     // First check whether a character is compressable ( <= 0xFF).
10595     // Create mask to test for Unicode chars inside zmm vector
10596     movl(result, 0x00FF);
10597     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10598 
10599     // Save k1
10600     kmovql(k3, k1);
10601 
10602     testl(len, -64);
10603     jcc(Assembler::zero, post_alignement);
10604 
10605     movl(tmp5, dst);
10606     andl(tmp5, (32 - 1));
10607     negl(tmp5);
10608     andl(tmp5, (32 - 1));
10609 
10610     // bail out when there is nothing to be done
10611     testl(tmp5, 0xFFFFFFFF);
10612     jcc(Assembler::zero, post_alignement);
10613 
10614     // ~(~0 << len), where len is the # of remaining elements to process
10615     movl(result, 0xFFFFFFFF);
10616     shlxl(result, result, tmp5);
10617     notl(result);
10618     kmovdl(k1, result);
10619 
10620     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10621     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10622     ktestd(k2, k1);
10623     jcc(Assembler::carryClear, restore_k1_return_zero);
10624 
10625     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10626 
10627     addptr(src, tmp5);
10628     addptr(src, tmp5);
10629     addptr(dst, tmp5);
10630     subl(len, tmp5);
10631 
10632     bind(post_alignement);
10633     // end of alignement
10634 
10635     movl(tmp5, len);
10636     andl(tmp5, (32 - 1));    // tail count (in chars)
10637     andl(len, ~(32 - 1));    // vector count (in chars)
10638     jcc(Assembler::zero, copy_loop_tail);
10639 
10640     lea(src, Address(src, len, Address::times_2));
10641     lea(dst, Address(dst, len, Address::times_1));
10642     negptr(len);
10643 
10644     bind(copy_32_loop);
10645     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10646     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10647     kortestdl(k2, k2);
10648     jcc(Assembler::carryClear, restore_k1_return_zero);
10649 
10650     // All elements in current processed chunk are valid candidates for
10651     // compression. Write a truncated byte elements to the memory.
10652     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10653     addptr(len, 32);
10654     jcc(Assembler::notZero, copy_32_loop);
10655 
10656     bind(copy_loop_tail);
10657     // bail out when there is nothing to be done
10658     testl(tmp5, 0xFFFFFFFF);
10659     // Restore k1
10660     kmovql(k1, k3);
10661     jcc(Assembler::zero, return_length);
10662 
10663     movl(len, tmp5);
10664 
10665     // ~(~0 << len), where len is the # of remaining elements to process
10666     movl(result, 0xFFFFFFFF);
10667     shlxl(result, result, len);
10668     notl(result);
10669 
10670     kmovdl(k1, result);
10671 
10672     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10673     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10674     ktestd(k2, k1);
10675     jcc(Assembler::carryClear, restore_k1_return_zero);
10676 
10677     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10678     // Restore k1
10679     kmovql(k1, k3);
10680     jmp(return_length);
10681 
10682     bind(restore_k1_return_zero);
10683     // Restore k1
10684     kmovql(k1, k3);
10685     jmp(return_zero);
10686 
10687     clear_vector_masking();   // closing of the stub context for programming mask registers
10688   }
10689   if (UseSSE42Intrinsics) {
10690     Label copy_32_loop, copy_16, copy_tail;
10691 
10692     bind(below_threshold);
10693 
10694     movl(result, len);
10695 
10696     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10697 
10698     // vectored compression
10699     andl(len, 0xfffffff0);    // vector count (in chars)
10700     andl(result, 0x0000000f);    // tail count (in chars)
10701     testl(len, len);
10702     jccb(Assembler::zero, copy_16);
10703 
10704     // compress 16 chars per iter
10705     movdl(tmp1Reg, tmp5);
10706     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10707     pxor(tmp4Reg, tmp4Reg);
10708 
10709     lea(src, Address(src, len, Address::times_2));
10710     lea(dst, Address(dst, len, Address::times_1));
10711     negptr(len);
10712 
10713     bind(copy_32_loop);
10714     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10715     por(tmp4Reg, tmp2Reg);
10716     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10717     por(tmp4Reg, tmp3Reg);
10718     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10719     jcc(Assembler::notZero, return_zero);
10720     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10721     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10722     addptr(len, 16);
10723     jcc(Assembler::notZero, copy_32_loop);
10724 
10725     // compress next vector of 8 chars (if any)
10726     bind(copy_16);
10727     movl(len, result);
10728     andl(len, 0xfffffff8);    // vector count (in chars)
10729     andl(result, 0x00000007);    // tail count (in chars)
10730     testl(len, len);
10731     jccb(Assembler::zero, copy_tail);
10732 
10733     movdl(tmp1Reg, tmp5);
10734     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10735     pxor(tmp3Reg, tmp3Reg);
10736 
10737     movdqu(tmp2Reg, Address(src, 0));
10738     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10739     jccb(Assembler::notZero, return_zero);
10740     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10741     movq(Address(dst, 0), tmp2Reg);
10742     addptr(src, 16);
10743     addptr(dst, 8);
10744 
10745     bind(copy_tail);
10746     movl(len, result);
10747   }
10748   // compress 1 char per iter
10749   testl(len, len);
10750   jccb(Assembler::zero, return_length);
10751   lea(src, Address(src, len, Address::times_2));
10752   lea(dst, Address(dst, len, Address::times_1));
10753   negptr(len);
10754 
10755   bind(copy_chars_loop);
10756   load_unsigned_short(result, Address(src, len, Address::times_2));
10757   testl(result, 0xff00);      // check if Unicode char
10758   jccb(Assembler::notZero, return_zero);
10759   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10760   increment(len);
10761   jcc(Assembler::notZero, copy_chars_loop);
10762 
10763   // if compression succeeded, return length
10764   bind(return_length);
10765   pop(result);
10766   jmpb(done);
10767 
10768   // if compression failed, return 0
10769   bind(return_zero);
10770   xorl(result, result);
10771   addptr(rsp, wordSize);
10772 
10773   bind(done);
10774 }
10775 
10776 // Inflate byte[] array to char[].
10777 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
10778 //   @HotSpotIntrinsicCandidate
10779 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
10780 //     for (int i = 0; i < len; i++) {
10781 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
10782 //     }
10783 //   }
10784 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10785   XMMRegister tmp1, Register tmp2) {
10786   Label copy_chars_loop, done, below_threshold;
10787   // rsi: src
10788   // rdi: dst
10789   // rdx: len
10790   // rcx: tmp2
10791 
10792   // rsi holds start addr of source byte[] to be inflated
10793   // rdi holds start addr of destination char[]
10794   // rdx holds length
10795   assert_different_registers(src, dst, len, tmp2);
10796 
10797   if ((UseAVX > 2) && // AVX512
10798     VM_Version::supports_avx512vlbw() &&
10799     VM_Version::supports_bmi2()) {
10800 
10801     set_vector_masking();  // opening of the stub context for programming mask registers
10802 
10803     Label copy_32_loop, copy_tail;
10804     Register tmp3_aliased = len;
10805 
10806     // if length of the string is less than 16, handle it in an old fashioned
10807     // way
10808     testl(len, -16);
10809     jcc(Assembler::zero, below_threshold);
10810 
10811     // In order to use only one arithmetic operation for the main loop we use
10812     // this pre-calculation
10813     movl(tmp2, len);
10814     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
10815     andl(len, -32);     // vector count
10816     jccb(Assembler::zero, copy_tail);
10817 
10818     lea(src, Address(src, len, Address::times_1));
10819     lea(dst, Address(dst, len, Address::times_2));
10820     negptr(len);
10821 
10822 
10823     // inflate 32 chars per iter
10824     bind(copy_32_loop);
10825     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
10826     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
10827     addptr(len, 32);
10828     jcc(Assembler::notZero, copy_32_loop);
10829 
10830     bind(copy_tail);
10831     // bail out when there is nothing to be done
10832     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
10833     jcc(Assembler::zero, done);
10834 
10835     // Save k1
10836     kmovql(k2, k1);
10837 
10838     // ~(~0 << length), where length is the # of remaining elements to process
10839     movl(tmp3_aliased, -1);
10840     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
10841     notl(tmp3_aliased);
10842     kmovdl(k1, tmp3_aliased);
10843     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
10844     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
10845 
10846     // Restore k1
10847     kmovql(k1, k2);
10848     jmp(done);
10849 
10850     clear_vector_masking();   // closing of the stub context for programming mask registers
10851   }
10852   if (UseSSE42Intrinsics) {
10853     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
10854 
10855     movl(tmp2, len);
10856 
10857     if (UseAVX > 1) {
10858       andl(tmp2, (16 - 1));
10859       andl(len, -16);
10860       jccb(Assembler::zero, copy_new_tail);
10861     } else {
10862       andl(tmp2, 0x00000007);   // tail count (in chars)
10863       andl(len, 0xfffffff8);    // vector count (in chars)
10864       jccb(Assembler::zero, copy_tail);
10865     }
10866 
10867     // vectored inflation
10868     lea(src, Address(src, len, Address::times_1));
10869     lea(dst, Address(dst, len, Address::times_2));
10870     negptr(len);
10871 
10872     if (UseAVX > 1) {
10873       bind(copy_16_loop);
10874       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
10875       vmovdqu(Address(dst, len, Address::times_2), tmp1);
10876       addptr(len, 16);
10877       jcc(Assembler::notZero, copy_16_loop);
10878 
10879       bind(below_threshold);
10880       bind(copy_new_tail);
10881       if ((UseAVX > 2) &&
10882         VM_Version::supports_avx512vlbw() &&
10883         VM_Version::supports_bmi2()) {
10884         movl(tmp2, len);
10885       } else {
10886         movl(len, tmp2);
10887       }
10888       andl(tmp2, 0x00000007);
10889       andl(len, 0xFFFFFFF8);
10890       jccb(Assembler::zero, copy_tail);
10891 
10892       pmovzxbw(tmp1, Address(src, 0));
10893       movdqu(Address(dst, 0), tmp1);
10894       addptr(src, 8);
10895       addptr(dst, 2 * 8);
10896 
10897       jmp(copy_tail, true);
10898     }
10899 
10900     // inflate 8 chars per iter
10901     bind(copy_8_loop);
10902     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10903     movdqu(Address(dst, len, Address::times_2), tmp1);
10904     addptr(len, 8);
10905     jcc(Assembler::notZero, copy_8_loop);
10906 
10907     bind(copy_tail);
10908     movl(len, tmp2);
10909 
10910     cmpl(len, 4);
10911     jccb(Assembler::less, copy_bytes);
10912 
10913     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10914     pmovzxbw(tmp1, tmp1);
10915     movq(Address(dst, 0), tmp1);
10916     subptr(len, 4);
10917     addptr(src, 4);
10918     addptr(dst, 8);
10919 
10920     bind(copy_bytes);
10921   }
10922   testl(len, len);
10923   jccb(Assembler::zero, done);
10924   lea(src, Address(src, len, Address::times_1));
10925   lea(dst, Address(dst, len, Address::times_2));
10926   negptr(len);
10927 
10928   // inflate 1 char per iter
10929   bind(copy_chars_loop);
10930   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10931   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10932   increment(len);
10933   jcc(Assembler::notZero, copy_chars_loop);
10934 
10935   bind(done);
10936 }
10937 
10938 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10939   switch (cond) {
10940     // Note some conditions are synonyms for others
10941     case Assembler::zero:         return Assembler::notZero;
10942     case Assembler::notZero:      return Assembler::zero;
10943     case Assembler::less:         return Assembler::greaterEqual;
10944     case Assembler::lessEqual:    return Assembler::greater;
10945     case Assembler::greater:      return Assembler::lessEqual;
10946     case Assembler::greaterEqual: return Assembler::less;
10947     case Assembler::below:        return Assembler::aboveEqual;
10948     case Assembler::belowEqual:   return Assembler::above;
10949     case Assembler::above:        return Assembler::belowEqual;
10950     case Assembler::aboveEqual:   return Assembler::below;
10951     case Assembler::overflow:     return Assembler::noOverflow;
10952     case Assembler::noOverflow:   return Assembler::overflow;
10953     case Assembler::negative:     return Assembler::positive;
10954     case Assembler::positive:     return Assembler::negative;
10955     case Assembler::parity:       return Assembler::noParity;
10956     case Assembler::noParity:     return Assembler::parity;
10957   }
10958   ShouldNotReachHere(); return Assembler::overflow;
10959 }
10960 
10961 SkipIfEqual::SkipIfEqual(
10962     MacroAssembler* masm, const bool* flag_addr, bool value) {
10963   _masm = masm;
10964   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10965   _masm->jcc(Assembler::equal, _label);
10966 }
10967 
10968 SkipIfEqual::~SkipIfEqual() {
10969   _masm->bind(_label);
10970 }
10971 
10972 // 32-bit Windows has its own fast-path implementation
10973 // of get_thread
10974 #if !defined(WIN32) || defined(_LP64)
10975 
10976 // This is simply a call to Thread::current()
10977 void MacroAssembler::get_thread(Register thread) {
10978   if (thread != rax) {
10979     push(rax);
10980   }
10981   LP64_ONLY(push(rdi);)
10982   LP64_ONLY(push(rsi);)
10983   push(rdx);
10984   push(rcx);
10985 #ifdef _LP64
10986   push(r8);
10987   push(r9);
10988   push(r10);
10989   push(r11);
10990 #endif
10991 
10992   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
10993 
10994 #ifdef _LP64
10995   pop(r11);
10996   pop(r10);
10997   pop(r9);
10998   pop(r8);
10999 #endif
11000   pop(rcx);
11001   pop(rdx);
11002   LP64_ONLY(pop(rsi);)
11003   LP64_ONLY(pop(rdi);)
11004   if (thread != rax) {
11005     mov(thread, rax);
11006     pop(rax);
11007   }
11008 }
11009 
11010 #endif