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