1 /*
   2  * Copyright (c) 1997, 2017, 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 "asm/assembler.hpp"
  27 #include "asm/assembler.inline.hpp"
  28 #include "compiler/disassembler.hpp"
  29 #include "gc/shared/barrierSet.hpp"
  30 #include "gc/shared/barrierSetCodeGen.hpp"
  31 #include "gc/shared/collectedHeap.inline.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "memory/universe.hpp"
  35 #include "oops/klass.inline.hpp"
  36 #include "prims/methodHandles.hpp"
  37 #include "runtime/access.hpp"
  38 #include "runtime/biasedLocking.hpp"
  39 #include "runtime/interfaceSupport.hpp"
  40 #include "runtime/objectMonitor.hpp"
  41 #include "runtime/os.hpp"
  42 #include "runtime/sharedRuntime.hpp"
  43 #include "runtime/stubRoutines.hpp"
  44 #include "runtime/thread.hpp"
  45 #include "utilities/macros.hpp"
  46 #include "crc32c.h"
  47 #ifdef COMPILER2
  48 #include "opto/intrinsicnode.hpp"
  49 #endif
  50 
  51 #ifdef PRODUCT
  52 #define BLOCK_COMMENT(str) /* nothing */
  53 #define STOP(error) stop(error)
  54 #else
  55 #define BLOCK_COMMENT(str) block_comment(str)
  56 #define STOP(error) block_comment(error); stop(error)
  57 #endif
  58 
  59 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  60 
  61 #ifdef ASSERT
  62 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  63 #endif
  64 
  65 static Assembler::Condition reverse[] = {
  66     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  67     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  68     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  69     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  70     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  71     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  72     Assembler::above          /* belowEqual    = 0x6 */ ,
  73     Assembler::belowEqual     /* above         = 0x7 */ ,
  74     Assembler::positive       /* negative      = 0x8 */ ,
  75     Assembler::negative       /* positive      = 0x9 */ ,
  76     Assembler::noParity       /* parity        = 0xa */ ,
  77     Assembler::parity         /* noParity      = 0xb */ ,
  78     Assembler::greaterEqual   /* less          = 0xc */ ,
  79     Assembler::less           /* greaterEqual  = 0xd */ ,
  80     Assembler::greater        /* lessEqual     = 0xe */ ,
  81     Assembler::lessEqual      /* greater       = 0xf, */
  82 
  83 };
  84 
  85 
  86 // Implementation of MacroAssembler
  87 
  88 // First all the versions that have distinct versions depending on 32/64 bit
  89 // Unless the difference is trivial (1 line or so).
  90 
  91 #ifndef _LP64
  92 
  93 // 32bit versions
  94 
  95 Address MacroAssembler::as_Address(AddressLiteral adr) {
  96   return Address(adr.target(), adr.rspec());
  97 }
  98 
  99 Address MacroAssembler::as_Address(ArrayAddress adr) {
 100   return Address::make_array(adr);
 101 }
 102 
 103 void MacroAssembler::call_VM_leaf_base(address entry_point,
 104                                        int number_of_arguments) {
 105   call(RuntimeAddress(entry_point));
 106   increment(rsp, number_of_arguments * wordSize);
 107 }
 108 
 109 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 110   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 111 }
 112 
 113 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 114   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 115 }
 116 
 117 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 118   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 119 }
 120 
 121 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 122   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 123 }
 124 
 125 void MacroAssembler::extend_sign(Register hi, Register lo) {
 126   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 127   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 128     cdql();
 129   } else {
 130     movl(hi, lo);
 131     sarl(hi, 31);
 132   }
 133 }
 134 
 135 void MacroAssembler::jC2(Register tmp, Label& L) {
 136   // set parity bit if FPU flag C2 is set (via rax)
 137   save_rax(tmp);
 138   fwait(); fnstsw_ax();
 139   sahf();
 140   restore_rax(tmp);
 141   // branch
 142   jcc(Assembler::parity, L);
 143 }
 144 
 145 void MacroAssembler::jnC2(Register tmp, Label& L) {
 146   // set parity bit if FPU flag C2 is set (via rax)
 147   save_rax(tmp);
 148   fwait(); fnstsw_ax();
 149   sahf();
 150   restore_rax(tmp);
 151   // branch
 152   jcc(Assembler::noParity, L);
 153 }
 154 
 155 // 32bit can do a case table jump in one instruction but we no longer allow the base
 156 // to be installed in the Address class
 157 void MacroAssembler::jump(ArrayAddress entry) {
 158   jmp(as_Address(entry));
 159 }
 160 
 161 // Note: y_lo will be destroyed
 162 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 163   // Long compare for Java (semantics as described in JVM spec.)
 164   Label high, low, done;
 165 
 166   cmpl(x_hi, y_hi);
 167   jcc(Assembler::less, low);
 168   jcc(Assembler::greater, high);
 169   // x_hi is the return register
 170   xorl(x_hi, x_hi);
 171   cmpl(x_lo, y_lo);
 172   jcc(Assembler::below, low);
 173   jcc(Assembler::equal, done);
 174 
 175   bind(high);
 176   xorl(x_hi, x_hi);
 177   increment(x_hi);
 178   jmp(done);
 179 
 180   bind(low);
 181   xorl(x_hi, x_hi);
 182   decrementl(x_hi);
 183 
 184   bind(done);
 185 }
 186 
 187 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 188     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 189 }
 190 
 191 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 192   // leal(dst, as_Address(adr));
 193   // see note in movl as to why we must use a move
 194   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 195 }
 196 
 197 void MacroAssembler::leave() {
 198   mov(rsp, rbp);
 199   pop(rbp);
 200 }
 201 
 202 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 203   // Multiplication of two Java long values stored on the stack
 204   // as illustrated below. Result is in rdx:rax.
 205   //
 206   // rsp ---> [  ??  ] \               \
 207   //            ....    | y_rsp_offset  |
 208   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 209   //          [ y_hi ]                  | (in bytes)
 210   //            ....                    |
 211   //          [ x_lo ]                 /
 212   //          [ x_hi ]
 213   //            ....
 214   //
 215   // Basic idea: lo(result) = lo(x_lo * y_lo)
 216   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 217   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 218   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 219   Label quick;
 220   // load x_hi, y_hi and check if quick
 221   // multiplication is possible
 222   movl(rbx, x_hi);
 223   movl(rcx, y_hi);
 224   movl(rax, rbx);
 225   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 226   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 227   // do full multiplication
 228   // 1st step
 229   mull(y_lo);                                    // x_hi * y_lo
 230   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 231   // 2nd step
 232   movl(rax, x_lo);
 233   mull(rcx);                                     // x_lo * y_hi
 234   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 235   // 3rd step
 236   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 237   movl(rax, x_lo);
 238   mull(y_lo);                                    // x_lo * y_lo
 239   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 240 }
 241 
 242 void MacroAssembler::lneg(Register hi, Register lo) {
 243   negl(lo);
 244   adcl(hi, 0);
 245   negl(hi);
 246 }
 247 
 248 void MacroAssembler::lshl(Register hi, Register lo) {
 249   // Java shift left long support (semantics as described in JVM spec., p.305)
 250   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 251   // shift value is in rcx !
 252   assert(hi != rcx, "must not use rcx");
 253   assert(lo != rcx, "must not use rcx");
 254   const Register s = rcx;                        // shift count
 255   const int      n = BitsPerWord;
 256   Label L;
 257   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 258   cmpl(s, n);                                    // if (s < n)
 259   jcc(Assembler::less, L);                       // else (s >= n)
 260   movl(hi, lo);                                  // x := x << n
 261   xorl(lo, lo);
 262   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 263   bind(L);                                       // s (mod n) < n
 264   shldl(hi, lo);                                 // x := x << s
 265   shll(lo);
 266 }
 267 
 268 
 269 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 270   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 271   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 272   assert(hi != rcx, "must not use rcx");
 273   assert(lo != rcx, "must not use rcx");
 274   const Register s = rcx;                        // shift count
 275   const int      n = BitsPerWord;
 276   Label L;
 277   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 278   cmpl(s, n);                                    // if (s < n)
 279   jcc(Assembler::less, L);                       // else (s >= n)
 280   movl(lo, hi);                                  // x := x >> n
 281   if (sign_extension) sarl(hi, 31);
 282   else                xorl(hi, hi);
 283   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 284   bind(L);                                       // s (mod n) < n
 285   shrdl(lo, hi);                                 // x := x >> s
 286   if (sign_extension) sarl(hi);
 287   else                shrl(hi);
 288 }
 289 
 290 void MacroAssembler::movoop(Register dst, jobject obj) {
 291   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 292 }
 293 
 294 void MacroAssembler::movoop(Address dst, jobject obj) {
 295   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 296 }
 297 
 298 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 299   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 300 }
 301 
 302 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 303   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 304 }
 305 
 306 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 307   // scratch register is not used,
 308   // it is defined to match parameters of 64-bit version of this method.
 309   if (src.is_lval()) {
 310     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 311   } else {
 312     movl(dst, as_Address(src));
 313   }
 314 }
 315 
 316 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 317   movl(as_Address(dst), src);
 318 }
 319 
 320 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 321   movl(dst, as_Address(src));
 322 }
 323 
 324 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 325 void MacroAssembler::movptr(Address dst, intptr_t src) {
 326   movl(dst, src);
 327 }
 328 
 329 
 330 void MacroAssembler::pop_callee_saved_registers() {
 331   pop(rcx);
 332   pop(rdx);
 333   pop(rdi);
 334   pop(rsi);
 335 }
 336 
 337 void MacroAssembler::pop_fTOS() {
 338   fld_d(Address(rsp, 0));
 339   addl(rsp, 2 * wordSize);
 340 }
 341 
 342 void MacroAssembler::push_callee_saved_registers() {
 343   push(rsi);
 344   push(rdi);
 345   push(rdx);
 346   push(rcx);
 347 }
 348 
 349 void MacroAssembler::push_fTOS() {
 350   subl(rsp, 2 * wordSize);
 351   fstp_d(Address(rsp, 0));
 352 }
 353 
 354 
 355 void MacroAssembler::pushoop(jobject obj) {
 356   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 357 }
 358 
 359 void MacroAssembler::pushklass(Metadata* obj) {
 360   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 361 }
 362 
 363 void MacroAssembler::pushptr(AddressLiteral src) {
 364   if (src.is_lval()) {
 365     push_literal32((int32_t)src.target(), src.rspec());
 366   } else {
 367     pushl(as_Address(src));
 368   }
 369 }
 370 
 371 void MacroAssembler::set_word_if_not_zero(Register dst) {
 372   xorl(dst, dst);
 373   set_byte_if_not_zero(dst);
 374 }
 375 
 376 static void pass_arg0(MacroAssembler* masm, Register arg) {
 377   masm->push(arg);
 378 }
 379 
 380 static void pass_arg1(MacroAssembler* masm, Register arg) {
 381   masm->push(arg);
 382 }
 383 
 384 static void pass_arg2(MacroAssembler* masm, Register arg) {
 385   masm->push(arg);
 386 }
 387 
 388 static void pass_arg3(MacroAssembler* masm, Register arg) {
 389   masm->push(arg);
 390 }
 391 
 392 #ifndef PRODUCT
 393 extern "C" void findpc(intptr_t x);
 394 #endif
 395 
 396 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 397   // In order to get locks to work, we need to fake a in_VM state
 398   JavaThread* thread = JavaThread::current();
 399   JavaThreadState saved_state = thread->thread_state();
 400   thread->set_thread_state(_thread_in_vm);
 401   if (ShowMessageBoxOnError) {
 402     JavaThread* thread = JavaThread::current();
 403     JavaThreadState saved_state = thread->thread_state();
 404     thread->set_thread_state(_thread_in_vm);
 405     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 406       ttyLocker ttyl;
 407       BytecodeCounter::print();
 408     }
 409     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 410     // This is the value of eip which points to where verify_oop will return.
 411     if (os::message_box(msg, "Execution stopped, print registers?")) {
 412       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 413       BREAKPOINT;
 414     }
 415   } else {
 416     ttyLocker ttyl;
 417     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 418   }
 419   // Don't assert holding the ttyLock
 420     assert(false, "DEBUG MESSAGE: %s", msg);
 421   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 422 }
 423 
 424 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 425   ttyLocker ttyl;
 426   FlagSetting fs(Debugging, true);
 427   tty->print_cr("eip = 0x%08x", eip);
 428 #ifndef PRODUCT
 429   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 430     tty->cr();
 431     findpc(eip);
 432     tty->cr();
 433   }
 434 #endif
 435 #define PRINT_REG(rax) \
 436   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 437   PRINT_REG(rax);
 438   PRINT_REG(rbx);
 439   PRINT_REG(rcx);
 440   PRINT_REG(rdx);
 441   PRINT_REG(rdi);
 442   PRINT_REG(rsi);
 443   PRINT_REG(rbp);
 444   PRINT_REG(rsp);
 445 #undef PRINT_REG
 446   // Print some words near top of staack.
 447   int* dump_sp = (int*) rsp;
 448   for (int col1 = 0; col1 < 8; col1++) {
 449     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 450     os::print_location(tty, *dump_sp++);
 451   }
 452   for (int row = 0; row < 16; row++) {
 453     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 454     for (int col = 0; col < 8; col++) {
 455       tty->print(" 0x%08x", *dump_sp++);
 456     }
 457     tty->cr();
 458   }
 459   // Print some instructions around pc:
 460   Disassembler::decode((address)eip-64, (address)eip);
 461   tty->print_cr("--------");
 462   Disassembler::decode((address)eip, (address)eip+32);
 463 }
 464 
 465 void MacroAssembler::stop(const char* msg) {
 466   ExternalAddress message((address)msg);
 467   // push address of message
 468   pushptr(message.addr());
 469   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 470   pusha();                                            // push registers
 471   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 472   hlt();
 473 }
 474 
 475 void MacroAssembler::warn(const char* msg) {
 476   push_CPU_state();
 477 
 478   ExternalAddress message((address) msg);
 479   // push address of message
 480   pushptr(message.addr());
 481 
 482   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 483   addl(rsp, wordSize);       // discard argument
 484   pop_CPU_state();
 485 }
 486 
 487 void MacroAssembler::print_state() {
 488   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 489   pusha();                                            // push registers
 490 
 491   push_CPU_state();
 492   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 493   pop_CPU_state();
 494 
 495   popa();
 496   addl(rsp, wordSize);
 497 }
 498 
 499 #else // _LP64
 500 
 501 // 64 bit versions
 502 
 503 Address MacroAssembler::as_Address(AddressLiteral adr) {
 504   // amd64 always does this as a pc-rel
 505   // we can be absolute or disp based on the instruction type
 506   // jmp/call are displacements others are absolute
 507   assert(!adr.is_lval(), "must be rval");
 508   assert(reachable(adr), "must be");
 509   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 510 
 511 }
 512 
 513 Address MacroAssembler::as_Address(ArrayAddress adr) {
 514   AddressLiteral base = adr.base();
 515   lea(rscratch1, base);
 516   Address index = adr.index();
 517   assert(index._disp == 0, "must not have disp"); // maybe it can?
 518   Address array(rscratch1, index._index, index._scale, index._disp);
 519   return array;
 520 }
 521 
 522 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 523   Label L, E;
 524 
 525 #ifdef _WIN64
 526   // Windows always allocates space for it's register args
 527   assert(num_args <= 4, "only register arguments supported");
 528   subq(rsp,  frame::arg_reg_save_area_bytes);
 529 #endif
 530 
 531   // Align stack if necessary
 532   testl(rsp, 15);
 533   jcc(Assembler::zero, L);
 534 
 535   subq(rsp, 8);
 536   {
 537     call(RuntimeAddress(entry_point));
 538   }
 539   addq(rsp, 8);
 540   jmp(E);
 541 
 542   bind(L);
 543   {
 544     call(RuntimeAddress(entry_point));
 545   }
 546 
 547   bind(E);
 548 
 549 #ifdef _WIN64
 550   // restore stack pointer
 551   addq(rsp, frame::arg_reg_save_area_bytes);
 552 #endif
 553 
 554 }
 555 
 556 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 557   assert(!src2.is_lval(), "should use cmpptr");
 558 
 559   if (reachable(src2)) {
 560     cmpq(src1, as_Address(src2));
 561   } else {
 562     lea(rscratch1, src2);
 563     Assembler::cmpq(src1, Address(rscratch1, 0));
 564   }
 565 }
 566 
 567 int MacroAssembler::corrected_idivq(Register reg) {
 568   // Full implementation of Java ldiv and lrem; checks for special
 569   // case as described in JVM spec., p.243 & p.271.  The function
 570   // returns the (pc) offset of the idivl instruction - may be needed
 571   // for implicit exceptions.
 572   //
 573   //         normal case                           special case
 574   //
 575   // input : rax: dividend                         min_long
 576   //         reg: divisor   (may not be eax/edx)   -1
 577   //
 578   // output: rax: quotient  (= rax idiv reg)       min_long
 579   //         rdx: remainder (= rax irem reg)       0
 580   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 581   static const int64_t min_long = 0x8000000000000000;
 582   Label normal_case, special_case;
 583 
 584   // check for special case
 585   cmp64(rax, ExternalAddress((address) &min_long));
 586   jcc(Assembler::notEqual, normal_case);
 587   xorl(rdx, rdx); // prepare rdx for possible special case (where
 588                   // remainder = 0)
 589   cmpq(reg, -1);
 590   jcc(Assembler::equal, special_case);
 591 
 592   // handle normal case
 593   bind(normal_case);
 594   cdqq();
 595   int idivq_offset = offset();
 596   idivq(reg);
 597 
 598   // normal and special case exit
 599   bind(special_case);
 600 
 601   return idivq_offset;
 602 }
 603 
 604 void MacroAssembler::decrementq(Register reg, int value) {
 605   if (value == min_jint) { subq(reg, value); return; }
 606   if (value <  0) { incrementq(reg, -value); return; }
 607   if (value == 0) {                        ; return; }
 608   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 609   /* else */      { subq(reg, value)       ; return; }
 610 }
 611 
 612 void MacroAssembler::decrementq(Address dst, int value) {
 613   if (value == min_jint) { subq(dst, value); return; }
 614   if (value <  0) { incrementq(dst, -value); return; }
 615   if (value == 0) {                        ; return; }
 616   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 617   /* else */      { subq(dst, value)       ; return; }
 618 }
 619 
 620 void MacroAssembler::incrementq(AddressLiteral dst) {
 621   if (reachable(dst)) {
 622     incrementq(as_Address(dst));
 623   } else {
 624     lea(rscratch1, dst);
 625     incrementq(Address(rscratch1, 0));
 626   }
 627 }
 628 
 629 void MacroAssembler::incrementq(Register reg, int value) {
 630   if (value == min_jint) { addq(reg, value); return; }
 631   if (value <  0) { decrementq(reg, -value); return; }
 632   if (value == 0) {                        ; return; }
 633   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 634   /* else */      { addq(reg, value)       ; return; }
 635 }
 636 
 637 void MacroAssembler::incrementq(Address dst, int value) {
 638   if (value == min_jint) { addq(dst, value); return; }
 639   if (value <  0) { decrementq(dst, -value); return; }
 640   if (value == 0) {                        ; return; }
 641   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 642   /* else */      { addq(dst, value)       ; return; }
 643 }
 644 
 645 // 32bit can do a case table jump in one instruction but we no longer allow the base
 646 // to be installed in the Address class
 647 void MacroAssembler::jump(ArrayAddress entry) {
 648   lea(rscratch1, entry.base());
 649   Address dispatch = entry.index();
 650   assert(dispatch._base == noreg, "must be");
 651   dispatch._base = rscratch1;
 652   jmp(dispatch);
 653 }
 654 
 655 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 656   ShouldNotReachHere(); // 64bit doesn't use two regs
 657   cmpq(x_lo, y_lo);
 658 }
 659 
 660 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 661     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 662 }
 663 
 664 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 665   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 666   movptr(dst, rscratch1);
 667 }
 668 
 669 void MacroAssembler::leave() {
 670   // %%% is this really better? Why not on 32bit too?
 671   emit_int8((unsigned char)0xC9); // LEAVE
 672 }
 673 
 674 void MacroAssembler::lneg(Register hi, Register lo) {
 675   ShouldNotReachHere(); // 64bit doesn't use two regs
 676   negq(lo);
 677 }
 678 
 679 void MacroAssembler::movoop(Register dst, jobject obj) {
 680   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 681 }
 682 
 683 void MacroAssembler::movoop(Address dst, jobject obj) {
 684   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 685   movq(dst, rscratch1);
 686 }
 687 
 688 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 689   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 690 }
 691 
 692 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 693   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 694   movq(dst, rscratch1);
 695 }
 696 
 697 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 698   if (src.is_lval()) {
 699     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 700   } else {
 701     if (reachable(src)) {
 702       movq(dst, as_Address(src));
 703     } else {
 704       lea(scratch, src);
 705       movq(dst, Address(scratch, 0));
 706     }
 707   }
 708 }
 709 
 710 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 711   movq(as_Address(dst), src);
 712 }
 713 
 714 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 715   movq(dst, as_Address(src));
 716 }
 717 
 718 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 719 void MacroAssembler::movptr(Address dst, intptr_t src) {
 720   mov64(rscratch1, src);
 721   movq(dst, rscratch1);
 722 }
 723 
 724 // These are mostly for initializing NULL
 725 void MacroAssembler::movptr(Address dst, int32_t src) {
 726   movslq(dst, src);
 727 }
 728 
 729 void MacroAssembler::movptr(Register dst, int32_t src) {
 730   mov64(dst, (intptr_t)src);
 731 }
 732 
 733 void MacroAssembler::pushoop(jobject obj) {
 734   movoop(rscratch1, obj);
 735   push(rscratch1);
 736 }
 737 
 738 void MacroAssembler::pushklass(Metadata* obj) {
 739   mov_metadata(rscratch1, obj);
 740   push(rscratch1);
 741 }
 742 
 743 void MacroAssembler::pushptr(AddressLiteral src) {
 744   lea(rscratch1, src);
 745   if (src.is_lval()) {
 746     push(rscratch1);
 747   } else {
 748     pushq(Address(rscratch1, 0));
 749   }
 750 }
 751 
 752 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 753   // we must set sp to zero to clear frame
 754   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 755   // must clear fp, so that compiled frames are not confused; it is
 756   // possible that we need it only for debugging
 757   if (clear_fp) {
 758     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 759   }
 760 
 761   // Always clear the pc because it could have been set by make_walkable()
 762   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 763 }
 764 
 765 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 766                                          Register last_java_fp,
 767                                          address  last_java_pc) {
 768   // determine last_java_sp register
 769   if (!last_java_sp->is_valid()) {
 770     last_java_sp = rsp;
 771   }
 772 
 773   // last_java_fp is optional
 774   if (last_java_fp->is_valid()) {
 775     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 776            last_java_fp);
 777   }
 778 
 779   // last_java_pc is optional
 780   if (last_java_pc != NULL) {
 781     Address java_pc(r15_thread,
 782                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 783     lea(rscratch1, InternalAddress(last_java_pc));
 784     movptr(java_pc, rscratch1);
 785   }
 786 
 787   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 788 }
 789 
 790 static void pass_arg0(MacroAssembler* masm, Register arg) {
 791   if (c_rarg0 != arg ) {
 792     masm->mov(c_rarg0, arg);
 793   }
 794 }
 795 
 796 static void pass_arg1(MacroAssembler* masm, Register arg) {
 797   if (c_rarg1 != arg ) {
 798     masm->mov(c_rarg1, arg);
 799   }
 800 }
 801 
 802 static void pass_arg2(MacroAssembler* masm, Register arg) {
 803   if (c_rarg2 != arg ) {
 804     masm->mov(c_rarg2, arg);
 805   }
 806 }
 807 
 808 static void pass_arg3(MacroAssembler* masm, Register arg) {
 809   if (c_rarg3 != arg ) {
 810     masm->mov(c_rarg3, arg);
 811   }
 812 }
 813 
 814 void MacroAssembler::stop(const char* msg) {
 815   address rip = pc();
 816   pusha(); // get regs on stack
 817   lea(c_rarg0, ExternalAddress((address) msg));
 818   lea(c_rarg1, InternalAddress(rip));
 819   movq(c_rarg2, rsp); // pass pointer to regs array
 820   andq(rsp, -16); // align stack as required by ABI
 821   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 822   hlt();
 823 }
 824 
 825 void MacroAssembler::warn(const char* msg) {
 826   push(rbp);
 827   movq(rbp, rsp);
 828   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 829   push_CPU_state();   // keeps alignment at 16 bytes
 830   lea(c_rarg0, ExternalAddress((address) msg));
 831   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 832   pop_CPU_state();
 833   mov(rsp, rbp);
 834   pop(rbp);
 835 }
 836 
 837 void MacroAssembler::print_state() {
 838   address rip = pc();
 839   pusha();            // get regs on stack
 840   push(rbp);
 841   movq(rbp, rsp);
 842   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 843   push_CPU_state();   // keeps alignment at 16 bytes
 844 
 845   lea(c_rarg0, InternalAddress(rip));
 846   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 847   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 848 
 849   pop_CPU_state();
 850   mov(rsp, rbp);
 851   pop(rbp);
 852   popa();
 853 }
 854 
 855 #ifndef PRODUCT
 856 extern "C" void findpc(intptr_t x);
 857 #endif
 858 
 859 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 860   // In order to get locks to work, we need to fake a in_VM state
 861   if (ShowMessageBoxOnError) {
 862     JavaThread* thread = JavaThread::current();
 863     JavaThreadState saved_state = thread->thread_state();
 864     thread->set_thread_state(_thread_in_vm);
 865 #ifndef PRODUCT
 866     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 867       ttyLocker ttyl;
 868       BytecodeCounter::print();
 869     }
 870 #endif
 871     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 872     // XXX correct this offset for amd64
 873     // This is the value of eip which points to where verify_oop will return.
 874     if (os::message_box(msg, "Execution stopped, print registers?")) {
 875       print_state64(pc, regs);
 876       BREAKPOINT;
 877       assert(false, "start up GDB");
 878     }
 879     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 880   } else {
 881     ttyLocker ttyl;
 882     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 883                     msg);
 884     assert(false, "DEBUG MESSAGE: %s", msg);
 885   }
 886 }
 887 
 888 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 889   ttyLocker ttyl;
 890   FlagSetting fs(Debugging, true);
 891   tty->print_cr("rip = 0x%016lx", pc);
 892 #ifndef PRODUCT
 893   tty->cr();
 894   findpc(pc);
 895   tty->cr();
 896 #endif
 897 #define PRINT_REG(rax, value) \
 898   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 899   PRINT_REG(rax, regs[15]);
 900   PRINT_REG(rbx, regs[12]);
 901   PRINT_REG(rcx, regs[14]);
 902   PRINT_REG(rdx, regs[13]);
 903   PRINT_REG(rdi, regs[8]);
 904   PRINT_REG(rsi, regs[9]);
 905   PRINT_REG(rbp, regs[10]);
 906   PRINT_REG(rsp, regs[11]);
 907   PRINT_REG(r8 , regs[7]);
 908   PRINT_REG(r9 , regs[6]);
 909   PRINT_REG(r10, regs[5]);
 910   PRINT_REG(r11, regs[4]);
 911   PRINT_REG(r12, regs[3]);
 912   PRINT_REG(r13, regs[2]);
 913   PRINT_REG(r14, regs[1]);
 914   PRINT_REG(r15, regs[0]);
 915 #undef PRINT_REG
 916   // Print some words near top of staack.
 917   int64_t* rsp = (int64_t*) regs[11];
 918   int64_t* dump_sp = rsp;
 919   for (int col1 = 0; col1 < 8; col1++) {
 920     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 921     os::print_location(tty, *dump_sp++);
 922   }
 923   for (int row = 0; row < 25; row++) {
 924     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 925     for (int col = 0; col < 4; col++) {
 926       tty->print(" 0x%016lx", *dump_sp++);
 927     }
 928     tty->cr();
 929   }
 930   // Print some instructions around pc:
 931   Disassembler::decode((address)pc-64, (address)pc);
 932   tty->print_cr("--------");
 933   Disassembler::decode((address)pc, (address)pc+32);
 934 }
 935 
 936 #endif // _LP64
 937 
 938 // Now versions that are common to 32/64 bit
 939 
 940 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 941   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 942 }
 943 
 944 void MacroAssembler::addptr(Register dst, Register src) {
 945   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 946 }
 947 
 948 void MacroAssembler::addptr(Address dst, Register src) {
 949   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 950 }
 951 
 952 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 953   if (reachable(src)) {
 954     Assembler::addsd(dst, as_Address(src));
 955   } else {
 956     lea(rscratch1, src);
 957     Assembler::addsd(dst, Address(rscratch1, 0));
 958   }
 959 }
 960 
 961 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 962   if (reachable(src)) {
 963     addss(dst, as_Address(src));
 964   } else {
 965     lea(rscratch1, src);
 966     addss(dst, Address(rscratch1, 0));
 967   }
 968 }
 969 
 970 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 971   if (reachable(src)) {
 972     Assembler::addpd(dst, as_Address(src));
 973   } else {
 974     lea(rscratch1, src);
 975     Assembler::addpd(dst, Address(rscratch1, 0));
 976   }
 977 }
 978 
 979 void MacroAssembler::align(int modulus) {
 980   align(modulus, offset());
 981 }
 982 
 983 void MacroAssembler::align(int modulus, int target) {
 984   if (target % modulus != 0) {
 985     nop(modulus - (target % modulus));
 986   }
 987 }
 988 
 989 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 990   // Used in sign-masking with aligned address.
 991   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 992   if (reachable(src)) {
 993     Assembler::andpd(dst, as_Address(src));
 994   } else {
 995     lea(rscratch1, src);
 996     Assembler::andpd(dst, Address(rscratch1, 0));
 997   }
 998 }
 999 
1000 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1001   // Used in sign-masking with aligned address.
1002   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1003   if (reachable(src)) {
1004     Assembler::andps(dst, as_Address(src));
1005   } else {
1006     lea(rscratch1, src);
1007     Assembler::andps(dst, Address(rscratch1, 0));
1008   }
1009 }
1010 
1011 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1012   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1013 }
1014 
1015 void MacroAssembler::atomic_incl(Address counter_addr) {
1016   if (os::is_MP())
1017     lock();
1018   incrementl(counter_addr);
1019 }
1020 
1021 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1022   if (reachable(counter_addr)) {
1023     atomic_incl(as_Address(counter_addr));
1024   } else {
1025     lea(scr, counter_addr);
1026     atomic_incl(Address(scr, 0));
1027   }
1028 }
1029 
1030 #ifdef _LP64
1031 void MacroAssembler::atomic_incq(Address counter_addr) {
1032   if (os::is_MP())
1033     lock();
1034   incrementq(counter_addr);
1035 }
1036 
1037 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1038   if (reachable(counter_addr)) {
1039     atomic_incq(as_Address(counter_addr));
1040   } else {
1041     lea(scr, counter_addr);
1042     atomic_incq(Address(scr, 0));
1043   }
1044 }
1045 #endif
1046 
1047 // Writes to stack successive pages until offset reached to check for
1048 // stack overflow + shadow pages.  This clobbers tmp.
1049 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1050   movptr(tmp, rsp);
1051   // Bang stack for total size given plus shadow page size.
1052   // Bang one page at a time because large size can bang beyond yellow and
1053   // red zones.
1054   Label loop;
1055   bind(loop);
1056   movl(Address(tmp, (-os::vm_page_size())), size );
1057   subptr(tmp, os::vm_page_size());
1058   subl(size, os::vm_page_size());
1059   jcc(Assembler::greater, loop);
1060 
1061   // Bang down shadow pages too.
1062   // At this point, (tmp-0) is the last address touched, so don't
1063   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1064   // was post-decremented.)  Skip this address by starting at i=1, and
1065   // touch a few more pages below.  N.B.  It is important to touch all
1066   // the way down including all pages in the shadow zone.
1067   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1068     // this could be any sized move but this is can be a debugging crumb
1069     // so the bigger the better.
1070     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1071   }
1072 }
1073 
1074 void MacroAssembler::reserved_stack_check() {
1075     // testing if reserved zone needs to be enabled
1076     Label no_reserved_zone_enabling;
1077     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1078     NOT_LP64(get_thread(rsi);)
1079 
1080     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1081     jcc(Assembler::below, no_reserved_zone_enabling);
1082 
1083     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1084     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1085     should_not_reach_here();
1086 
1087     bind(no_reserved_zone_enabling);
1088 }
1089 
1090 int MacroAssembler::biased_locking_enter(Register lock_reg,
1091                                          Register obj_reg,
1092                                          Register swap_reg,
1093                                          Register tmp_reg,
1094                                          bool swap_reg_contains_mark,
1095                                          Label& done,
1096                                          Label* slow_case,
1097                                          BiasedLockingCounters* counters) {
1098   assert(UseBiasedLocking, "why call this otherwise?");
1099   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1100   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1101   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1102   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1103   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1104   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1105 
1106   if (PrintBiasedLockingStatistics && counters == NULL) {
1107     counters = BiasedLocking::counters();
1108   }
1109   // Biased locking
1110   // See whether the lock is currently biased toward our thread and
1111   // whether the epoch is still valid
1112   // Note that the runtime guarantees sufficient alignment of JavaThread
1113   // pointers to allow age to be placed into low bits
1114   // First check to see whether biasing is even enabled for this object
1115   Label cas_label;
1116   int null_check_offset = -1;
1117   if (!swap_reg_contains_mark) {
1118     null_check_offset = offset();
1119     movptr(swap_reg, mark_addr);
1120   }
1121   movptr(tmp_reg, swap_reg);
1122   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1123   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1124   jcc(Assembler::notEqual, cas_label);
1125   // The bias pattern is present in the object's header. Need to check
1126   // whether the bias owner and the epoch are both still current.
1127 #ifndef _LP64
1128   // Note that because there is no current thread register on x86_32 we
1129   // need to store off the mark word we read out of the object to
1130   // avoid reloading it and needing to recheck invariants below. This
1131   // store is unfortunate but it makes the overall code shorter and
1132   // simpler.
1133   movptr(saved_mark_addr, swap_reg);
1134 #endif
1135   if (swap_reg_contains_mark) {
1136     null_check_offset = offset();
1137   }
1138   load_prototype_header(tmp_reg, obj_reg);
1139 #ifdef _LP64
1140   orptr(tmp_reg, r15_thread);
1141   xorptr(tmp_reg, swap_reg);
1142   Register header_reg = tmp_reg;
1143 #else
1144   xorptr(tmp_reg, swap_reg);
1145   get_thread(swap_reg);
1146   xorptr(swap_reg, tmp_reg);
1147   Register header_reg = swap_reg;
1148 #endif
1149   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1150   if (counters != NULL) {
1151     cond_inc32(Assembler::zero,
1152                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1153   }
1154   jcc(Assembler::equal, done);
1155 
1156   Label try_revoke_bias;
1157   Label try_rebias;
1158 
1159   // At this point we know that the header has the bias pattern and
1160   // that we are not the bias owner in the current epoch. We need to
1161   // figure out more details about the state of the header in order to
1162   // know what operations can be legally performed on the object's
1163   // header.
1164 
1165   // If the low three bits in the xor result aren't clear, that means
1166   // the prototype header is no longer biased and we have to revoke
1167   // the bias on this object.
1168   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1169   jccb(Assembler::notZero, try_revoke_bias);
1170 
1171   // Biasing is still enabled for this data type. See whether the
1172   // epoch of the current bias is still valid, meaning that the epoch
1173   // bits of the mark word are equal to the epoch bits of the
1174   // prototype header. (Note that the prototype header's epoch bits
1175   // only change at a safepoint.) If not, attempt to rebias the object
1176   // toward the current thread. Note that we must be absolutely sure
1177   // that the current epoch is invalid in order to do this because
1178   // otherwise the manipulations it performs on the mark word are
1179   // illegal.
1180   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1181   jccb(Assembler::notZero, try_rebias);
1182 
1183   // The epoch of the current bias is still valid but we know nothing
1184   // about the owner; it might be set or it might be clear. Try to
1185   // acquire the bias of the object using an atomic operation. If this
1186   // fails we will go in to the runtime to revoke the object's bias.
1187   // Note that we first construct the presumed unbiased header so we
1188   // don't accidentally blow away another thread's valid bias.
1189   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1190   andptr(swap_reg,
1191          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1192 #ifdef _LP64
1193   movptr(tmp_reg, swap_reg);
1194   orptr(tmp_reg, r15_thread);
1195 #else
1196   get_thread(tmp_reg);
1197   orptr(tmp_reg, swap_reg);
1198 #endif
1199   if (os::is_MP()) {
1200     lock();
1201   }
1202   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1203   // If the biasing toward our thread failed, this means that
1204   // another thread succeeded in biasing it toward itself and we
1205   // need to revoke that bias. The revocation will occur in the
1206   // interpreter runtime in the slow case.
1207   if (counters != NULL) {
1208     cond_inc32(Assembler::zero,
1209                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1210   }
1211   if (slow_case != NULL) {
1212     jcc(Assembler::notZero, *slow_case);
1213   }
1214   jmp(done);
1215 
1216   bind(try_rebias);
1217   // At this point we know the epoch has expired, meaning that the
1218   // current "bias owner", if any, is actually invalid. Under these
1219   // circumstances _only_, we are allowed to use the current header's
1220   // value as the comparison value when doing the cas to acquire the
1221   // bias in the current epoch. In other words, we allow transfer of
1222   // the bias from one thread to another directly in this situation.
1223   //
1224   // FIXME: due to a lack of registers we currently blow away the age
1225   // bits in this situation. Should attempt to preserve them.
1226   load_prototype_header(tmp_reg, obj_reg);
1227 #ifdef _LP64
1228   orptr(tmp_reg, r15_thread);
1229 #else
1230   get_thread(swap_reg);
1231   orptr(tmp_reg, swap_reg);
1232   movptr(swap_reg, saved_mark_addr);
1233 #endif
1234   if (os::is_MP()) {
1235     lock();
1236   }
1237   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1238   // If the biasing toward our thread failed, then another thread
1239   // succeeded in biasing it toward itself and we need to revoke that
1240   // bias. The revocation will occur in the runtime in the slow case.
1241   if (counters != NULL) {
1242     cond_inc32(Assembler::zero,
1243                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1244   }
1245   if (slow_case != NULL) {
1246     jcc(Assembler::notZero, *slow_case);
1247   }
1248   jmp(done);
1249 
1250   bind(try_revoke_bias);
1251   // The prototype mark in the klass doesn't have the bias bit set any
1252   // more, indicating that objects of this data type are not supposed
1253   // to be biased any more. We are going to try to reset the mark of
1254   // this object to the prototype value and fall through to the
1255   // CAS-based locking scheme. Note that if our CAS fails, it means
1256   // that another thread raced us for the privilege of revoking the
1257   // bias of this particular object, so it's okay to continue in the
1258   // normal locking code.
1259   //
1260   // FIXME: due to a lack of registers we currently blow away the age
1261   // bits in this situation. Should attempt to preserve them.
1262   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1263   load_prototype_header(tmp_reg, obj_reg);
1264   if (os::is_MP()) {
1265     lock();
1266   }
1267   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1268   // Fall through to the normal CAS-based lock, because no matter what
1269   // the result of the above CAS, some thread must have succeeded in
1270   // removing the bias bit from the object's header.
1271   if (counters != NULL) {
1272     cond_inc32(Assembler::zero,
1273                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1274   }
1275 
1276   bind(cas_label);
1277 
1278   return null_check_offset;
1279 }
1280 
1281 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1282   assert(UseBiasedLocking, "why call this otherwise?");
1283 
1284   // Check for biased locking unlock case, which is a no-op
1285   // Note: we do not have to check the thread ID for two reasons.
1286   // First, the interpreter checks for IllegalMonitorStateException at
1287   // a higher level. Second, if the bias was revoked while we held the
1288   // lock, the object could not be rebiased toward another thread, so
1289   // the bias bit would be clear.
1290   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1291   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1292   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1293   jcc(Assembler::equal, done);
1294 }
1295 
1296 #ifdef COMPILER2
1297 
1298 #if INCLUDE_RTM_OPT
1299 
1300 // Update rtm_counters based on abort status
1301 // input: abort_status
1302 //        rtm_counters (RTMLockingCounters*)
1303 // flags are killed
1304 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1305 
1306   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1307   if (PrintPreciseRTMLockingStatistics) {
1308     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1309       Label check_abort;
1310       testl(abort_status, (1<<i));
1311       jccb(Assembler::equal, check_abort);
1312       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1313       bind(check_abort);
1314     }
1315   }
1316 }
1317 
1318 // Branch if (random & (count-1) != 0), count is 2^n
1319 // tmp, scr and flags are killed
1320 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1321   assert(tmp == rax, "");
1322   assert(scr == rdx, "");
1323   rdtsc(); // modifies EDX:EAX
1324   andptr(tmp, count-1);
1325   jccb(Assembler::notZero, brLabel);
1326 }
1327 
1328 // Perform abort ratio calculation, set no_rtm bit if high ratio
1329 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1330 // tmpReg, rtm_counters_Reg and flags are killed
1331 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1332                                                  Register rtm_counters_Reg,
1333                                                  RTMLockingCounters* rtm_counters,
1334                                                  Metadata* method_data) {
1335   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1336 
1337   if (RTMLockingCalculationDelay > 0) {
1338     // Delay calculation
1339     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1340     testptr(tmpReg, tmpReg);
1341     jccb(Assembler::equal, L_done);
1342   }
1343   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1344   //   Aborted transactions = abort_count * 100
1345   //   All transactions = total_count *  RTMTotalCountIncrRate
1346   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1347 
1348   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1349   cmpptr(tmpReg, RTMAbortThreshold);
1350   jccb(Assembler::below, L_check_always_rtm2);
1351   imulptr(tmpReg, tmpReg, 100);
1352 
1353   Register scrReg = rtm_counters_Reg;
1354   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1355   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1356   imulptr(scrReg, scrReg, RTMAbortRatio);
1357   cmpptr(tmpReg, scrReg);
1358   jccb(Assembler::below, L_check_always_rtm1);
1359   if (method_data != NULL) {
1360     // set rtm_state to "no rtm" in MDO
1361     mov_metadata(tmpReg, method_data);
1362     if (os::is_MP()) {
1363       lock();
1364     }
1365     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1366   }
1367   jmpb(L_done);
1368   bind(L_check_always_rtm1);
1369   // Reload RTMLockingCounters* address
1370   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1371   bind(L_check_always_rtm2);
1372   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1373   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1374   jccb(Assembler::below, L_done);
1375   if (method_data != NULL) {
1376     // set rtm_state to "always rtm" in MDO
1377     mov_metadata(tmpReg, method_data);
1378     if (os::is_MP()) {
1379       lock();
1380     }
1381     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1382   }
1383   bind(L_done);
1384 }
1385 
1386 // Update counters and perform abort ratio calculation
1387 // input:  abort_status_Reg
1388 // rtm_counters_Reg, flags are killed
1389 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1390                                    Register rtm_counters_Reg,
1391                                    RTMLockingCounters* rtm_counters,
1392                                    Metadata* method_data,
1393                                    bool profile_rtm) {
1394 
1395   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1396   // update rtm counters based on rax value at abort
1397   // reads abort_status_Reg, updates flags
1398   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1399   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1400   if (profile_rtm) {
1401     // Save abort status because abort_status_Reg is used by following code.
1402     if (RTMRetryCount > 0) {
1403       push(abort_status_Reg);
1404     }
1405     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1406     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1407     // restore abort status
1408     if (RTMRetryCount > 0) {
1409       pop(abort_status_Reg);
1410     }
1411   }
1412 }
1413 
1414 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1415 // inputs: retry_count_Reg
1416 //       : abort_status_Reg
1417 // output: retry_count_Reg decremented by 1
1418 // flags are killed
1419 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1420   Label doneRetry;
1421   assert(abort_status_Reg == rax, "");
1422   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1423   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1424   // if reason is in 0x6 and retry count != 0 then retry
1425   andptr(abort_status_Reg, 0x6);
1426   jccb(Assembler::zero, doneRetry);
1427   testl(retry_count_Reg, retry_count_Reg);
1428   jccb(Assembler::zero, doneRetry);
1429   pause();
1430   decrementl(retry_count_Reg);
1431   jmp(retryLabel);
1432   bind(doneRetry);
1433 }
1434 
1435 // Spin and retry if lock is busy,
1436 // inputs: box_Reg (monitor address)
1437 //       : retry_count_Reg
1438 // output: retry_count_Reg decremented by 1
1439 //       : clear z flag if retry count exceeded
1440 // tmp_Reg, scr_Reg, flags are killed
1441 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1442                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1443   Label SpinLoop, SpinExit, doneRetry;
1444   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1445 
1446   testl(retry_count_Reg, retry_count_Reg);
1447   jccb(Assembler::zero, doneRetry);
1448   decrementl(retry_count_Reg);
1449   movptr(scr_Reg, RTMSpinLoopCount);
1450 
1451   bind(SpinLoop);
1452   pause();
1453   decrementl(scr_Reg);
1454   jccb(Assembler::lessEqual, SpinExit);
1455   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1456   testptr(tmp_Reg, tmp_Reg);
1457   jccb(Assembler::notZero, SpinLoop);
1458 
1459   bind(SpinExit);
1460   jmp(retryLabel);
1461   bind(doneRetry);
1462   incrementl(retry_count_Reg); // clear z flag
1463 }
1464 
1465 // Use RTM for normal stack locks
1466 // Input: objReg (object to lock)
1467 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1468                                        Register retry_on_abort_count_Reg,
1469                                        RTMLockingCounters* stack_rtm_counters,
1470                                        Metadata* method_data, bool profile_rtm,
1471                                        Label& DONE_LABEL, Label& IsInflated) {
1472   assert(UseRTMForStackLocks, "why call this otherwise?");
1473   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1474   assert(tmpReg == rax, "");
1475   assert(scrReg == rdx, "");
1476   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1477 
1478   if (RTMRetryCount > 0) {
1479     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1480     bind(L_rtm_retry);
1481   }
1482   movptr(tmpReg, Address(objReg, 0));
1483   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1484   jcc(Assembler::notZero, IsInflated);
1485 
1486   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1487     Label L_noincrement;
1488     if (RTMTotalCountIncrRate > 1) {
1489       // tmpReg, scrReg and flags are killed
1490       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1491     }
1492     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1493     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1494     bind(L_noincrement);
1495   }
1496   xbegin(L_on_abort);
1497   movptr(tmpReg, Address(objReg, 0));       // fetch markword
1498   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1499   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1500   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1501 
1502   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1503   if (UseRTMXendForLockBusy) {
1504     xend();
1505     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1506     jmp(L_decrement_retry);
1507   }
1508   else {
1509     xabort(0);
1510   }
1511   bind(L_on_abort);
1512   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1513     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1514   }
1515   bind(L_decrement_retry);
1516   if (RTMRetryCount > 0) {
1517     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1518     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1519   }
1520 }
1521 
1522 // Use RTM for inflating locks
1523 // inputs: objReg (object to lock)
1524 //         boxReg (on-stack box address (displaced header location) - KILLED)
1525 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1526 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1527                                           Register scrReg, Register retry_on_busy_count_Reg,
1528                                           Register retry_on_abort_count_Reg,
1529                                           RTMLockingCounters* rtm_counters,
1530                                           Metadata* method_data, bool profile_rtm,
1531                                           Label& DONE_LABEL) {
1532   assert(UseRTMLocking, "why call this otherwise?");
1533   assert(tmpReg == rax, "");
1534   assert(scrReg == rdx, "");
1535   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1536   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1537 
1538   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1539   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1540   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1541 
1542   if (RTMRetryCount > 0) {
1543     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1544     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1545     bind(L_rtm_retry);
1546   }
1547   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1548     Label L_noincrement;
1549     if (RTMTotalCountIncrRate > 1) {
1550       // tmpReg, scrReg and flags are killed
1551       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1552     }
1553     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1554     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1555     bind(L_noincrement);
1556   }
1557   xbegin(L_on_abort);
1558   movptr(tmpReg, Address(objReg, 0));
1559   movptr(tmpReg, Address(tmpReg, owner_offset));
1560   testptr(tmpReg, tmpReg);
1561   jcc(Assembler::zero, DONE_LABEL);
1562   if (UseRTMXendForLockBusy) {
1563     xend();
1564     jmp(L_decrement_retry);
1565   }
1566   else {
1567     xabort(0);
1568   }
1569   bind(L_on_abort);
1570   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1571   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1572     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1573   }
1574   if (RTMRetryCount > 0) {
1575     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1576     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1577   }
1578 
1579   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1580   testptr(tmpReg, tmpReg) ;
1581   jccb(Assembler::notZero, L_decrement_retry) ;
1582 
1583   // Appears unlocked - try to swing _owner from null to non-null.
1584   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1585 #ifdef _LP64
1586   Register threadReg = r15_thread;
1587 #else
1588   get_thread(scrReg);
1589   Register threadReg = scrReg;
1590 #endif
1591   if (os::is_MP()) {
1592     lock();
1593   }
1594   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1595 
1596   if (RTMRetryCount > 0) {
1597     // success done else retry
1598     jccb(Assembler::equal, DONE_LABEL) ;
1599     bind(L_decrement_retry);
1600     // Spin and retry if lock is busy.
1601     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1602   }
1603   else {
1604     bind(L_decrement_retry);
1605   }
1606 }
1607 
1608 #endif //  INCLUDE_RTM_OPT
1609 
1610 // Fast_Lock and Fast_Unlock used by C2
1611 
1612 // Because the transitions from emitted code to the runtime
1613 // monitorenter/exit helper stubs are so slow it's critical that
1614 // we inline both the stack-locking fast-path and the inflated fast path.
1615 //
1616 // See also: cmpFastLock and cmpFastUnlock.
1617 //
1618 // What follows is a specialized inline transliteration of the code
1619 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1620 // another option would be to emit TrySlowEnter and TrySlowExit methods
1621 // at startup-time.  These methods would accept arguments as
1622 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1623 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1624 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1625 // In practice, however, the # of lock sites is bounded and is usually small.
1626 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1627 // if the processor uses simple bimodal branch predictors keyed by EIP
1628 // Since the helper routines would be called from multiple synchronization
1629 // sites.
1630 //
1631 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1632 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1633 // to those specialized methods.  That'd give us a mostly platform-independent
1634 // implementation that the JITs could optimize and inline at their pleasure.
1635 // Done correctly, the only time we'd need to cross to native could would be
1636 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1637 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1638 // (b) explicit barriers or fence operations.
1639 //
1640 // TODO:
1641 //
1642 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1643 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1644 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1645 //    the lock operators would typically be faster than reifying Self.
1646 //
1647 // *  Ideally I'd define the primitives as:
1648 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1649 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1650 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1651 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1652 //    Furthermore the register assignments are overconstrained, possibly resulting in
1653 //    sub-optimal code near the synchronization site.
1654 //
1655 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1656 //    Alternately, use a better sp-proximity test.
1657 //
1658 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1659 //    Either one is sufficient to uniquely identify a thread.
1660 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1661 //
1662 // *  Intrinsify notify() and notifyAll() for the common cases where the
1663 //    object is locked by the calling thread but the waitlist is empty.
1664 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1665 //
1666 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1667 //    But beware of excessive branch density on AMD Opterons.
1668 //
1669 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1670 //    or failure of the fast-path.  If the fast-path fails then we pass
1671 //    control to the slow-path, typically in C.  In Fast_Lock and
1672 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1673 //    will emit a conditional branch immediately after the node.
1674 //    So we have branches to branches and lots of ICC.ZF games.
1675 //    Instead, it might be better to have C2 pass a "FailureLabel"
1676 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1677 //    will drop through the node.  ICC.ZF is undefined at exit.
1678 //    In the case of failure, the node will branch directly to the
1679 //    FailureLabel
1680 
1681 
1682 // obj: object to lock
1683 // box: on-stack box address (displaced header location) - KILLED
1684 // rax,: tmp -- KILLED
1685 // scr: tmp -- KILLED
1686 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1687                                Register scrReg, Register cx1Reg, Register cx2Reg,
1688                                BiasedLockingCounters* counters,
1689                                RTMLockingCounters* rtm_counters,
1690                                RTMLockingCounters* stack_rtm_counters,
1691                                Metadata* method_data,
1692                                bool use_rtm, bool profile_rtm) {
1693   // Ensure the register assignments are disjoint
1694   assert(tmpReg == rax, "");
1695 
1696   if (use_rtm) {
1697     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1698   } else {
1699     assert(cx1Reg == noreg, "");
1700     assert(cx2Reg == noreg, "");
1701     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1702   }
1703 
1704   if (counters != NULL) {
1705     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1706   }
1707   if (EmitSync & 1) {
1708       // set box->dhw = markOopDesc::unused_mark()
1709       // Force all sync thru slow-path: slow_enter() and slow_exit()
1710       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1711       cmpptr (rsp, (int32_t)NULL_WORD);
1712   } else {
1713     // Possible cases that we'll encounter in fast_lock
1714     // ------------------------------------------------
1715     // * Inflated
1716     //    -- unlocked
1717     //    -- Locked
1718     //       = by self
1719     //       = by other
1720     // * biased
1721     //    -- by Self
1722     //    -- by other
1723     // * neutral
1724     // * stack-locked
1725     //    -- by self
1726     //       = sp-proximity test hits
1727     //       = sp-proximity test generates false-negative
1728     //    -- by other
1729     //
1730 
1731     Label IsInflated, DONE_LABEL;
1732 
1733     // it's stack-locked, biased or neutral
1734     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1735     // order to reduce the number of conditional branches in the most common cases.
1736     // Beware -- there's a subtle invariant that fetch of the markword
1737     // at [FETCH], below, will never observe a biased encoding (*101b).
1738     // If this invariant is not held we risk exclusion (safety) failure.
1739     if (UseBiasedLocking && !UseOptoBiasInlining) {
1740       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1741     }
1742 
1743 #if INCLUDE_RTM_OPT
1744     if (UseRTMForStackLocks && use_rtm) {
1745       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1746                         stack_rtm_counters, method_data, profile_rtm,
1747                         DONE_LABEL, IsInflated);
1748     }
1749 #endif // INCLUDE_RTM_OPT
1750 
1751     movptr(tmpReg, Address(objReg, 0));          // [FETCH]
1752     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1753     jccb(Assembler::notZero, IsInflated);
1754 
1755     // Attempt stack-locking ...
1756     orptr (tmpReg, markOopDesc::unlocked_value);
1757     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1758     if (os::is_MP()) {
1759       lock();
1760     }
1761     cmpxchgptr(boxReg, Address(objReg, 0));      // Updates tmpReg
1762     if (counters != NULL) {
1763       cond_inc32(Assembler::equal,
1764                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1765     }
1766     jcc(Assembler::equal, DONE_LABEL);           // Success
1767 
1768     // Recursive locking.
1769     // The object is stack-locked: markword contains stack pointer to BasicLock.
1770     // Locked by current thread if difference with current SP is less than one page.
1771     subptr(tmpReg, rsp);
1772     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1773     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1774     movptr(Address(boxReg, 0), tmpReg);
1775     if (counters != NULL) {
1776       cond_inc32(Assembler::equal,
1777                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1778     }
1779     jmp(DONE_LABEL);
1780 
1781     bind(IsInflated);
1782     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1783 
1784 #if INCLUDE_RTM_OPT
1785     // Use the same RTM locking code in 32- and 64-bit VM.
1786     if (use_rtm) {
1787       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1788                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1789     } else {
1790 #endif // INCLUDE_RTM_OPT
1791 
1792 #ifndef _LP64
1793     // The object is inflated.
1794 
1795     // boxReg refers to the on-stack BasicLock in the current frame.
1796     // We'd like to write:
1797     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1798     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1799     // additional latency as we have another ST in the store buffer that must drain.
1800 
1801     if (EmitSync & 8192) {
1802        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1803        get_thread (scrReg);
1804        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1805        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1806        if (os::is_MP()) {
1807          lock();
1808        }
1809        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1810     } else
1811     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1812        // register juggle because we need tmpReg for cmpxchgptr below
1813        movptr(scrReg, boxReg);
1814        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1815 
1816        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1817        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1818           // prefetchw [eax + Offset(_owner)-2]
1819           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1820        }
1821 
1822        if ((EmitSync & 64) == 0) {
1823          // Optimistic form: consider XORL tmpReg,tmpReg
1824          movptr(tmpReg, NULL_WORD);
1825        } else {
1826          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1827          // Test-And-CAS instead of CAS
1828          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1829          testptr(tmpReg, tmpReg);                   // Locked ?
1830          jccb  (Assembler::notZero, DONE_LABEL);
1831        }
1832 
1833        // Appears unlocked - try to swing _owner from null to non-null.
1834        // Ideally, I'd manifest "Self" with get_thread and then attempt
1835        // to CAS the register containing Self into m->Owner.
1836        // But we don't have enough registers, so instead we can either try to CAS
1837        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1838        // we later store "Self" into m->Owner.  Transiently storing a stack address
1839        // (rsp or the address of the box) into  m->owner is harmless.
1840        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1841        if (os::is_MP()) {
1842          lock();
1843        }
1844        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1845        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1846        // If we weren't able to swing _owner from NULL to the BasicLock
1847        // then take the slow path.
1848        jccb  (Assembler::notZero, DONE_LABEL);
1849        // update _owner from BasicLock to thread
1850        get_thread (scrReg);                    // beware: clobbers ICCs
1851        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1852        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1853 
1854        // If the CAS fails we can either retry or pass control to the slow-path.
1855        // We use the latter tactic.
1856        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1857        // If the CAS was successful ...
1858        //   Self has acquired the lock
1859        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1860        // Intentional fall-through into DONE_LABEL ...
1861     } else {
1862        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1863        movptr(boxReg, tmpReg);
1864 
1865        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1866        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1867           // prefetchw [eax + Offset(_owner)-2]
1868           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1869        }
1870 
1871        if ((EmitSync & 64) == 0) {
1872          // Optimistic form
1873          xorptr  (tmpReg, tmpReg);
1874        } else {
1875          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1876          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1877          testptr(tmpReg, tmpReg);                   // Locked ?
1878          jccb  (Assembler::notZero, DONE_LABEL);
1879        }
1880 
1881        // Appears unlocked - try to swing _owner from null to non-null.
1882        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1883        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1884        get_thread (scrReg);
1885        if (os::is_MP()) {
1886          lock();
1887        }
1888        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1889 
1890        // If the CAS fails we can either retry or pass control to the slow-path.
1891        // We use the latter tactic.
1892        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1893        // If the CAS was successful ...
1894        //   Self has acquired the lock
1895        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1896        // Intentional fall-through into DONE_LABEL ...
1897     }
1898 #else // _LP64
1899     // It's inflated
1900     movq(scrReg, tmpReg);
1901     xorq(tmpReg, tmpReg);
1902 
1903     if (os::is_MP()) {
1904       lock();
1905     }
1906     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1907     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1908     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1909     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1910     // Intentional fall-through into DONE_LABEL ...
1911     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1912 #endif // _LP64
1913 #if INCLUDE_RTM_OPT
1914     } // use_rtm()
1915 #endif
1916     // DONE_LABEL is a hot target - we'd really like to place it at the
1917     // start of cache line by padding with NOPs.
1918     // See the AMD and Intel software optimization manuals for the
1919     // most efficient "long" NOP encodings.
1920     // Unfortunately none of our alignment mechanisms suffice.
1921     bind(DONE_LABEL);
1922 
1923     // At DONE_LABEL the icc ZFlag is set as follows ...
1924     // Fast_Unlock uses the same protocol.
1925     // ZFlag == 1 -> Success
1926     // ZFlag == 0 -> Failure - force control through the slow-path
1927   }
1928 }
1929 
1930 // obj: object to unlock
1931 // box: box address (displaced header location), killed.  Must be EAX.
1932 // tmp: killed, cannot be obj nor box.
1933 //
1934 // Some commentary on balanced locking:
1935 //
1936 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1937 // Methods that don't have provably balanced locking are forced to run in the
1938 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1939 // The interpreter provides two properties:
1940 // I1:  At return-time the interpreter automatically and quietly unlocks any
1941 //      objects acquired the current activation (frame).  Recall that the
1942 //      interpreter maintains an on-stack list of locks currently held by
1943 //      a frame.
1944 // I2:  If a method attempts to unlock an object that is not held by the
1945 //      the frame the interpreter throws IMSX.
1946 //
1947 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1948 // B() doesn't have provably balanced locking so it runs in the interpreter.
1949 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1950 // is still locked by A().
1951 //
1952 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1953 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1954 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1955 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1956 // Arguably given that the spec legislates the JNI case as undefined our implementation
1957 // could reasonably *avoid* checking owner in Fast_Unlock().
1958 // In the interest of performance we elide m->Owner==Self check in unlock.
1959 // A perfectly viable alternative is to elide the owner check except when
1960 // Xcheck:jni is enabled.
1961 
1962 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1963   assert(boxReg == rax, "");
1964   assert_different_registers(objReg, boxReg, tmpReg);
1965 
1966   if (EmitSync & 4) {
1967     // Disable - inhibit all inlining.  Force control through the slow-path
1968     cmpptr (rsp, 0);
1969   } else {
1970     Label DONE_LABEL, Stacked, CheckSucc;
1971 
1972     // Critically, the biased locking test must have precedence over
1973     // and appear before the (box->dhw == 0) recursive stack-lock test.
1974     if (UseBiasedLocking && !UseOptoBiasInlining) {
1975        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1976     }
1977 
1978 #if INCLUDE_RTM_OPT
1979     if (UseRTMForStackLocks && use_rtm) {
1980       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1981       Label L_regular_unlock;
1982       movptr(tmpReg, Address(objReg, 0));           // fetch markword
1983       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1984       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1985       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1986       xend();                                       // otherwise end...
1987       jmp(DONE_LABEL);                              // ... and we're done
1988       bind(L_regular_unlock);
1989     }
1990 #endif
1991 
1992     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
1993     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
1994     movptr(tmpReg, Address(objReg, 0));             // Examine the object's markword
1995     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
1996     jccb  (Assembler::zero, Stacked);
1997 
1998     // It's inflated.
1999 #if INCLUDE_RTM_OPT
2000     if (use_rtm) {
2001       Label L_regular_inflated_unlock;
2002       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2003       movptr(boxReg, Address(tmpReg, owner_offset));
2004       testptr(boxReg, boxReg);
2005       jccb(Assembler::notZero, L_regular_inflated_unlock);
2006       xend();
2007       jmpb(DONE_LABEL);
2008       bind(L_regular_inflated_unlock);
2009     }
2010 #endif
2011 
2012     // Despite our balanced locking property we still check that m->_owner == Self
2013     // as java routines or native JNI code called by this thread might
2014     // have released the lock.
2015     // Refer to the comments in synchronizer.cpp for how we might encode extra
2016     // state in _succ so we can avoid fetching EntryList|cxq.
2017     //
2018     // I'd like to add more cases in fast_lock() and fast_unlock() --
2019     // such as recursive enter and exit -- but we have to be wary of
2020     // I$ bloat, T$ effects and BP$ effects.
2021     //
2022     // If there's no contention try a 1-0 exit.  That is, exit without
2023     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2024     // we detect and recover from the race that the 1-0 exit admits.
2025     //
2026     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2027     // before it STs null into _owner, releasing the lock.  Updates
2028     // to data protected by the critical section must be visible before
2029     // we drop the lock (and thus before any other thread could acquire
2030     // the lock and observe the fields protected by the lock).
2031     // IA32's memory-model is SPO, so STs are ordered with respect to
2032     // each other and there's no need for an explicit barrier (fence).
2033     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2034 #ifndef _LP64
2035     get_thread (boxReg);
2036     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2037       // prefetchw [ebx + Offset(_owner)-2]
2038       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2039     }
2040 
2041     // Note that we could employ various encoding schemes to reduce
2042     // the number of loads below (currently 4) to just 2 or 3.
2043     // Refer to the comments in synchronizer.cpp.
2044     // In practice the chain of fetches doesn't seem to impact performance, however.
2045     xorptr(boxReg, boxReg);
2046     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2047        // Attempt to reduce branch density - AMD's branch predictor.
2048        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2049        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2050        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2051        jccb  (Assembler::notZero, DONE_LABEL);
2052        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2053        jmpb  (DONE_LABEL);
2054     } else {
2055        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2056        jccb  (Assembler::notZero, DONE_LABEL);
2057        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2058        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2059        jccb  (Assembler::notZero, CheckSucc);
2060        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2061        jmpb  (DONE_LABEL);
2062     }
2063 
2064     // The Following code fragment (EmitSync & 65536) improves the performance of
2065     // contended applications and contended synchronization microbenchmarks.
2066     // Unfortunately the emission of the code - even though not executed - causes regressions
2067     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2068     // with an equal number of never-executed NOPs results in the same regression.
2069     // We leave it off by default.
2070 
2071     if ((EmitSync & 65536) != 0) {
2072        Label LSuccess, LGoSlowPath ;
2073 
2074        bind  (CheckSucc);
2075 
2076        // Optional pre-test ... it's safe to elide this
2077        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2078        jccb(Assembler::zero, LGoSlowPath);
2079 
2080        // We have a classic Dekker-style idiom:
2081        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2082        // There are a number of ways to implement the barrier:
2083        // (1) lock:andl &m->_owner, 0
2084        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2085        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2086        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2087        // (2) If supported, an explicit MFENCE is appealing.
2088        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2089        //     particularly if the write-buffer is full as might be the case if
2090        //     if stores closely precede the fence or fence-equivalent instruction.
2091        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2092        //     as the situation has changed with Nehalem and Shanghai.
2093        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2094        //     The $lines underlying the top-of-stack should be in M-state.
2095        //     The locked add instruction is serializing, of course.
2096        // (4) Use xchg, which is serializing
2097        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2098        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2099        //     The integer condition codes will tell us if succ was 0.
2100        //     Since _succ and _owner should reside in the same $line and
2101        //     we just stored into _owner, it's likely that the $line
2102        //     remains in M-state for the lock:orl.
2103        //
2104        // We currently use (3), although it's likely that switching to (2)
2105        // is correct for the future.
2106 
2107        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2108        if (os::is_MP()) {
2109          lock(); addptr(Address(rsp, 0), 0);
2110        }
2111        // Ratify _succ remains non-null
2112        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2113        jccb  (Assembler::notZero, LSuccess);
2114 
2115        xorptr(boxReg, boxReg);                  // box is really EAX
2116        if (os::is_MP()) { lock(); }
2117        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2118        // There's no successor so we tried to regrab the lock with the
2119        // placeholder value. If that didn't work, then another thread
2120        // grabbed the lock so we're done (and exit was a success).
2121        jccb  (Assembler::notEqual, LSuccess);
2122        // Since we're low on registers we installed rsp as a placeholding in _owner.
2123        // Now install Self over rsp.  This is safe as we're transitioning from
2124        // non-null to non=null
2125        get_thread (boxReg);
2126        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2127        // Intentional fall-through into LGoSlowPath ...
2128 
2129        bind  (LGoSlowPath);
2130        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2131        jmpb  (DONE_LABEL);
2132 
2133        bind  (LSuccess);
2134        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2135        jmpb  (DONE_LABEL);
2136     }
2137 
2138     bind (Stacked);
2139     // It's not inflated and it's not recursively stack-locked and it's not biased.
2140     // It must be stack-locked.
2141     // Try to reset the header to displaced header.
2142     // The "box" value on the stack is stable, so we can reload
2143     // and be assured we observe the same value as above.
2144     movptr(tmpReg, Address(boxReg, 0));
2145     if (os::is_MP()) {
2146       lock();
2147     }
2148     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2149     // Intention fall-thru into DONE_LABEL
2150 
2151     // DONE_LABEL is a hot target - we'd really like to place it at the
2152     // start of cache line by padding with NOPs.
2153     // See the AMD and Intel software optimization manuals for the
2154     // most efficient "long" NOP encodings.
2155     // Unfortunately none of our alignment mechanisms suffice.
2156     if ((EmitSync & 65536) == 0) {
2157        bind (CheckSucc);
2158     }
2159 #else // _LP64
2160     // It's inflated
2161     if (EmitSync & 1024) {
2162       // Emit code to check that _owner == Self
2163       // We could fold the _owner test into subsequent code more efficiently
2164       // than using a stand-alone check, but since _owner checking is off by
2165       // default we don't bother. We also might consider predicating the
2166       // _owner==Self check on Xcheck:jni or running on a debug build.
2167       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2168       xorptr(boxReg, r15_thread);
2169     } else {
2170       xorptr(boxReg, boxReg);
2171     }
2172     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2173     jccb  (Assembler::notZero, DONE_LABEL);
2174     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2175     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2176     jccb  (Assembler::notZero, CheckSucc);
2177     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2178     jmpb  (DONE_LABEL);
2179 
2180     if ((EmitSync & 65536) == 0) {
2181       // Try to avoid passing control into the slow_path ...
2182       Label LSuccess, LGoSlowPath ;
2183       bind  (CheckSucc);
2184 
2185       // The following optional optimization can be elided if necessary
2186       // Effectively: if (succ == null) goto SlowPath
2187       // The code reduces the window for a race, however,
2188       // and thus benefits performance.
2189       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2190       jccb  (Assembler::zero, LGoSlowPath);
2191 
2192       xorptr(boxReg, boxReg);
2193       if ((EmitSync & 16) && os::is_MP()) {
2194         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2195       } else {
2196         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2197         if (os::is_MP()) {
2198           // Memory barrier/fence
2199           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2200           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2201           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2202           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2203           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2204           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2205           lock(); addl(Address(rsp, 0), 0);
2206         }
2207       }
2208       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2209       jccb  (Assembler::notZero, LSuccess);
2210 
2211       // Rare inopportune interleaving - race.
2212       // The successor vanished in the small window above.
2213       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2214       // We need to ensure progress and succession.
2215       // Try to reacquire the lock.
2216       // If that fails then the new owner is responsible for succession and this
2217       // thread needs to take no further action and can exit via the fast path (success).
2218       // If the re-acquire succeeds then pass control into the slow path.
2219       // As implemented, this latter mode is horrible because we generated more
2220       // coherence traffic on the lock *and* artifically extended the critical section
2221       // length while by virtue of passing control into the slow path.
2222 
2223       // box is really RAX -- the following CMPXCHG depends on that binding
2224       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2225       if (os::is_MP()) { lock(); }
2226       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2227       // There's no successor so we tried to regrab the lock.
2228       // If that didn't work, then another thread grabbed the
2229       // lock so we're done (and exit was a success).
2230       jccb  (Assembler::notEqual, LSuccess);
2231       // Intentional fall-through into slow-path
2232 
2233       bind  (LGoSlowPath);
2234       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2235       jmpb  (DONE_LABEL);
2236 
2237       bind  (LSuccess);
2238       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2239       jmpb  (DONE_LABEL);
2240     }
2241 
2242     bind  (Stacked);
2243     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2244     if (os::is_MP()) { lock(); }
2245     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2246 
2247     if (EmitSync & 65536) {
2248        bind (CheckSucc);
2249     }
2250 #endif
2251     bind(DONE_LABEL);
2252   }
2253 }
2254 #endif // COMPILER2
2255 
2256 void MacroAssembler::c2bool(Register x) {
2257   // implements x == 0 ? 0 : 1
2258   // note: must only look at least-significant byte of x
2259   //       since C-style booleans are stored in one byte
2260   //       only! (was bug)
2261   andl(x, 0xFF);
2262   setb(Assembler::notZero, x);
2263 }
2264 
2265 // Wouldn't need if AddressLiteral version had new name
2266 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2267   Assembler::call(L, rtype);
2268 }
2269 
2270 void MacroAssembler::call(Register entry) {
2271   Assembler::call(entry);
2272 }
2273 
2274 void MacroAssembler::call(AddressLiteral entry) {
2275   if (reachable(entry)) {
2276     Assembler::call_literal(entry.target(), entry.rspec());
2277   } else {
2278     lea(rscratch1, entry);
2279     Assembler::call(rscratch1);
2280   }
2281 }
2282 
2283 void MacroAssembler::ic_call(address entry, jint method_index) {
2284   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2285   movptr(rax, (intptr_t)Universe::non_oop_word());
2286   call(AddressLiteral(entry, rh));
2287 }
2288 
2289 // Implementation of call_VM versions
2290 
2291 void MacroAssembler::call_VM(Register oop_result,
2292                              address entry_point,
2293                              bool check_exceptions) {
2294   Label C, E;
2295   call(C, relocInfo::none);
2296   jmp(E);
2297 
2298   bind(C);
2299   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2300   ret(0);
2301 
2302   bind(E);
2303 }
2304 
2305 void MacroAssembler::call_VM(Register oop_result,
2306                              address entry_point,
2307                              Register arg_1,
2308                              bool check_exceptions) {
2309   Label C, E;
2310   call(C, relocInfo::none);
2311   jmp(E);
2312 
2313   bind(C);
2314   pass_arg1(this, arg_1);
2315   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2316   ret(0);
2317 
2318   bind(E);
2319 }
2320 
2321 void MacroAssembler::call_VM(Register oop_result,
2322                              address entry_point,
2323                              Register arg_1,
2324                              Register arg_2,
2325                              bool check_exceptions) {
2326   Label C, E;
2327   call(C, relocInfo::none);
2328   jmp(E);
2329 
2330   bind(C);
2331 
2332   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2333 
2334   pass_arg2(this, arg_2);
2335   pass_arg1(this, arg_1);
2336   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2337   ret(0);
2338 
2339   bind(E);
2340 }
2341 
2342 void MacroAssembler::call_VM(Register oop_result,
2343                              address entry_point,
2344                              Register arg_1,
2345                              Register arg_2,
2346                              Register arg_3,
2347                              bool check_exceptions) {
2348   Label C, E;
2349   call(C, relocInfo::none);
2350   jmp(E);
2351 
2352   bind(C);
2353 
2354   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2355   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2356   pass_arg3(this, arg_3);
2357 
2358   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2359   pass_arg2(this, arg_2);
2360 
2361   pass_arg1(this, arg_1);
2362   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2363   ret(0);
2364 
2365   bind(E);
2366 }
2367 
2368 void MacroAssembler::call_VM(Register oop_result,
2369                              Register last_java_sp,
2370                              address entry_point,
2371                              int number_of_arguments,
2372                              bool check_exceptions) {
2373   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2374   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2375 }
2376 
2377 void MacroAssembler::call_VM(Register oop_result,
2378                              Register last_java_sp,
2379                              address entry_point,
2380                              Register arg_1,
2381                              bool check_exceptions) {
2382   pass_arg1(this, arg_1);
2383   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2384 }
2385 
2386 void MacroAssembler::call_VM(Register oop_result,
2387                              Register last_java_sp,
2388                              address entry_point,
2389                              Register arg_1,
2390                              Register arg_2,
2391                              bool check_exceptions) {
2392 
2393   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2394   pass_arg2(this, arg_2);
2395   pass_arg1(this, arg_1);
2396   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2397 }
2398 
2399 void MacroAssembler::call_VM(Register oop_result,
2400                              Register last_java_sp,
2401                              address entry_point,
2402                              Register arg_1,
2403                              Register arg_2,
2404                              Register arg_3,
2405                              bool check_exceptions) {
2406   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2407   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2408   pass_arg3(this, arg_3);
2409   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2410   pass_arg2(this, arg_2);
2411   pass_arg1(this, arg_1);
2412   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2413 }
2414 
2415 void MacroAssembler::super_call_VM(Register oop_result,
2416                                    Register last_java_sp,
2417                                    address entry_point,
2418                                    int number_of_arguments,
2419                                    bool check_exceptions) {
2420   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2421   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2422 }
2423 
2424 void MacroAssembler::super_call_VM(Register oop_result,
2425                                    Register last_java_sp,
2426                                    address entry_point,
2427                                    Register arg_1,
2428                                    bool check_exceptions) {
2429   pass_arg1(this, arg_1);
2430   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2431 }
2432 
2433 void MacroAssembler::super_call_VM(Register oop_result,
2434                                    Register last_java_sp,
2435                                    address entry_point,
2436                                    Register arg_1,
2437                                    Register arg_2,
2438                                    bool check_exceptions) {
2439 
2440   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2441   pass_arg2(this, arg_2);
2442   pass_arg1(this, arg_1);
2443   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2444 }
2445 
2446 void MacroAssembler::super_call_VM(Register oop_result,
2447                                    Register last_java_sp,
2448                                    address entry_point,
2449                                    Register arg_1,
2450                                    Register arg_2,
2451                                    Register arg_3,
2452                                    bool check_exceptions) {
2453   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2454   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2455   pass_arg3(this, arg_3);
2456   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2457   pass_arg2(this, arg_2);
2458   pass_arg1(this, arg_1);
2459   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2460 }
2461 
2462 void MacroAssembler::call_VM_base(Register oop_result,
2463                                   Register java_thread,
2464                                   Register last_java_sp,
2465                                   address  entry_point,
2466                                   int      number_of_arguments,
2467                                   bool     check_exceptions) {
2468   // determine java_thread register
2469   if (!java_thread->is_valid()) {
2470 #ifdef _LP64
2471     java_thread = r15_thread;
2472 #else
2473     java_thread = rdi;
2474     get_thread(java_thread);
2475 #endif // LP64
2476   }
2477   // determine last_java_sp register
2478   if (!last_java_sp->is_valid()) {
2479     last_java_sp = rsp;
2480   }
2481   // debugging support
2482   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2483   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2484 #ifdef ASSERT
2485   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2486   // r12 is the heapbase.
2487   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2488 #endif // ASSERT
2489 
2490   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2491   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2492 
2493   // push java thread (becomes first argument of C function)
2494 
2495   NOT_LP64(push(java_thread); number_of_arguments++);
2496   LP64_ONLY(mov(c_rarg0, r15_thread));
2497 
2498   // set last Java frame before call
2499   assert(last_java_sp != rbp, "can't use ebp/rbp");
2500 
2501   // Only interpreter should have to set fp
2502   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2503 
2504   // do the call, remove parameters
2505   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2506 
2507   // restore the thread (cannot use the pushed argument since arguments
2508   // may be overwritten by C code generated by an optimizing compiler);
2509   // however can use the register value directly if it is callee saved.
2510   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2511     // rdi & rsi (also r15) are callee saved -> nothing to do
2512 #ifdef ASSERT
2513     guarantee(java_thread != rax, "change this code");
2514     push(rax);
2515     { Label L;
2516       get_thread(rax);
2517       cmpptr(java_thread, rax);
2518       jcc(Assembler::equal, L);
2519       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2520       bind(L);
2521     }
2522     pop(rax);
2523 #endif
2524   } else {
2525     get_thread(java_thread);
2526   }
2527   // reset last Java frame
2528   // Only interpreter should have to clear fp
2529   reset_last_Java_frame(java_thread, true);
2530 
2531    // C++ interp handles this in the interpreter
2532   check_and_handle_popframe(java_thread);
2533   check_and_handle_earlyret(java_thread);
2534 
2535   if (check_exceptions) {
2536     // check for pending exceptions (java_thread is set upon return)
2537     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2538 #ifndef _LP64
2539     jump_cc(Assembler::notEqual,
2540             RuntimeAddress(StubRoutines::forward_exception_entry()));
2541 #else
2542     // This used to conditionally jump to forward_exception however it is
2543     // possible if we relocate that the branch will not reach. So we must jump
2544     // around so we can always reach
2545 
2546     Label ok;
2547     jcc(Assembler::equal, ok);
2548     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2549     bind(ok);
2550 #endif // LP64
2551   }
2552 
2553   // get oop result if there is one and reset the value in the thread
2554   if (oop_result->is_valid()) {
2555     get_vm_result(oop_result, java_thread);
2556   }
2557 }
2558 
2559 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2560 
2561   // Calculate the value for last_Java_sp
2562   // somewhat subtle. call_VM does an intermediate call
2563   // which places a return address on the stack just under the
2564   // stack pointer as the user finsihed with it. This allows
2565   // use to retrieve last_Java_pc from last_Java_sp[-1].
2566   // On 32bit we then have to push additional args on the stack to accomplish
2567   // the actual requested call. On 64bit call_VM only can use register args
2568   // so the only extra space is the return address that call_VM created.
2569   // This hopefully explains the calculations here.
2570 
2571 #ifdef _LP64
2572   // We've pushed one address, correct last_Java_sp
2573   lea(rax, Address(rsp, wordSize));
2574 #else
2575   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2576 #endif // LP64
2577 
2578   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2579 
2580 }
2581 
2582 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2583 void MacroAssembler::call_VM_leaf0(address entry_point) {
2584   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2585 }
2586 
2587 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2588   call_VM_leaf_base(entry_point, number_of_arguments);
2589 }
2590 
2591 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2592   pass_arg0(this, arg_0);
2593   call_VM_leaf(entry_point, 1);
2594 }
2595 
2596 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2597 
2598   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2599   pass_arg1(this, arg_1);
2600   pass_arg0(this, arg_0);
2601   call_VM_leaf(entry_point, 2);
2602 }
2603 
2604 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2605   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2606   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2607   pass_arg2(this, arg_2);
2608   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2609   pass_arg1(this, arg_1);
2610   pass_arg0(this, arg_0);
2611   call_VM_leaf(entry_point, 3);
2612 }
2613 
2614 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2615   pass_arg0(this, arg_0);
2616   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2617 }
2618 
2619 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2620 
2621   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2622   pass_arg1(this, arg_1);
2623   pass_arg0(this, arg_0);
2624   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2625 }
2626 
2627 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2628   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2629   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2630   pass_arg2(this, arg_2);
2631   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2632   pass_arg1(this, arg_1);
2633   pass_arg0(this, arg_0);
2634   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2635 }
2636 
2637 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2638   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2639   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2640   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2641   pass_arg3(this, arg_3);
2642   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2643   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2644   pass_arg2(this, arg_2);
2645   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2646   pass_arg1(this, arg_1);
2647   pass_arg0(this, arg_0);
2648   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2649 }
2650 
2651 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2652   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2653   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2654   verify_oop(oop_result, "broken oop in call_VM_base");
2655 }
2656 
2657 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2658   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2659   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2660 }
2661 
2662 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2663 }
2664 
2665 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2666 }
2667 
2668 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2669   if (reachable(src1)) {
2670     cmpl(as_Address(src1), imm);
2671   } else {
2672     lea(rscratch1, src1);
2673     cmpl(Address(rscratch1, 0), imm);
2674   }
2675 }
2676 
2677 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2678   assert(!src2.is_lval(), "use cmpptr");
2679   if (reachable(src2)) {
2680     cmpl(src1, as_Address(src2));
2681   } else {
2682     lea(rscratch1, src2);
2683     cmpl(src1, Address(rscratch1, 0));
2684   }
2685 }
2686 
2687 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2688   Assembler::cmpl(src1, imm);
2689 }
2690 
2691 void MacroAssembler::cmp32(Register src1, Address src2) {
2692   Assembler::cmpl(src1, src2);
2693 }
2694 
2695 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2696   ucomisd(opr1, opr2);
2697 
2698   Label L;
2699   if (unordered_is_less) {
2700     movl(dst, -1);
2701     jcc(Assembler::parity, L);
2702     jcc(Assembler::below , L);
2703     movl(dst, 0);
2704     jcc(Assembler::equal , L);
2705     increment(dst);
2706   } else { // unordered is greater
2707     movl(dst, 1);
2708     jcc(Assembler::parity, L);
2709     jcc(Assembler::above , L);
2710     movl(dst, 0);
2711     jcc(Assembler::equal , L);
2712     decrementl(dst);
2713   }
2714   bind(L);
2715 }
2716 
2717 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2718   ucomiss(opr1, opr2);
2719 
2720   Label L;
2721   if (unordered_is_less) {
2722     movl(dst, -1);
2723     jcc(Assembler::parity, L);
2724     jcc(Assembler::below , L);
2725     movl(dst, 0);
2726     jcc(Assembler::equal , L);
2727     increment(dst);
2728   } else { // unordered is greater
2729     movl(dst, 1);
2730     jcc(Assembler::parity, L);
2731     jcc(Assembler::above , L);
2732     movl(dst, 0);
2733     jcc(Assembler::equal , L);
2734     decrementl(dst);
2735   }
2736   bind(L);
2737 }
2738 
2739 
2740 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2741   if (reachable(src1)) {
2742     cmpb(as_Address(src1), imm);
2743   } else {
2744     lea(rscratch1, src1);
2745     cmpb(Address(rscratch1, 0), imm);
2746   }
2747 }
2748 
2749 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2750 #ifdef _LP64
2751   if (src2.is_lval()) {
2752     movptr(rscratch1, src2);
2753     Assembler::cmpq(src1, rscratch1);
2754   } else if (reachable(src2)) {
2755     cmpq(src1, as_Address(src2));
2756   } else {
2757     lea(rscratch1, src2);
2758     Assembler::cmpq(src1, Address(rscratch1, 0));
2759   }
2760 #else
2761   if (src2.is_lval()) {
2762     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2763   } else {
2764     cmpl(src1, as_Address(src2));
2765   }
2766 #endif // _LP64
2767 }
2768 
2769 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2770   assert(src2.is_lval(), "not a mem-mem compare");
2771 #ifdef _LP64
2772   // moves src2's literal address
2773   movptr(rscratch1, src2);
2774   Assembler::cmpq(src1, rscratch1);
2775 #else
2776   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2777 #endif // _LP64
2778 }
2779 
2780 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2781   if (reachable(adr)) {
2782     if (os::is_MP())
2783       lock();
2784     cmpxchgptr(reg, as_Address(adr));
2785   } else {
2786     lea(rscratch1, adr);
2787     if (os::is_MP())
2788       lock();
2789     cmpxchgptr(reg, Address(rscratch1, 0));
2790   }
2791 }
2792 
2793 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2794   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2795 }
2796 
2797 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2798   if (reachable(src)) {
2799     Assembler::comisd(dst, as_Address(src));
2800   } else {
2801     lea(rscratch1, src);
2802     Assembler::comisd(dst, Address(rscratch1, 0));
2803   }
2804 }
2805 
2806 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2807   if (reachable(src)) {
2808     Assembler::comiss(dst, as_Address(src));
2809   } else {
2810     lea(rscratch1, src);
2811     Assembler::comiss(dst, Address(rscratch1, 0));
2812   }
2813 }
2814 
2815 
2816 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2817   Condition negated_cond = negate_condition(cond);
2818   Label L;
2819   jcc(negated_cond, L);
2820   pushf(); // Preserve flags
2821   atomic_incl(counter_addr);
2822   popf();
2823   bind(L);
2824 }
2825 
2826 int MacroAssembler::corrected_idivl(Register reg) {
2827   // Full implementation of Java idiv and irem; checks for
2828   // special case as described in JVM spec., p.243 & p.271.
2829   // The function returns the (pc) offset of the idivl
2830   // instruction - may be needed for implicit exceptions.
2831   //
2832   //         normal case                           special case
2833   //
2834   // input : rax,: dividend                         min_int
2835   //         reg: divisor   (may not be rax,/rdx)   -1
2836   //
2837   // output: rax,: quotient  (= rax, idiv reg)       min_int
2838   //         rdx: remainder (= rax, irem reg)       0
2839   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2840   const int min_int = 0x80000000;
2841   Label normal_case, special_case;
2842 
2843   // check for special case
2844   cmpl(rax, min_int);
2845   jcc(Assembler::notEqual, normal_case);
2846   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2847   cmpl(reg, -1);
2848   jcc(Assembler::equal, special_case);
2849 
2850   // handle normal case
2851   bind(normal_case);
2852   cdql();
2853   int idivl_offset = offset();
2854   idivl(reg);
2855 
2856   // normal and special case exit
2857   bind(special_case);
2858 
2859   return idivl_offset;
2860 }
2861 
2862 
2863 
2864 void MacroAssembler::decrementl(Register reg, int value) {
2865   if (value == min_jint) {subl(reg, value) ; return; }
2866   if (value <  0) { incrementl(reg, -value); return; }
2867   if (value == 0) {                        ; return; }
2868   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2869   /* else */      { subl(reg, value)       ; return; }
2870 }
2871 
2872 void MacroAssembler::decrementl(Address dst, int value) {
2873   if (value == min_jint) {subl(dst, value) ; return; }
2874   if (value <  0) { incrementl(dst, -value); return; }
2875   if (value == 0) {                        ; return; }
2876   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2877   /* else */      { subl(dst, value)       ; return; }
2878 }
2879 
2880 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2881   assert (shift_value > 0, "illegal shift value");
2882   Label _is_positive;
2883   testl (reg, reg);
2884   jcc (Assembler::positive, _is_positive);
2885   int offset = (1 << shift_value) - 1 ;
2886 
2887   if (offset == 1) {
2888     incrementl(reg);
2889   } else {
2890     addl(reg, offset);
2891   }
2892 
2893   bind (_is_positive);
2894   sarl(reg, shift_value);
2895 }
2896 
2897 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2898   if (reachable(src)) {
2899     Assembler::divsd(dst, as_Address(src));
2900   } else {
2901     lea(rscratch1, src);
2902     Assembler::divsd(dst, Address(rscratch1, 0));
2903   }
2904 }
2905 
2906 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2907   if (reachable(src)) {
2908     Assembler::divss(dst, as_Address(src));
2909   } else {
2910     lea(rscratch1, src);
2911     Assembler::divss(dst, Address(rscratch1, 0));
2912   }
2913 }
2914 
2915 // !defined(COMPILER2) is because of stupid core builds
2916 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2917 void MacroAssembler::empty_FPU_stack() {
2918   if (VM_Version::supports_mmx()) {
2919     emms();
2920   } else {
2921     for (int i = 8; i-- > 0; ) ffree(i);
2922   }
2923 }
2924 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2925 
2926 
2927 // Defines obj, preserves var_size_in_bytes
2928 void MacroAssembler::eden_allocate(Register obj,
2929                                    Register var_size_in_bytes,
2930                                    int con_size_in_bytes,
2931                                    Register t1,
2932                                    Label& slow_case) {
2933   assert(obj == rax, "obj must be in rax, for cmpxchg");
2934   assert_different_registers(obj, var_size_in_bytes, t1);
2935   if (!Universe::heap()->supports_inline_contig_alloc()) {
2936     jmp(slow_case);
2937   } else {
2938     Register end = t1;
2939     Label retry;
2940     bind(retry);
2941     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2942     movptr(obj, heap_top);
2943     if (var_size_in_bytes == noreg) {
2944       lea(end, Address(obj, con_size_in_bytes));
2945     } else {
2946       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2947     }
2948     // if end < obj then we wrapped around => object too long => slow case
2949     cmpptr(end, obj);
2950     jcc(Assembler::below, slow_case);
2951     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2952     jcc(Assembler::above, slow_case);
2953     // Compare obj with the top addr, and if still equal, store the new top addr in
2954     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2955     // it otherwise. Use lock prefix for atomicity on MPs.
2956     locked_cmpxchgptr(end, heap_top);
2957     jcc(Assembler::notEqual, retry);
2958   }
2959 }
2960 
2961 void MacroAssembler::enter() {
2962   push(rbp);
2963   mov(rbp, rsp);
2964 }
2965 
2966 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2967 void MacroAssembler::fat_nop() {
2968   if (UseAddressNop) {
2969     addr_nop_5();
2970   } else {
2971     emit_int8(0x26); // es:
2972     emit_int8(0x2e); // cs:
2973     emit_int8(0x64); // fs:
2974     emit_int8(0x65); // gs:
2975     emit_int8((unsigned char)0x90);
2976   }
2977 }
2978 
2979 void MacroAssembler::fcmp(Register tmp) {
2980   fcmp(tmp, 1, true, true);
2981 }
2982 
2983 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2984   assert(!pop_right || pop_left, "usage error");
2985   if (VM_Version::supports_cmov()) {
2986     assert(tmp == noreg, "unneeded temp");
2987     if (pop_left) {
2988       fucomip(index);
2989     } else {
2990       fucomi(index);
2991     }
2992     if (pop_right) {
2993       fpop();
2994     }
2995   } else {
2996     assert(tmp != noreg, "need temp");
2997     if (pop_left) {
2998       if (pop_right) {
2999         fcompp();
3000       } else {
3001         fcomp(index);
3002       }
3003     } else {
3004       fcom(index);
3005     }
3006     // convert FPU condition into eflags condition via rax,
3007     save_rax(tmp);
3008     fwait(); fnstsw_ax();
3009     sahf();
3010     restore_rax(tmp);
3011   }
3012   // condition codes set as follows:
3013   //
3014   // CF (corresponds to C0) if x < y
3015   // PF (corresponds to C2) if unordered
3016   // ZF (corresponds to C3) if x = y
3017 }
3018 
3019 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3020   fcmp2int(dst, unordered_is_less, 1, true, true);
3021 }
3022 
3023 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3024   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3025   Label L;
3026   if (unordered_is_less) {
3027     movl(dst, -1);
3028     jcc(Assembler::parity, L);
3029     jcc(Assembler::below , L);
3030     movl(dst, 0);
3031     jcc(Assembler::equal , L);
3032     increment(dst);
3033   } else { // unordered is greater
3034     movl(dst, 1);
3035     jcc(Assembler::parity, L);
3036     jcc(Assembler::above , L);
3037     movl(dst, 0);
3038     jcc(Assembler::equal , L);
3039     decrementl(dst);
3040   }
3041   bind(L);
3042 }
3043 
3044 void MacroAssembler::fld_d(AddressLiteral src) {
3045   fld_d(as_Address(src));
3046 }
3047 
3048 void MacroAssembler::fld_s(AddressLiteral src) {
3049   fld_s(as_Address(src));
3050 }
3051 
3052 void MacroAssembler::fld_x(AddressLiteral src) {
3053   Assembler::fld_x(as_Address(src));
3054 }
3055 
3056 void MacroAssembler::fldcw(AddressLiteral src) {
3057   Assembler::fldcw(as_Address(src));
3058 }
3059 
3060 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3061   if (reachable(src)) {
3062     Assembler::mulpd(dst, as_Address(src));
3063   } else {
3064     lea(rscratch1, src);
3065     Assembler::mulpd(dst, Address(rscratch1, 0));
3066   }
3067 }
3068 
3069 void MacroAssembler::increase_precision() {
3070   subptr(rsp, BytesPerWord);
3071   fnstcw(Address(rsp, 0));
3072   movl(rax, Address(rsp, 0));
3073   orl(rax, 0x300);
3074   push(rax);
3075   fldcw(Address(rsp, 0));
3076   pop(rax);
3077 }
3078 
3079 void MacroAssembler::restore_precision() {
3080   fldcw(Address(rsp, 0));
3081   addptr(rsp, BytesPerWord);
3082 }
3083 
3084 void MacroAssembler::fpop() {
3085   ffree();
3086   fincstp();
3087 }
3088 
3089 void MacroAssembler::load_float(Address src) {
3090   if (UseSSE >= 1) {
3091     movflt(xmm0, src);
3092   } else {
3093     LP64_ONLY(ShouldNotReachHere());
3094     NOT_LP64(fld_s(src));
3095   }
3096 }
3097 
3098 void MacroAssembler::store_float(Address dst) {
3099   if (UseSSE >= 1) {
3100     movflt(dst, xmm0);
3101   } else {
3102     LP64_ONLY(ShouldNotReachHere());
3103     NOT_LP64(fstp_s(dst));
3104   }
3105 }
3106 
3107 void MacroAssembler::load_double(Address src) {
3108   if (UseSSE >= 2) {
3109     movdbl(xmm0, src);
3110   } else {
3111     LP64_ONLY(ShouldNotReachHere());
3112     NOT_LP64(fld_d(src));
3113   }
3114 }
3115 
3116 void MacroAssembler::store_double(Address dst) {
3117   if (UseSSE >= 2) {
3118     movdbl(dst, xmm0);
3119   } else {
3120     LP64_ONLY(ShouldNotReachHere());
3121     NOT_LP64(fstp_d(dst));
3122   }
3123 }
3124 
3125 void MacroAssembler::fremr(Register tmp) {
3126   save_rax(tmp);
3127   { Label L;
3128     bind(L);
3129     fprem();
3130     fwait(); fnstsw_ax();
3131 #ifdef _LP64
3132     testl(rax, 0x400);
3133     jcc(Assembler::notEqual, L);
3134 #else
3135     sahf();
3136     jcc(Assembler::parity, L);
3137 #endif // _LP64
3138   }
3139   restore_rax(tmp);
3140   // Result is in ST0.
3141   // Note: fxch & fpop to get rid of ST1
3142   // (otherwise FPU stack could overflow eventually)
3143   fxch(1);
3144   fpop();
3145 }
3146 
3147 // dst = c = a * b + c
3148 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3149   Assembler::vfmadd231sd(c, a, b);
3150   if (dst != c) {
3151     movdbl(dst, c);
3152   }
3153 }
3154 
3155 // dst = c = a * b + c
3156 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3157   Assembler::vfmadd231ss(c, a, b);
3158   if (dst != c) {
3159     movflt(dst, c);
3160   }
3161 }
3162 
3163 
3164 
3165 
3166 void MacroAssembler::incrementl(AddressLiteral dst) {
3167   if (reachable(dst)) {
3168     incrementl(as_Address(dst));
3169   } else {
3170     lea(rscratch1, dst);
3171     incrementl(Address(rscratch1, 0));
3172   }
3173 }
3174 
3175 void MacroAssembler::incrementl(ArrayAddress dst) {
3176   incrementl(as_Address(dst));
3177 }
3178 
3179 void MacroAssembler::incrementl(Register reg, int value) {
3180   if (value == min_jint) {addl(reg, value) ; return; }
3181   if (value <  0) { decrementl(reg, -value); return; }
3182   if (value == 0) {                        ; return; }
3183   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3184   /* else */      { addl(reg, value)       ; return; }
3185 }
3186 
3187 void MacroAssembler::incrementl(Address dst, int value) {
3188   if (value == min_jint) {addl(dst, value) ; return; }
3189   if (value <  0) { decrementl(dst, -value); return; }
3190   if (value == 0) {                        ; return; }
3191   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3192   /* else */      { addl(dst, value)       ; return; }
3193 }
3194 
3195 void MacroAssembler::jump(AddressLiteral dst) {
3196   if (reachable(dst)) {
3197     jmp_literal(dst.target(), dst.rspec());
3198   } else {
3199     lea(rscratch1, dst);
3200     jmp(rscratch1);
3201   }
3202 }
3203 
3204 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3205   if (reachable(dst)) {
3206     InstructionMark im(this);
3207     relocate(dst.reloc());
3208     const int short_size = 2;
3209     const int long_size = 6;
3210     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3211     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3212       // 0111 tttn #8-bit disp
3213       emit_int8(0x70 | cc);
3214       emit_int8((offs - short_size) & 0xFF);
3215     } else {
3216       // 0000 1111 1000 tttn #32-bit disp
3217       emit_int8(0x0F);
3218       emit_int8((unsigned char)(0x80 | cc));
3219       emit_int32(offs - long_size);
3220     }
3221   } else {
3222 #ifdef ASSERT
3223     warning("reversing conditional branch");
3224 #endif /* ASSERT */
3225     Label skip;
3226     jccb(reverse[cc], skip);
3227     lea(rscratch1, dst);
3228     Assembler::jmp(rscratch1);
3229     bind(skip);
3230   }
3231 }
3232 
3233 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3234   if (reachable(src)) {
3235     Assembler::ldmxcsr(as_Address(src));
3236   } else {
3237     lea(rscratch1, src);
3238     Assembler::ldmxcsr(Address(rscratch1, 0));
3239   }
3240 }
3241 
3242 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3243   int off;
3244   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3245     off = offset();
3246     movsbl(dst, src); // movsxb
3247   } else {
3248     off = load_unsigned_byte(dst, src);
3249     shll(dst, 24);
3250     sarl(dst, 24);
3251   }
3252   return off;
3253 }
3254 
3255 // Note: load_signed_short used to be called load_signed_word.
3256 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3257 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3258 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3259 int MacroAssembler::load_signed_short(Register dst, Address src) {
3260   int off;
3261   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3262     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3263     // version but this is what 64bit has always done. This seems to imply
3264     // that users are only using 32bits worth.
3265     off = offset();
3266     movswl(dst, src); // movsxw
3267   } else {
3268     off = load_unsigned_short(dst, src);
3269     shll(dst, 16);
3270     sarl(dst, 16);
3271   }
3272   return off;
3273 }
3274 
3275 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3276   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3277   // and "3.9 Partial Register Penalties", p. 22).
3278   int off;
3279   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3280     off = offset();
3281     movzbl(dst, src); // movzxb
3282   } else {
3283     xorl(dst, dst);
3284     off = offset();
3285     movb(dst, src);
3286   }
3287   return off;
3288 }
3289 
3290 // Note: load_unsigned_short used to be called load_unsigned_word.
3291 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3292   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3293   // and "3.9 Partial Register Penalties", p. 22).
3294   int off;
3295   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3296     off = offset();
3297     movzwl(dst, src); // movzxw
3298   } else {
3299     xorl(dst, dst);
3300     off = offset();
3301     movw(dst, src);
3302   }
3303   return off;
3304 }
3305 
3306 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3307   switch (size_in_bytes) {
3308 #ifndef _LP64
3309   case  8:
3310     assert(dst2 != noreg, "second dest register required");
3311     movl(dst,  src);
3312     movl(dst2, src.plus_disp(BytesPerInt));
3313     break;
3314 #else
3315   case  8:  movq(dst, src); break;
3316 #endif
3317   case  4:  movl(dst, src); break;
3318   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3319   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3320   default:  ShouldNotReachHere();
3321   }
3322 }
3323 
3324 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3325   switch (size_in_bytes) {
3326 #ifndef _LP64
3327   case  8:
3328     assert(src2 != noreg, "second source register required");
3329     movl(dst,                        src);
3330     movl(dst.plus_disp(BytesPerInt), src2);
3331     break;
3332 #else
3333   case  8:  movq(dst, src); break;
3334 #endif
3335   case  4:  movl(dst, src); break;
3336   case  2:  movw(dst, src); break;
3337   case  1:  movb(dst, src); break;
3338   default:  ShouldNotReachHere();
3339   }
3340 }
3341 
3342 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3343   if (reachable(dst)) {
3344     movl(as_Address(dst), src);
3345   } else {
3346     lea(rscratch1, dst);
3347     movl(Address(rscratch1, 0), src);
3348   }
3349 }
3350 
3351 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3352   if (reachable(src)) {
3353     movl(dst, as_Address(src));
3354   } else {
3355     lea(rscratch1, src);
3356     movl(dst, Address(rscratch1, 0));
3357   }
3358 }
3359 
3360 // C++ bool manipulation
3361 
3362 void MacroAssembler::movbool(Register dst, Address src) {
3363   if(sizeof(bool) == 1)
3364     movb(dst, src);
3365   else if(sizeof(bool) == 2)
3366     movw(dst, src);
3367   else if(sizeof(bool) == 4)
3368     movl(dst, src);
3369   else
3370     // unsupported
3371     ShouldNotReachHere();
3372 }
3373 
3374 void MacroAssembler::movbool(Address dst, bool boolconst) {
3375   if(sizeof(bool) == 1)
3376     movb(dst, (int) boolconst);
3377   else if(sizeof(bool) == 2)
3378     movw(dst, (int) boolconst);
3379   else if(sizeof(bool) == 4)
3380     movl(dst, (int) boolconst);
3381   else
3382     // unsupported
3383     ShouldNotReachHere();
3384 }
3385 
3386 void MacroAssembler::movbool(Address dst, Register src) {
3387   if(sizeof(bool) == 1)
3388     movb(dst, src);
3389   else if(sizeof(bool) == 2)
3390     movw(dst, src);
3391   else if(sizeof(bool) == 4)
3392     movl(dst, src);
3393   else
3394     // unsupported
3395     ShouldNotReachHere();
3396 }
3397 
3398 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3399   movb(as_Address(dst), src);
3400 }
3401 
3402 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3403   if (reachable(src)) {
3404     movdl(dst, as_Address(src));
3405   } else {
3406     lea(rscratch1, src);
3407     movdl(dst, Address(rscratch1, 0));
3408   }
3409 }
3410 
3411 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3412   if (reachable(src)) {
3413     movq(dst, as_Address(src));
3414   } else {
3415     lea(rscratch1, src);
3416     movq(dst, Address(rscratch1, 0));
3417   }
3418 }
3419 
3420 void MacroAssembler::setvectmask(Register dst, Register src) {
3421   Assembler::movl(dst, 1);
3422   Assembler::shlxl(dst, dst, src);
3423   Assembler::decl(dst);
3424   Assembler::kmovdl(k1, dst);
3425   Assembler::movl(dst, src);
3426 }
3427 
3428 void MacroAssembler::restorevectmask() {
3429   Assembler::knotwl(k1, k0);
3430 }
3431 
3432 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3433   if (reachable(src)) {
3434     if (UseXmmLoadAndClearUpper) {
3435       movsd (dst, as_Address(src));
3436     } else {
3437       movlpd(dst, as_Address(src));
3438     }
3439   } else {
3440     lea(rscratch1, src);
3441     if (UseXmmLoadAndClearUpper) {
3442       movsd (dst, Address(rscratch1, 0));
3443     } else {
3444       movlpd(dst, Address(rscratch1, 0));
3445     }
3446   }
3447 }
3448 
3449 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3450   if (reachable(src)) {
3451     movss(dst, as_Address(src));
3452   } else {
3453     lea(rscratch1, src);
3454     movss(dst, Address(rscratch1, 0));
3455   }
3456 }
3457 
3458 void MacroAssembler::movptr(Register dst, Register src) {
3459   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3460 }
3461 
3462 void MacroAssembler::movptr(Register dst, Address src) {
3463   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3464 }
3465 
3466 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3467 void MacroAssembler::movptr(Register dst, intptr_t src) {
3468   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3469 }
3470 
3471 void MacroAssembler::movptr(Address dst, Register src) {
3472   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3473 }
3474 
3475 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3476   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3477     Assembler::vextractf32x4(dst, src, 0);
3478   } else {
3479     Assembler::movdqu(dst, src);
3480   }
3481 }
3482 
3483 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3484   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3485     Assembler::vinsertf32x4(dst, dst, src, 0);
3486   } else {
3487     Assembler::movdqu(dst, src);
3488   }
3489 }
3490 
3491 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3492   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3493     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3494   } else {
3495     Assembler::movdqu(dst, src);
3496   }
3497 }
3498 
3499 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3500   if (reachable(src)) {
3501     movdqu(dst, as_Address(src));
3502   } else {
3503     lea(scratchReg, src);
3504     movdqu(dst, Address(scratchReg, 0));
3505   }
3506 }
3507 
3508 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3509   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3510     vextractf64x4_low(dst, src);
3511   } else {
3512     Assembler::vmovdqu(dst, src);
3513   }
3514 }
3515 
3516 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3517   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3518     vinsertf64x4_low(dst, src);
3519   } else {
3520     Assembler::vmovdqu(dst, src);
3521   }
3522 }
3523 
3524 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3525   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3526     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3527   }
3528   else {
3529     Assembler::vmovdqu(dst, src);
3530   }
3531 }
3532 
3533 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3534   if (reachable(src)) {
3535     vmovdqu(dst, as_Address(src));
3536   }
3537   else {
3538     lea(rscratch1, src);
3539     vmovdqu(dst, Address(rscratch1, 0));
3540   }
3541 }
3542 
3543 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3544   if (reachable(src)) {
3545     Assembler::movdqa(dst, as_Address(src));
3546   } else {
3547     lea(rscratch1, src);
3548     Assembler::movdqa(dst, Address(rscratch1, 0));
3549   }
3550 }
3551 
3552 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3553   if (reachable(src)) {
3554     Assembler::movsd(dst, as_Address(src));
3555   } else {
3556     lea(rscratch1, src);
3557     Assembler::movsd(dst, Address(rscratch1, 0));
3558   }
3559 }
3560 
3561 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3562   if (reachable(src)) {
3563     Assembler::movss(dst, as_Address(src));
3564   } else {
3565     lea(rscratch1, src);
3566     Assembler::movss(dst, Address(rscratch1, 0));
3567   }
3568 }
3569 
3570 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3571   if (reachable(src)) {
3572     Assembler::mulsd(dst, as_Address(src));
3573   } else {
3574     lea(rscratch1, src);
3575     Assembler::mulsd(dst, Address(rscratch1, 0));
3576   }
3577 }
3578 
3579 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3580   if (reachable(src)) {
3581     Assembler::mulss(dst, as_Address(src));
3582   } else {
3583     lea(rscratch1, src);
3584     Assembler::mulss(dst, Address(rscratch1, 0));
3585   }
3586 }
3587 
3588 void MacroAssembler::null_check(Register reg, int offset) {
3589   if (needs_explicit_null_check(offset)) {
3590     // provoke OS NULL exception if reg = NULL by
3591     // accessing M[reg] w/o changing any (non-CC) registers
3592     // NOTE: cmpl is plenty here to provoke a segv
3593     cmpptr(rax, Address(reg, 0));
3594     // Note: should probably use testl(rax, Address(reg, 0));
3595     //       may be shorter code (however, this version of
3596     //       testl needs to be implemented first)
3597   } else {
3598     // nothing to do, (later) access of M[reg + offset]
3599     // will provoke OS NULL exception if reg = NULL
3600   }
3601 }
3602 
3603 void MacroAssembler::os_breakpoint() {
3604   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3605   // (e.g., MSVC can't call ps() otherwise)
3606   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3607 }
3608 
3609 #ifdef _LP64
3610 #define XSTATE_BV 0x200
3611 #endif
3612 
3613 void MacroAssembler::pop_CPU_state() {
3614   pop_FPU_state();
3615   pop_IU_state();
3616 }
3617 
3618 void MacroAssembler::pop_FPU_state() {
3619 #ifndef _LP64
3620   frstor(Address(rsp, 0));
3621 #else
3622   fxrstor(Address(rsp, 0));
3623 #endif
3624   addptr(rsp, FPUStateSizeInWords * wordSize);
3625 }
3626 
3627 void MacroAssembler::pop_IU_state() {
3628   popa();
3629   LP64_ONLY(addq(rsp, 8));
3630   popf();
3631 }
3632 
3633 // Save Integer and Float state
3634 // Warning: Stack must be 16 byte aligned (64bit)
3635 void MacroAssembler::push_CPU_state() {
3636   push_IU_state();
3637   push_FPU_state();
3638 }
3639 
3640 void MacroAssembler::push_FPU_state() {
3641   subptr(rsp, FPUStateSizeInWords * wordSize);
3642 #ifndef _LP64
3643   fnsave(Address(rsp, 0));
3644   fwait();
3645 #else
3646   fxsave(Address(rsp, 0));
3647 #endif // LP64
3648 }
3649 
3650 void MacroAssembler::push_IU_state() {
3651   // Push flags first because pusha kills them
3652   pushf();
3653   // Make sure rsp stays 16-byte aligned
3654   LP64_ONLY(subq(rsp, 8));
3655   pusha();
3656 }
3657 
3658 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3659   if (!java_thread->is_valid()) {
3660     java_thread = rdi;
3661     get_thread(java_thread);
3662   }
3663   // we must set sp to zero to clear frame
3664   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3665   if (clear_fp) {
3666     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3667   }
3668 
3669   // Always clear the pc because it could have been set by make_walkable()
3670   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3671 
3672 }
3673 
3674 void MacroAssembler::restore_rax(Register tmp) {
3675   if (tmp == noreg) pop(rax);
3676   else if (tmp != rax) mov(rax, tmp);
3677 }
3678 
3679 void MacroAssembler::round_to(Register reg, int modulus) {
3680   addptr(reg, modulus - 1);
3681   andptr(reg, -modulus);
3682 }
3683 
3684 void MacroAssembler::save_rax(Register tmp) {
3685   if (tmp == noreg) push(rax);
3686   else if (tmp != rax) mov(tmp, rax);
3687 }
3688 
3689 // Write serialization page so VM thread can do a pseudo remote membar.
3690 // We use the current thread pointer to calculate a thread specific
3691 // offset to write to within the page. This minimizes bus traffic
3692 // due to cache line collision.
3693 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3694   movl(tmp, thread);
3695   shrl(tmp, os::get_serialize_page_shift_count());
3696   andl(tmp, (os::vm_page_size() - sizeof(int)));
3697 
3698   Address index(noreg, tmp, Address::times_1);
3699   ExternalAddress page(os::get_memory_serialize_page());
3700 
3701   // Size of store must match masking code above
3702   movl(as_Address(ArrayAddress(page, index)), tmp);
3703 }
3704 
3705 // Calls to C land
3706 //
3707 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3708 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3709 // has to be reset to 0. This is required to allow proper stack traversal.
3710 void MacroAssembler::set_last_Java_frame(Register java_thread,
3711                                          Register last_java_sp,
3712                                          Register last_java_fp,
3713                                          address  last_java_pc) {
3714   // determine java_thread register
3715   if (!java_thread->is_valid()) {
3716     java_thread = rdi;
3717     get_thread(java_thread);
3718   }
3719   // determine last_java_sp register
3720   if (!last_java_sp->is_valid()) {
3721     last_java_sp = rsp;
3722   }
3723 
3724   // last_java_fp is optional
3725 
3726   if (last_java_fp->is_valid()) {
3727     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3728   }
3729 
3730   // last_java_pc is optional
3731 
3732   if (last_java_pc != NULL) {
3733     lea(Address(java_thread,
3734                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3735         InternalAddress(last_java_pc));
3736 
3737   }
3738   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3739 }
3740 
3741 void MacroAssembler::shlptr(Register dst, int imm8) {
3742   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3743 }
3744 
3745 void MacroAssembler::shrptr(Register dst, int imm8) {
3746   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3747 }
3748 
3749 void MacroAssembler::sign_extend_byte(Register reg) {
3750   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3751     movsbl(reg, reg); // movsxb
3752   } else {
3753     shll(reg, 24);
3754     sarl(reg, 24);
3755   }
3756 }
3757 
3758 void MacroAssembler::sign_extend_short(Register reg) {
3759   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3760     movswl(reg, reg); // movsxw
3761   } else {
3762     shll(reg, 16);
3763     sarl(reg, 16);
3764   }
3765 }
3766 
3767 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3768   assert(reachable(src), "Address should be reachable");
3769   testl(dst, as_Address(src));
3770 }
3771 
3772 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3773   int dst_enc = dst->encoding();
3774   int src_enc = src->encoding();
3775   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3776     Assembler::pcmpeqb(dst, src);
3777   } else if ((dst_enc < 16) && (src_enc < 16)) {
3778     Assembler::pcmpeqb(dst, src);
3779   } else if (src_enc < 16) {
3780     subptr(rsp, 64);
3781     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3782     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3783     Assembler::pcmpeqb(xmm0, src);
3784     movdqu(dst, xmm0);
3785     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3786     addptr(rsp, 64);
3787   } else if (dst_enc < 16) {
3788     subptr(rsp, 64);
3789     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3790     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3791     Assembler::pcmpeqb(dst, xmm0);
3792     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3793     addptr(rsp, 64);
3794   } else {
3795     subptr(rsp, 64);
3796     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3797     subptr(rsp, 64);
3798     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3799     movdqu(xmm0, src);
3800     movdqu(xmm1, dst);
3801     Assembler::pcmpeqb(xmm1, xmm0);
3802     movdqu(dst, xmm1);
3803     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3804     addptr(rsp, 64);
3805     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3806     addptr(rsp, 64);
3807   }
3808 }
3809 
3810 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3811   int dst_enc = dst->encoding();
3812   int src_enc = src->encoding();
3813   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3814     Assembler::pcmpeqw(dst, src);
3815   } else if ((dst_enc < 16) && (src_enc < 16)) {
3816     Assembler::pcmpeqw(dst, src);
3817   } else if (src_enc < 16) {
3818     subptr(rsp, 64);
3819     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3820     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3821     Assembler::pcmpeqw(xmm0, src);
3822     movdqu(dst, xmm0);
3823     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3824     addptr(rsp, 64);
3825   } else if (dst_enc < 16) {
3826     subptr(rsp, 64);
3827     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3828     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3829     Assembler::pcmpeqw(dst, xmm0);
3830     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3831     addptr(rsp, 64);
3832   } else {
3833     subptr(rsp, 64);
3834     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3835     subptr(rsp, 64);
3836     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3837     movdqu(xmm0, src);
3838     movdqu(xmm1, dst);
3839     Assembler::pcmpeqw(xmm1, xmm0);
3840     movdqu(dst, xmm1);
3841     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3842     addptr(rsp, 64);
3843     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3844     addptr(rsp, 64);
3845   }
3846 }
3847 
3848 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3849   int dst_enc = dst->encoding();
3850   if (dst_enc < 16) {
3851     Assembler::pcmpestri(dst, src, imm8);
3852   } else {
3853     subptr(rsp, 64);
3854     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3855     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3856     Assembler::pcmpestri(xmm0, src, imm8);
3857     movdqu(dst, xmm0);
3858     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3859     addptr(rsp, 64);
3860   }
3861 }
3862 
3863 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3864   int dst_enc = dst->encoding();
3865   int src_enc = src->encoding();
3866   if ((dst_enc < 16) && (src_enc < 16)) {
3867     Assembler::pcmpestri(dst, src, imm8);
3868   } else if (src_enc < 16) {
3869     subptr(rsp, 64);
3870     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3871     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3872     Assembler::pcmpestri(xmm0, src, imm8);
3873     movdqu(dst, xmm0);
3874     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3875     addptr(rsp, 64);
3876   } else if (dst_enc < 16) {
3877     subptr(rsp, 64);
3878     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3879     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3880     Assembler::pcmpestri(dst, xmm0, imm8);
3881     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3882     addptr(rsp, 64);
3883   } else {
3884     subptr(rsp, 64);
3885     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3886     subptr(rsp, 64);
3887     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3888     movdqu(xmm0, src);
3889     movdqu(xmm1, dst);
3890     Assembler::pcmpestri(xmm1, xmm0, imm8);
3891     movdqu(dst, xmm1);
3892     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3893     addptr(rsp, 64);
3894     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3895     addptr(rsp, 64);
3896   }
3897 }
3898 
3899 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3900   int dst_enc = dst->encoding();
3901   int src_enc = src->encoding();
3902   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3903     Assembler::pmovzxbw(dst, src);
3904   } else if ((dst_enc < 16) && (src_enc < 16)) {
3905     Assembler::pmovzxbw(dst, src);
3906   } else if (src_enc < 16) {
3907     subptr(rsp, 64);
3908     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3909     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3910     Assembler::pmovzxbw(xmm0, src);
3911     movdqu(dst, xmm0);
3912     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3913     addptr(rsp, 64);
3914   } else if (dst_enc < 16) {
3915     subptr(rsp, 64);
3916     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3917     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3918     Assembler::pmovzxbw(dst, xmm0);
3919     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3920     addptr(rsp, 64);
3921   } else {
3922     subptr(rsp, 64);
3923     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3924     subptr(rsp, 64);
3925     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3926     movdqu(xmm0, src);
3927     movdqu(xmm1, dst);
3928     Assembler::pmovzxbw(xmm1, xmm0);
3929     movdqu(dst, xmm1);
3930     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3931     addptr(rsp, 64);
3932     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3933     addptr(rsp, 64);
3934   }
3935 }
3936 
3937 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
3938   int dst_enc = dst->encoding();
3939   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3940     Assembler::pmovzxbw(dst, src);
3941   } else if (dst_enc < 16) {
3942     Assembler::pmovzxbw(dst, src);
3943   } else {
3944     subptr(rsp, 64);
3945     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3946     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3947     Assembler::pmovzxbw(xmm0, src);
3948     movdqu(dst, xmm0);
3949     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3950     addptr(rsp, 64);
3951   }
3952 }
3953 
3954 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
3955   int src_enc = src->encoding();
3956   if (src_enc < 16) {
3957     Assembler::pmovmskb(dst, src);
3958   } else {
3959     subptr(rsp, 64);
3960     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3961     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3962     Assembler::pmovmskb(dst, xmm0);
3963     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3964     addptr(rsp, 64);
3965   }
3966 }
3967 
3968 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
3969   int dst_enc = dst->encoding();
3970   int src_enc = src->encoding();
3971   if ((dst_enc < 16) && (src_enc < 16)) {
3972     Assembler::ptest(dst, src);
3973   } else if (src_enc < 16) {
3974     subptr(rsp, 64);
3975     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3976     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3977     Assembler::ptest(xmm0, src);
3978     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3979     addptr(rsp, 64);
3980   } else if (dst_enc < 16) {
3981     subptr(rsp, 64);
3982     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3983     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3984     Assembler::ptest(dst, xmm0);
3985     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3986     addptr(rsp, 64);
3987   } else {
3988     subptr(rsp, 64);
3989     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3990     subptr(rsp, 64);
3991     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3992     movdqu(xmm0, src);
3993     movdqu(xmm1, dst);
3994     Assembler::ptest(xmm1, xmm0);
3995     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3996     addptr(rsp, 64);
3997     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3998     addptr(rsp, 64);
3999   }
4000 }
4001 
4002 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4003   if (reachable(src)) {
4004     Assembler::sqrtsd(dst, as_Address(src));
4005   } else {
4006     lea(rscratch1, src);
4007     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4008   }
4009 }
4010 
4011 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4012   if (reachable(src)) {
4013     Assembler::sqrtss(dst, as_Address(src));
4014   } else {
4015     lea(rscratch1, src);
4016     Assembler::sqrtss(dst, Address(rscratch1, 0));
4017   }
4018 }
4019 
4020 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4021   if (reachable(src)) {
4022     Assembler::subsd(dst, as_Address(src));
4023   } else {
4024     lea(rscratch1, src);
4025     Assembler::subsd(dst, Address(rscratch1, 0));
4026   }
4027 }
4028 
4029 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4030   if (reachable(src)) {
4031     Assembler::subss(dst, as_Address(src));
4032   } else {
4033     lea(rscratch1, src);
4034     Assembler::subss(dst, Address(rscratch1, 0));
4035   }
4036 }
4037 
4038 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4039   if (reachable(src)) {
4040     Assembler::ucomisd(dst, as_Address(src));
4041   } else {
4042     lea(rscratch1, src);
4043     Assembler::ucomisd(dst, Address(rscratch1, 0));
4044   }
4045 }
4046 
4047 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4048   if (reachable(src)) {
4049     Assembler::ucomiss(dst, as_Address(src));
4050   } else {
4051     lea(rscratch1, src);
4052     Assembler::ucomiss(dst, Address(rscratch1, 0));
4053   }
4054 }
4055 
4056 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4057   // Used in sign-bit flipping with aligned address.
4058   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4059   if (reachable(src)) {
4060     Assembler::xorpd(dst, as_Address(src));
4061   } else {
4062     lea(rscratch1, src);
4063     Assembler::xorpd(dst, Address(rscratch1, 0));
4064   }
4065 }
4066 
4067 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4068   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4069     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4070   }
4071   else {
4072     Assembler::xorpd(dst, src);
4073   }
4074 }
4075 
4076 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4077   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4078     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4079   } else {
4080     Assembler::xorps(dst, src);
4081   }
4082 }
4083 
4084 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4085   // Used in sign-bit flipping with aligned address.
4086   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4087   if (reachable(src)) {
4088     Assembler::xorps(dst, as_Address(src));
4089   } else {
4090     lea(rscratch1, src);
4091     Assembler::xorps(dst, Address(rscratch1, 0));
4092   }
4093 }
4094 
4095 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4096   // Used in sign-bit flipping with aligned address.
4097   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4098   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4099   if (reachable(src)) {
4100     Assembler::pshufb(dst, as_Address(src));
4101   } else {
4102     lea(rscratch1, src);
4103     Assembler::pshufb(dst, Address(rscratch1, 0));
4104   }
4105 }
4106 
4107 // AVX 3-operands instructions
4108 
4109 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4110   if (reachable(src)) {
4111     vaddsd(dst, nds, as_Address(src));
4112   } else {
4113     lea(rscratch1, src);
4114     vaddsd(dst, nds, Address(rscratch1, 0));
4115   }
4116 }
4117 
4118 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4119   if (reachable(src)) {
4120     vaddss(dst, nds, as_Address(src));
4121   } else {
4122     lea(rscratch1, src);
4123     vaddss(dst, nds, Address(rscratch1, 0));
4124   }
4125 }
4126 
4127 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4128   int dst_enc = dst->encoding();
4129   int nds_enc = nds->encoding();
4130   int src_enc = src->encoding();
4131   if ((dst_enc < 16) && (nds_enc < 16)) {
4132     vandps(dst, nds, negate_field, vector_len);
4133   } else if ((src_enc < 16) && (dst_enc < 16)) {
4134     movss(src, nds);
4135     vandps(dst, src, negate_field, vector_len);
4136   } else if (src_enc < 16) {
4137     movss(src, nds);
4138     vandps(src, src, negate_field, vector_len);
4139     movss(dst, src);
4140   } else if (dst_enc < 16) {
4141     movdqu(src, xmm0);
4142     movss(xmm0, nds);
4143     vandps(dst, xmm0, negate_field, vector_len);
4144     movdqu(xmm0, src);
4145   } else if (nds_enc < 16) {
4146     movdqu(src, xmm0);
4147     vandps(xmm0, nds, negate_field, vector_len);
4148     movss(dst, xmm0);
4149     movdqu(xmm0, src);
4150   } else {
4151     movdqu(src, xmm0);
4152     movss(xmm0, nds);
4153     vandps(xmm0, xmm0, negate_field, vector_len);
4154     movss(dst, xmm0);
4155     movdqu(xmm0, src);
4156   }
4157 }
4158 
4159 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4160   int dst_enc = dst->encoding();
4161   int nds_enc = nds->encoding();
4162   int src_enc = src->encoding();
4163   if ((dst_enc < 16) && (nds_enc < 16)) {
4164     vandpd(dst, nds, negate_field, vector_len);
4165   } else if ((src_enc < 16) && (dst_enc < 16)) {
4166     movsd(src, nds);
4167     vandpd(dst, src, negate_field, vector_len);
4168   } else if (src_enc < 16) {
4169     movsd(src, nds);
4170     vandpd(src, src, negate_field, vector_len);
4171     movsd(dst, src);
4172   } else if (dst_enc < 16) {
4173     movdqu(src, xmm0);
4174     movsd(xmm0, nds);
4175     vandpd(dst, xmm0, negate_field, vector_len);
4176     movdqu(xmm0, src);
4177   } else if (nds_enc < 16) {
4178     movdqu(src, xmm0);
4179     vandpd(xmm0, nds, negate_field, vector_len);
4180     movsd(dst, xmm0);
4181     movdqu(xmm0, src);
4182   } else {
4183     movdqu(src, xmm0);
4184     movsd(xmm0, nds);
4185     vandpd(xmm0, xmm0, negate_field, vector_len);
4186     movsd(dst, xmm0);
4187     movdqu(xmm0, src);
4188   }
4189 }
4190 
4191 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4192   int dst_enc = dst->encoding();
4193   int nds_enc = nds->encoding();
4194   int src_enc = src->encoding();
4195   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4196     Assembler::vpaddb(dst, nds, src, vector_len);
4197   } else if ((dst_enc < 16) && (src_enc < 16)) {
4198     Assembler::vpaddb(dst, dst, src, vector_len);
4199   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4200     // use nds as scratch for src
4201     evmovdqul(nds, src, Assembler::AVX_512bit);
4202     Assembler::vpaddb(dst, dst, nds, vector_len);
4203   } else if ((src_enc < 16) && (nds_enc < 16)) {
4204     // use nds as scratch for dst
4205     evmovdqul(nds, dst, Assembler::AVX_512bit);
4206     Assembler::vpaddb(nds, nds, src, vector_len);
4207     evmovdqul(dst, nds, Assembler::AVX_512bit);
4208   } else if (dst_enc < 16) {
4209     // use nds as scatch for xmm0 to hold src
4210     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4211     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4212     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4213     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4214   } else {
4215     // worse case scenario, all regs are in the upper bank
4216     subptr(rsp, 64);
4217     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4218     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4219     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4220     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4221     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4222     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4223     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4224     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4225     addptr(rsp, 64);
4226   }
4227 }
4228 
4229 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4230   int dst_enc = dst->encoding();
4231   int nds_enc = nds->encoding();
4232   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4233     Assembler::vpaddb(dst, nds, src, vector_len);
4234   } else if (dst_enc < 16) {
4235     Assembler::vpaddb(dst, dst, src, vector_len);
4236   } else if (nds_enc < 16) {
4237     // implies dst_enc in upper bank with src as scratch
4238     evmovdqul(nds, dst, Assembler::AVX_512bit);
4239     Assembler::vpaddb(nds, nds, src, vector_len);
4240     evmovdqul(dst, nds, Assembler::AVX_512bit);
4241   } else {
4242     // worse case scenario, all regs in upper bank
4243     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4244     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4245     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4246     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4247   }
4248 }
4249 
4250 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4251   int dst_enc = dst->encoding();
4252   int nds_enc = nds->encoding();
4253   int src_enc = src->encoding();
4254   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4255     Assembler::vpaddw(dst, nds, src, vector_len);
4256   } else if ((dst_enc < 16) && (src_enc < 16)) {
4257     Assembler::vpaddw(dst, dst, src, vector_len);
4258   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4259     // use nds as scratch for src
4260     evmovdqul(nds, src, Assembler::AVX_512bit);
4261     Assembler::vpaddw(dst, dst, nds, vector_len);
4262   } else if ((src_enc < 16) && (nds_enc < 16)) {
4263     // use nds as scratch for dst
4264     evmovdqul(nds, dst, Assembler::AVX_512bit);
4265     Assembler::vpaddw(nds, nds, src, vector_len);
4266     evmovdqul(dst, nds, Assembler::AVX_512bit);
4267   } else if (dst_enc < 16) {
4268     // use nds as scatch for xmm0 to hold src
4269     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4270     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4271     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4272     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4273   } else {
4274     // worse case scenario, all regs are in the upper bank
4275     subptr(rsp, 64);
4276     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4277     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4278     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4279     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4280     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4281     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4282     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4283     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4284     addptr(rsp, 64);
4285   }
4286 }
4287 
4288 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4289   int dst_enc = dst->encoding();
4290   int nds_enc = nds->encoding();
4291   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4292     Assembler::vpaddw(dst, nds, src, vector_len);
4293   } else if (dst_enc < 16) {
4294     Assembler::vpaddw(dst, dst, src, vector_len);
4295   } else if (nds_enc < 16) {
4296     // implies dst_enc in upper bank with src as scratch
4297     evmovdqul(nds, dst, Assembler::AVX_512bit);
4298     Assembler::vpaddw(nds, nds, src, vector_len);
4299     evmovdqul(dst, nds, Assembler::AVX_512bit);
4300   } else {
4301     // worse case scenario, all regs in upper bank
4302     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4303     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4304     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4305     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4306   }
4307 }
4308 
4309 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4310   if (reachable(src)) {
4311     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4312   } else {
4313     lea(rscratch1, src);
4314     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4315   }
4316 }
4317 
4318 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4319   int dst_enc = dst->encoding();
4320   int src_enc = src->encoding();
4321   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4322     Assembler::vpbroadcastw(dst, src);
4323   } else if ((dst_enc < 16) && (src_enc < 16)) {
4324     Assembler::vpbroadcastw(dst, src);
4325   } else if (src_enc < 16) {
4326     subptr(rsp, 64);
4327     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4328     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4329     Assembler::vpbroadcastw(xmm0, src);
4330     movdqu(dst, xmm0);
4331     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4332     addptr(rsp, 64);
4333   } else if (dst_enc < 16) {
4334     subptr(rsp, 64);
4335     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4336     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4337     Assembler::vpbroadcastw(dst, xmm0);
4338     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4339     addptr(rsp, 64);
4340   } else {
4341     subptr(rsp, 64);
4342     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4343     subptr(rsp, 64);
4344     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4345     movdqu(xmm0, src);
4346     movdqu(xmm1, dst);
4347     Assembler::vpbroadcastw(xmm1, xmm0);
4348     movdqu(dst, xmm1);
4349     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4350     addptr(rsp, 64);
4351     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4352     addptr(rsp, 64);
4353   }
4354 }
4355 
4356 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4357   int dst_enc = dst->encoding();
4358   int nds_enc = nds->encoding();
4359   int src_enc = src->encoding();
4360   assert(dst_enc == nds_enc, "");
4361   if ((dst_enc < 16) && (src_enc < 16)) {
4362     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4363   } else if (src_enc < 16) {
4364     subptr(rsp, 64);
4365     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4366     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4367     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4368     movdqu(dst, xmm0);
4369     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4370     addptr(rsp, 64);
4371   } else if (dst_enc < 16) {
4372     subptr(rsp, 64);
4373     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4374     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4375     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4376     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4377     addptr(rsp, 64);
4378   } else {
4379     subptr(rsp, 64);
4380     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4381     subptr(rsp, 64);
4382     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4383     movdqu(xmm0, src);
4384     movdqu(xmm1, dst);
4385     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4386     movdqu(dst, xmm1);
4387     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4388     addptr(rsp, 64);
4389     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4390     addptr(rsp, 64);
4391   }
4392 }
4393 
4394 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4395   int dst_enc = dst->encoding();
4396   int nds_enc = nds->encoding();
4397   int src_enc = src->encoding();
4398   assert(dst_enc == nds_enc, "");
4399   if ((dst_enc < 16) && (src_enc < 16)) {
4400     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4401   } else if (src_enc < 16) {
4402     subptr(rsp, 64);
4403     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4404     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4405     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4406     movdqu(dst, xmm0);
4407     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4408     addptr(rsp, 64);
4409   } else if (dst_enc < 16) {
4410     subptr(rsp, 64);
4411     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4412     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4413     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4414     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4415     addptr(rsp, 64);
4416   } else {
4417     subptr(rsp, 64);
4418     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4419     subptr(rsp, 64);
4420     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4421     movdqu(xmm0, src);
4422     movdqu(xmm1, dst);
4423     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4424     movdqu(dst, xmm1);
4425     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4426     addptr(rsp, 64);
4427     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4428     addptr(rsp, 64);
4429   }
4430 }
4431 
4432 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4433   int dst_enc = dst->encoding();
4434   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4435     Assembler::vpmovzxbw(dst, src, vector_len);
4436   } else if (dst_enc < 16) {
4437     Assembler::vpmovzxbw(dst, src, vector_len);
4438   } else {
4439     subptr(rsp, 64);
4440     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4441     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4442     Assembler::vpmovzxbw(xmm0, src, vector_len);
4443     movdqu(dst, xmm0);
4444     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4445     addptr(rsp, 64);
4446   }
4447 }
4448 
4449 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4450   int src_enc = src->encoding();
4451   if (src_enc < 16) {
4452     Assembler::vpmovmskb(dst, src);
4453   } else {
4454     subptr(rsp, 64);
4455     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4456     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4457     Assembler::vpmovmskb(dst, xmm0);
4458     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4459     addptr(rsp, 64);
4460   }
4461 }
4462 
4463 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4464   int dst_enc = dst->encoding();
4465   int nds_enc = nds->encoding();
4466   int src_enc = src->encoding();
4467   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4468     Assembler::vpmullw(dst, nds, src, vector_len);
4469   } else if ((dst_enc < 16) && (src_enc < 16)) {
4470     Assembler::vpmullw(dst, dst, src, vector_len);
4471   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4472     // use nds as scratch for src
4473     evmovdqul(nds, src, Assembler::AVX_512bit);
4474     Assembler::vpmullw(dst, dst, nds, vector_len);
4475   } else if ((src_enc < 16) && (nds_enc < 16)) {
4476     // use nds as scratch for dst
4477     evmovdqul(nds, dst, Assembler::AVX_512bit);
4478     Assembler::vpmullw(nds, nds, src, vector_len);
4479     evmovdqul(dst, nds, Assembler::AVX_512bit);
4480   } else if (dst_enc < 16) {
4481     // use nds as scatch for xmm0 to hold src
4482     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4483     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4484     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4485     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4486   } else {
4487     // worse case scenario, all regs are in the upper bank
4488     subptr(rsp, 64);
4489     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4490     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4491     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4492     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4493     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4494     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4495     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4496     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4497     addptr(rsp, 64);
4498   }
4499 }
4500 
4501 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4502   int dst_enc = dst->encoding();
4503   int nds_enc = nds->encoding();
4504   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4505     Assembler::vpmullw(dst, nds, src, vector_len);
4506   } else if (dst_enc < 16) {
4507     Assembler::vpmullw(dst, dst, src, vector_len);
4508   } else if (nds_enc < 16) {
4509     // implies dst_enc in upper bank with src as scratch
4510     evmovdqul(nds, dst, Assembler::AVX_512bit);
4511     Assembler::vpmullw(nds, nds, src, vector_len);
4512     evmovdqul(dst, nds, Assembler::AVX_512bit);
4513   } else {
4514     // worse case scenario, all regs in upper bank
4515     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4516     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4517     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4518     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4519   }
4520 }
4521 
4522 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4523   int dst_enc = dst->encoding();
4524   int nds_enc = nds->encoding();
4525   int src_enc = src->encoding();
4526   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4527     Assembler::vpsubb(dst, nds, src, vector_len);
4528   } else if ((dst_enc < 16) && (src_enc < 16)) {
4529     Assembler::vpsubb(dst, dst, src, vector_len);
4530   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4531     // use nds as scratch for src
4532     evmovdqul(nds, src, Assembler::AVX_512bit);
4533     Assembler::vpsubb(dst, dst, nds, vector_len);
4534   } else if ((src_enc < 16) && (nds_enc < 16)) {
4535     // use nds as scratch for dst
4536     evmovdqul(nds, dst, Assembler::AVX_512bit);
4537     Assembler::vpsubb(nds, nds, src, vector_len);
4538     evmovdqul(dst, nds, Assembler::AVX_512bit);
4539   } else if (dst_enc < 16) {
4540     // use nds as scatch for xmm0 to hold src
4541     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4542     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4543     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4544     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4545   } else {
4546     // worse case scenario, all regs are in the upper bank
4547     subptr(rsp, 64);
4548     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4549     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4550     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4551     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4552     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4553     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4554     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4555     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4556     addptr(rsp, 64);
4557   }
4558 }
4559 
4560 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4561   int dst_enc = dst->encoding();
4562   int nds_enc = nds->encoding();
4563   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4564     Assembler::vpsubb(dst, nds, src, vector_len);
4565   } else if (dst_enc < 16) {
4566     Assembler::vpsubb(dst, dst, src, vector_len);
4567   } else if (nds_enc < 16) {
4568     // implies dst_enc in upper bank with src as scratch
4569     evmovdqul(nds, dst, Assembler::AVX_512bit);
4570     Assembler::vpsubb(nds, nds, src, vector_len);
4571     evmovdqul(dst, nds, Assembler::AVX_512bit);
4572   } else {
4573     // worse case scenario, all regs in upper bank
4574     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4575     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4576     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4577     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4578   }
4579 }
4580 
4581 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4582   int dst_enc = dst->encoding();
4583   int nds_enc = nds->encoding();
4584   int src_enc = src->encoding();
4585   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4586     Assembler::vpsubw(dst, nds, src, vector_len);
4587   } else if ((dst_enc < 16) && (src_enc < 16)) {
4588     Assembler::vpsubw(dst, dst, src, vector_len);
4589   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4590     // use nds as scratch for src
4591     evmovdqul(nds, src, Assembler::AVX_512bit);
4592     Assembler::vpsubw(dst, dst, nds, vector_len);
4593   } else if ((src_enc < 16) && (nds_enc < 16)) {
4594     // use nds as scratch for dst
4595     evmovdqul(nds, dst, Assembler::AVX_512bit);
4596     Assembler::vpsubw(nds, nds, src, vector_len);
4597     evmovdqul(dst, nds, Assembler::AVX_512bit);
4598   } else if (dst_enc < 16) {
4599     // use nds as scatch for xmm0 to hold src
4600     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4601     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4602     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4603     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4604   } else {
4605     // worse case scenario, all regs are in the upper bank
4606     subptr(rsp, 64);
4607     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4608     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4609     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4610     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4611     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4612     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4613     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4614     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4615     addptr(rsp, 64);
4616   }
4617 }
4618 
4619 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4620   int dst_enc = dst->encoding();
4621   int nds_enc = nds->encoding();
4622   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4623     Assembler::vpsubw(dst, nds, src, vector_len);
4624   } else if (dst_enc < 16) {
4625     Assembler::vpsubw(dst, dst, src, vector_len);
4626   } else if (nds_enc < 16) {
4627     // implies dst_enc in upper bank with src as scratch
4628     evmovdqul(nds, dst, Assembler::AVX_512bit);
4629     Assembler::vpsubw(nds, nds, src, vector_len);
4630     evmovdqul(dst, nds, Assembler::AVX_512bit);
4631   } else {
4632     // worse case scenario, all regs in upper bank
4633     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4634     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4635     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4636     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4637   }
4638 }
4639 
4640 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4641   int dst_enc = dst->encoding();
4642   int nds_enc = nds->encoding();
4643   int shift_enc = shift->encoding();
4644   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4645     Assembler::vpsraw(dst, nds, shift, vector_len);
4646   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4647     Assembler::vpsraw(dst, dst, shift, vector_len);
4648   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4649     // use nds_enc as scratch with shift
4650     evmovdqul(nds, shift, Assembler::AVX_512bit);
4651     Assembler::vpsraw(dst, dst, nds, vector_len);
4652   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4653     // use nds as scratch with dst
4654     evmovdqul(nds, dst, Assembler::AVX_512bit);
4655     Assembler::vpsraw(nds, nds, shift, vector_len);
4656     evmovdqul(dst, nds, Assembler::AVX_512bit);
4657   } else if (dst_enc < 16) {
4658     // use nds to save a copy of xmm0 and hold shift
4659     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4660     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4661     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4662     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4663   } else if (nds_enc < 16) {
4664     // use nds as dest as temps
4665     evmovdqul(nds, dst, Assembler::AVX_512bit);
4666     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4667     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4668     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4669     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4670     evmovdqul(dst, nds, Assembler::AVX_512bit);
4671   } else {
4672     // worse case scenario, all regs are in the upper bank
4673     subptr(rsp, 64);
4674     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4675     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4676     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4677     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4678     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4679     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4680     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4681     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4682     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4683     addptr(rsp, 64);
4684   }
4685 }
4686 
4687 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4688   int dst_enc = dst->encoding();
4689   int nds_enc = nds->encoding();
4690   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4691     Assembler::vpsraw(dst, nds, shift, vector_len);
4692   } else if (dst_enc < 16) {
4693     Assembler::vpsraw(dst, dst, shift, vector_len);
4694   } else if (nds_enc < 16) {
4695     // use nds as scratch
4696     evmovdqul(nds, dst, Assembler::AVX_512bit);
4697     Assembler::vpsraw(nds, nds, shift, vector_len);
4698     evmovdqul(dst, nds, Assembler::AVX_512bit);
4699   } else {
4700     // use nds as scratch for xmm0
4701     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4702     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4703     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4704     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4705   }
4706 }
4707 
4708 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4709   int dst_enc = dst->encoding();
4710   int nds_enc = nds->encoding();
4711   int shift_enc = shift->encoding();
4712   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4713     Assembler::vpsrlw(dst, nds, shift, vector_len);
4714   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4715     Assembler::vpsrlw(dst, dst, shift, vector_len);
4716   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4717     // use nds_enc as scratch with shift
4718     evmovdqul(nds, shift, Assembler::AVX_512bit);
4719     Assembler::vpsrlw(dst, dst, nds, vector_len);
4720   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4721     // use nds as scratch with dst
4722     evmovdqul(nds, dst, Assembler::AVX_512bit);
4723     Assembler::vpsrlw(nds, nds, shift, vector_len);
4724     evmovdqul(dst, nds, Assembler::AVX_512bit);
4725   } else if (dst_enc < 16) {
4726     // use nds to save a copy of xmm0 and hold shift
4727     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4728     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4729     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4730     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4731   } else if (nds_enc < 16) {
4732     // use nds as dest as temps
4733     evmovdqul(nds, dst, Assembler::AVX_512bit);
4734     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4735     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4736     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4737     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4738     evmovdqul(dst, nds, Assembler::AVX_512bit);
4739   } else {
4740     // worse case scenario, all regs are in the upper bank
4741     subptr(rsp, 64);
4742     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4743     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4744     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4745     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4746     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4747     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4748     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4749     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4750     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4751     addptr(rsp, 64);
4752   }
4753 }
4754 
4755 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4756   int dst_enc = dst->encoding();
4757   int nds_enc = nds->encoding();
4758   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4759     Assembler::vpsrlw(dst, nds, shift, vector_len);
4760   } else if (dst_enc < 16) {
4761     Assembler::vpsrlw(dst, dst, shift, vector_len);
4762   } else if (nds_enc < 16) {
4763     // use nds as scratch
4764     evmovdqul(nds, dst, Assembler::AVX_512bit);
4765     Assembler::vpsrlw(nds, nds, shift, vector_len);
4766     evmovdqul(dst, nds, Assembler::AVX_512bit);
4767   } else {
4768     // use nds as scratch for xmm0
4769     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4770     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4771     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4772     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4773   }
4774 }
4775 
4776 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4777   int dst_enc = dst->encoding();
4778   int nds_enc = nds->encoding();
4779   int shift_enc = shift->encoding();
4780   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4781     Assembler::vpsllw(dst, nds, shift, vector_len);
4782   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4783     Assembler::vpsllw(dst, dst, shift, vector_len);
4784   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4785     // use nds_enc as scratch with shift
4786     evmovdqul(nds, shift, Assembler::AVX_512bit);
4787     Assembler::vpsllw(dst, dst, nds, vector_len);
4788   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4789     // use nds as scratch with dst
4790     evmovdqul(nds, dst, Assembler::AVX_512bit);
4791     Assembler::vpsllw(nds, nds, shift, vector_len);
4792     evmovdqul(dst, nds, Assembler::AVX_512bit);
4793   } else if (dst_enc < 16) {
4794     // use nds to save a copy of xmm0 and hold shift
4795     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4796     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4797     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4798     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4799   } else if (nds_enc < 16) {
4800     // use nds as dest as temps
4801     evmovdqul(nds, dst, Assembler::AVX_512bit);
4802     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4803     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4804     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4805     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4806     evmovdqul(dst, nds, Assembler::AVX_512bit);
4807   } else {
4808     // worse case scenario, all regs are in the upper bank
4809     subptr(rsp, 64);
4810     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4811     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4812     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4813     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4814     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4815     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4816     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4817     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4818     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4819     addptr(rsp, 64);
4820   }
4821 }
4822 
4823 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4824   int dst_enc = dst->encoding();
4825   int nds_enc = nds->encoding();
4826   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4827     Assembler::vpsllw(dst, nds, shift, vector_len);
4828   } else if (dst_enc < 16) {
4829     Assembler::vpsllw(dst, dst, shift, vector_len);
4830   } else if (nds_enc < 16) {
4831     // use nds as scratch
4832     evmovdqul(nds, dst, Assembler::AVX_512bit);
4833     Assembler::vpsllw(nds, nds, shift, vector_len);
4834     evmovdqul(dst, nds, Assembler::AVX_512bit);
4835   } else {
4836     // use nds as scratch for xmm0
4837     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4838     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4839     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4840     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4841   }
4842 }
4843 
4844 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4845   int dst_enc = dst->encoding();
4846   int src_enc = src->encoding();
4847   if ((dst_enc < 16) && (src_enc < 16)) {
4848     Assembler::vptest(dst, src);
4849   } else if (src_enc < 16) {
4850     subptr(rsp, 64);
4851     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4852     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4853     Assembler::vptest(xmm0, src);
4854     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4855     addptr(rsp, 64);
4856   } else if (dst_enc < 16) {
4857     subptr(rsp, 64);
4858     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4859     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4860     Assembler::vptest(dst, xmm0);
4861     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4862     addptr(rsp, 64);
4863   } else {
4864     subptr(rsp, 64);
4865     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4866     subptr(rsp, 64);
4867     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4868     movdqu(xmm0, src);
4869     movdqu(xmm1, dst);
4870     Assembler::vptest(xmm1, xmm0);
4871     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4872     addptr(rsp, 64);
4873     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4874     addptr(rsp, 64);
4875   }
4876 }
4877 
4878 // This instruction exists within macros, ergo we cannot control its input
4879 // when emitted through those patterns.
4880 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4881   if (VM_Version::supports_avx512nobw()) {
4882     int dst_enc = dst->encoding();
4883     int src_enc = src->encoding();
4884     if (dst_enc == src_enc) {
4885       if (dst_enc < 16) {
4886         Assembler::punpcklbw(dst, src);
4887       } else {
4888         subptr(rsp, 64);
4889         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4890         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4891         Assembler::punpcklbw(xmm0, xmm0);
4892         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4893         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4894         addptr(rsp, 64);
4895       }
4896     } else {
4897       if ((src_enc < 16) && (dst_enc < 16)) {
4898         Assembler::punpcklbw(dst, src);
4899       } else if (src_enc < 16) {
4900         subptr(rsp, 64);
4901         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4902         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4903         Assembler::punpcklbw(xmm0, src);
4904         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4905         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4906         addptr(rsp, 64);
4907       } else if (dst_enc < 16) {
4908         subptr(rsp, 64);
4909         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4910         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4911         Assembler::punpcklbw(dst, xmm0);
4912         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4913         addptr(rsp, 64);
4914       } else {
4915         subptr(rsp, 64);
4916         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4917         subptr(rsp, 64);
4918         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4919         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4920         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4921         Assembler::punpcklbw(xmm0, xmm1);
4922         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4923         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4924         addptr(rsp, 64);
4925         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4926         addptr(rsp, 64);
4927       }
4928     }
4929   } else {
4930     Assembler::punpcklbw(dst, src);
4931   }
4932 }
4933 
4934 // This instruction exists within macros, ergo we cannot control its input
4935 // when emitted through those patterns.
4936 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
4937   if (VM_Version::supports_avx512nobw()) {
4938     int dst_enc = dst->encoding();
4939     int src_enc = src->encoding();
4940     if (dst_enc == src_enc) {
4941       if (dst_enc < 16) {
4942         Assembler::pshuflw(dst, src, mode);
4943       } else {
4944         subptr(rsp, 64);
4945         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4946         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4947         Assembler::pshuflw(xmm0, xmm0, mode);
4948         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4949         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4950         addptr(rsp, 64);
4951       }
4952     } else {
4953       if ((src_enc < 16) && (dst_enc < 16)) {
4954         Assembler::pshuflw(dst, src, mode);
4955       } else if (src_enc < 16) {
4956         subptr(rsp, 64);
4957         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4958         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4959         Assembler::pshuflw(xmm0, src, mode);
4960         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4961         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4962         addptr(rsp, 64);
4963       } else if (dst_enc < 16) {
4964         subptr(rsp, 64);
4965         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4966         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4967         Assembler::pshuflw(dst, xmm0, mode);
4968         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4969         addptr(rsp, 64);
4970       } else {
4971         subptr(rsp, 64);
4972         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4973         subptr(rsp, 64);
4974         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4975         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4976         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4977         Assembler::pshuflw(xmm0, xmm1, mode);
4978         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4979         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4980         addptr(rsp, 64);
4981         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4982         addptr(rsp, 64);
4983       }
4984     }
4985   } else {
4986     Assembler::pshuflw(dst, src, mode);
4987   }
4988 }
4989 
4990 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4991   if (reachable(src)) {
4992     vandpd(dst, nds, as_Address(src), vector_len);
4993   } else {
4994     lea(rscratch1, src);
4995     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
4996   }
4997 }
4998 
4999 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5000   if (reachable(src)) {
5001     vandps(dst, nds, as_Address(src), vector_len);
5002   } else {
5003     lea(rscratch1, src);
5004     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5005   }
5006 }
5007 
5008 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5009   if (reachable(src)) {
5010     vdivsd(dst, nds, as_Address(src));
5011   } else {
5012     lea(rscratch1, src);
5013     vdivsd(dst, nds, Address(rscratch1, 0));
5014   }
5015 }
5016 
5017 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5018   if (reachable(src)) {
5019     vdivss(dst, nds, as_Address(src));
5020   } else {
5021     lea(rscratch1, src);
5022     vdivss(dst, nds, Address(rscratch1, 0));
5023   }
5024 }
5025 
5026 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5027   if (reachable(src)) {
5028     vmulsd(dst, nds, as_Address(src));
5029   } else {
5030     lea(rscratch1, src);
5031     vmulsd(dst, nds, Address(rscratch1, 0));
5032   }
5033 }
5034 
5035 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5036   if (reachable(src)) {
5037     vmulss(dst, nds, as_Address(src));
5038   } else {
5039     lea(rscratch1, src);
5040     vmulss(dst, nds, Address(rscratch1, 0));
5041   }
5042 }
5043 
5044 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5045   if (reachable(src)) {
5046     vsubsd(dst, nds, as_Address(src));
5047   } else {
5048     lea(rscratch1, src);
5049     vsubsd(dst, nds, Address(rscratch1, 0));
5050   }
5051 }
5052 
5053 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5054   if (reachable(src)) {
5055     vsubss(dst, nds, as_Address(src));
5056   } else {
5057     lea(rscratch1, src);
5058     vsubss(dst, nds, Address(rscratch1, 0));
5059   }
5060 }
5061 
5062 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5063   int nds_enc = nds->encoding();
5064   int dst_enc = dst->encoding();
5065   bool dst_upper_bank = (dst_enc > 15);
5066   bool nds_upper_bank = (nds_enc > 15);
5067   if (VM_Version::supports_avx512novl() &&
5068       (nds_upper_bank || dst_upper_bank)) {
5069     if (dst_upper_bank) {
5070       subptr(rsp, 64);
5071       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5072       movflt(xmm0, nds);
5073       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5074       movflt(dst, xmm0);
5075       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5076       addptr(rsp, 64);
5077     } else {
5078       movflt(dst, nds);
5079       vxorps(dst, dst, src, Assembler::AVX_128bit);
5080     }
5081   } else {
5082     vxorps(dst, nds, src, Assembler::AVX_128bit);
5083   }
5084 }
5085 
5086 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5087   int nds_enc = nds->encoding();
5088   int dst_enc = dst->encoding();
5089   bool dst_upper_bank = (dst_enc > 15);
5090   bool nds_upper_bank = (nds_enc > 15);
5091   if (VM_Version::supports_avx512novl() &&
5092       (nds_upper_bank || dst_upper_bank)) {
5093     if (dst_upper_bank) {
5094       subptr(rsp, 64);
5095       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5096       movdbl(xmm0, nds);
5097       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5098       movdbl(dst, xmm0);
5099       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5100       addptr(rsp, 64);
5101     } else {
5102       movdbl(dst, nds);
5103       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5104     }
5105   } else {
5106     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5107   }
5108 }
5109 
5110 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5111   if (reachable(src)) {
5112     vxorpd(dst, nds, as_Address(src), vector_len);
5113   } else {
5114     lea(rscratch1, src);
5115     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5116   }
5117 }
5118 
5119 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5120   if (reachable(src)) {
5121     vxorps(dst, nds, as_Address(src), vector_len);
5122   } else {
5123     lea(rscratch1, src);
5124     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5125   }
5126 }
5127 
5128 
5129 void MacroAssembler::resolve_jobject(Register value,
5130                                      Register thread,
5131                                      Register tmp) {
5132   BarrierSetCodeGen *code_gen = Universe::heap()->barrier_set()->code_gen();
5133   assert_different_registers(value, thread, tmp);
5134   Label done, not_weak;
5135   testptr(value, value);
5136   jcc(Assembler::zero, done);                // Use NULL as-is.
5137   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5138   jcc(Assembler::zero, not_weak);
5139   // Resolve jweak.
5140   code_gen->load_at(this, ACCESS_ON_ROOT | GC_ACCESS_ON_PHANTOM, T_OBJECT,
5141                     value, Address(value, -JNIHandles::weak_tag_value), tmp);
5142   verify_oop(value);
5143   jmp(done);
5144   bind(not_weak);
5145   // Resolve (untagged) jobject.
5146   code_gen->load_at(this, ACCESS_ON_ROOT | GC_ACCESS_ON_STRONG, T_OBJECT,
5147                     value, Address(value, 0), tmp);
5148   verify_oop(value);
5149   bind(done);
5150 }
5151 
5152 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5153   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5154 }
5155 
5156 // Force generation of a 4 byte immediate value even if it fits into 8bit
5157 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5158   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5159 }
5160 
5161 void MacroAssembler::subptr(Register dst, Register src) {
5162   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5163 }
5164 
5165 // C++ bool manipulation
5166 void MacroAssembler::testbool(Register dst) {
5167   if(sizeof(bool) == 1)
5168     testb(dst, 0xff);
5169   else if(sizeof(bool) == 2) {
5170     // testw implementation needed for two byte bools
5171     ShouldNotReachHere();
5172   } else if(sizeof(bool) == 4)
5173     testl(dst, dst);
5174   else
5175     // unsupported
5176     ShouldNotReachHere();
5177 }
5178 
5179 void MacroAssembler::testptr(Register dst, Register src) {
5180   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5181 }
5182 
5183 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5184 void MacroAssembler::tlab_allocate(Register obj,
5185                                    Register var_size_in_bytes,
5186                                    int con_size_in_bytes,
5187                                    Register t1,
5188                                    Register t2,
5189                                    Label& slow_case) {
5190   assert_different_registers(obj, t1, t2);
5191   assert_different_registers(obj, var_size_in_bytes, t1);
5192   Register end = t2;
5193   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5194 
5195   verify_tlab();
5196 
5197   NOT_LP64(get_thread(thread));
5198 
5199   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5200   if (var_size_in_bytes == noreg) {
5201     lea(end, Address(obj, con_size_in_bytes));
5202   } else {
5203     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5204   }
5205   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5206   jcc(Assembler::above, slow_case);
5207 
5208   // update the tlab top pointer
5209   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5210 
5211   // recover var_size_in_bytes if necessary
5212   if (var_size_in_bytes == end) {
5213     subptr(var_size_in_bytes, obj);
5214   }
5215   verify_tlab();
5216 }
5217 
5218 // Preserves rbx, and rdx.
5219 Register MacroAssembler::tlab_refill(Label& retry,
5220                                      Label& try_eden,
5221                                      Label& slow_case) {
5222   Register top = rax;
5223   Register t1  = rcx; // object size
5224   Register t2  = rsi;
5225   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5226   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5227   Label do_refill, discard_tlab;
5228 
5229   if (!Universe::heap()->supports_inline_contig_alloc()) {
5230     // No allocation in the shared eden.
5231     jmp(slow_case);
5232   }
5233 
5234   NOT_LP64(get_thread(thread_reg));
5235 
5236   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5237   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5238 
5239   // calculate amount of free space
5240   subptr(t1, top);
5241   shrptr(t1, LogHeapWordSize);
5242 
5243   // Retain tlab and allocate object in shared space if
5244   // the amount free in the tlab is too large to discard.
5245   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5246   jcc(Assembler::lessEqual, discard_tlab);
5247 
5248   // Retain
5249   // %%% yuck as movptr...
5250   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5251   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5252   if (TLABStats) {
5253     // increment number of slow_allocations
5254     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5255   }
5256   jmp(try_eden);
5257 
5258   bind(discard_tlab);
5259   if (TLABStats) {
5260     // increment number of refills
5261     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5262     // accumulate wastage -- t1 is amount free in tlab
5263     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5264   }
5265 
5266   // if tlab is currently allocated (top or end != null) then
5267   // fill [top, end + alignment_reserve) with array object
5268   testptr(top, top);
5269   jcc(Assembler::zero, do_refill);
5270 
5271   // set up the mark word
5272   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5273   // set the length to the remaining space
5274   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5275   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5276   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5277   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5278   // set klass to intArrayKlass
5279   // dubious reloc why not an oop reloc?
5280   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5281   // store klass last.  concurrent gcs assumes klass length is valid if
5282   // klass field is not null.
5283   store_klass(top, t1);
5284 
5285   movptr(t1, top);
5286   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5287   incr_allocated_bytes(thread_reg, t1, 0);
5288 
5289   // refill the tlab with an eden allocation
5290   bind(do_refill);
5291   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5292   shlptr(t1, LogHeapWordSize);
5293   // allocate new tlab, address returned in top
5294   eden_allocate(top, t1, 0, t2, slow_case);
5295 
5296   // Check that t1 was preserved in eden_allocate.
5297 #ifdef ASSERT
5298   if (UseTLAB) {
5299     Label ok;
5300     Register tsize = rsi;
5301     assert_different_registers(tsize, thread_reg, t1);
5302     push(tsize);
5303     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5304     shlptr(tsize, LogHeapWordSize);
5305     cmpptr(t1, tsize);
5306     jcc(Assembler::equal, ok);
5307     STOP("assert(t1 != tlab size)");
5308     should_not_reach_here();
5309 
5310     bind(ok);
5311     pop(tsize);
5312   }
5313 #endif
5314   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5315   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5316   addptr(top, t1);
5317   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5318   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5319 
5320   if (ZeroTLAB) {
5321     // This is a fast TLAB refill, therefore the GC is not notified of it.
5322     // So compiled code must fill the new TLAB with zeroes.
5323     movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5324     zero_memory(top, t1, 0, t2);
5325   }
5326 
5327   verify_tlab();
5328   jmp(retry);
5329 
5330   return thread_reg; // for use by caller
5331 }
5332 
5333 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5334 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5335   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5336   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5337   Label done;
5338 
5339   testptr(length_in_bytes, length_in_bytes);
5340   jcc(Assembler::zero, done);
5341 
5342   // initialize topmost word, divide index by 2, check if odd and test if zero
5343   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5344 #ifdef ASSERT
5345   {
5346     Label L;
5347     testptr(length_in_bytes, BytesPerWord - 1);
5348     jcc(Assembler::zero, L);
5349     stop("length must be a multiple of BytesPerWord");
5350     bind(L);
5351   }
5352 #endif
5353   Register index = length_in_bytes;
5354   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5355   if (UseIncDec) {
5356     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5357   } else {
5358     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5359     shrptr(index, 1);
5360   }
5361 #ifndef _LP64
5362   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5363   {
5364     Label even;
5365     // note: if index was a multiple of 8, then it cannot
5366     //       be 0 now otherwise it must have been 0 before
5367     //       => if it is even, we don't need to check for 0 again
5368     jcc(Assembler::carryClear, even);
5369     // clear topmost word (no jump would be needed if conditional assignment worked here)
5370     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5371     // index could be 0 now, must check again
5372     jcc(Assembler::zero, done);
5373     bind(even);
5374   }
5375 #endif // !_LP64
5376   // initialize remaining object fields: index is a multiple of 2 now
5377   {
5378     Label loop;
5379     bind(loop);
5380     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5381     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5382     decrement(index);
5383     jcc(Assembler::notZero, loop);
5384   }
5385 
5386   bind(done);
5387 }
5388 
5389 void MacroAssembler::incr_allocated_bytes(Register thread,
5390                                           Register var_size_in_bytes,
5391                                           int con_size_in_bytes,
5392                                           Register t1) {
5393   if (!thread->is_valid()) {
5394 #ifdef _LP64
5395     thread = r15_thread;
5396 #else
5397     assert(t1->is_valid(), "need temp reg");
5398     thread = t1;
5399     get_thread(thread);
5400 #endif
5401   }
5402 
5403 #ifdef _LP64
5404   if (var_size_in_bytes->is_valid()) {
5405     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5406   } else {
5407     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5408   }
5409 #else
5410   if (var_size_in_bytes->is_valid()) {
5411     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5412   } else {
5413     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5414   }
5415   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5416 #endif
5417 }
5418 
5419 // Look up the method for a megamorphic invokeinterface call.
5420 // The target method is determined by <intf_klass, itable_index>.
5421 // The receiver klass is in recv_klass.
5422 // On success, the result will be in method_result, and execution falls through.
5423 // On failure, execution transfers to the given label.
5424 void MacroAssembler::lookup_interface_method(Register recv_klass,
5425                                              Register intf_klass,
5426                                              RegisterOrConstant itable_index,
5427                                              Register method_result,
5428                                              Register scan_temp,
5429                                              Label& L_no_such_interface) {
5430   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5431   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5432          "caller must use same register for non-constant itable index as for method");
5433 
5434   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5435   int vtable_base = in_bytes(Klass::vtable_start_offset());
5436   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5437   int scan_step   = itableOffsetEntry::size() * wordSize;
5438   int vte_size    = vtableEntry::size_in_bytes();
5439   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5440   assert(vte_size == wordSize, "else adjust times_vte_scale");
5441 
5442   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5443 
5444   // %%% Could store the aligned, prescaled offset in the klassoop.
5445   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5446 
5447   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5448   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5449   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5450 
5451   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5452   //   if (scan->interface() == intf) {
5453   //     result = (klass + scan->offset() + itable_index);
5454   //   }
5455   // }
5456   Label search, found_method;
5457 
5458   for (int peel = 1; peel >= 0; peel--) {
5459     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5460     cmpptr(intf_klass, method_result);
5461 
5462     if (peel) {
5463       jccb(Assembler::equal, found_method);
5464     } else {
5465       jccb(Assembler::notEqual, search);
5466       // (invert the test to fall through to found_method...)
5467     }
5468 
5469     if (!peel)  break;
5470 
5471     bind(search);
5472 
5473     // Check that the previous entry is non-null.  A null entry means that
5474     // the receiver class doesn't implement the interface, and wasn't the
5475     // same as when the caller was compiled.
5476     testptr(method_result, method_result);
5477     jcc(Assembler::zero, L_no_such_interface);
5478     addptr(scan_temp, scan_step);
5479   }
5480 
5481   bind(found_method);
5482 
5483   // Got a hit.
5484   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5485   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5486 }
5487 
5488 
5489 // virtual method calling
5490 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5491                                            RegisterOrConstant vtable_index,
5492                                            Register method_result) {
5493   const int base = in_bytes(Klass::vtable_start_offset());
5494   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5495   Address vtable_entry_addr(recv_klass,
5496                             vtable_index, Address::times_ptr,
5497                             base + vtableEntry::method_offset_in_bytes());
5498   movptr(method_result, vtable_entry_addr);
5499 }
5500 
5501 
5502 void MacroAssembler::check_klass_subtype(Register sub_klass,
5503                            Register super_klass,
5504                            Register temp_reg,
5505                            Label& L_success) {
5506   Label L_failure;
5507   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5508   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5509   bind(L_failure);
5510 }
5511 
5512 
5513 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5514                                                    Register super_klass,
5515                                                    Register temp_reg,
5516                                                    Label* L_success,
5517                                                    Label* L_failure,
5518                                                    Label* L_slow_path,
5519                                         RegisterOrConstant super_check_offset) {
5520   assert_different_registers(sub_klass, super_klass, temp_reg);
5521   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5522   if (super_check_offset.is_register()) {
5523     assert_different_registers(sub_klass, super_klass,
5524                                super_check_offset.as_register());
5525   } else if (must_load_sco) {
5526     assert(temp_reg != noreg, "supply either a temp or a register offset");
5527   }
5528 
5529   Label L_fallthrough;
5530   int label_nulls = 0;
5531   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5532   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5533   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5534   assert(label_nulls <= 1, "at most one NULL in the batch");
5535 
5536   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5537   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5538   Address super_check_offset_addr(super_klass, sco_offset);
5539 
5540   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5541   // range of a jccb.  If this routine grows larger, reconsider at
5542   // least some of these.
5543 #define local_jcc(assembler_cond, label)                                \
5544   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5545   else                             jcc( assembler_cond, label) /*omit semi*/
5546 
5547   // Hacked jmp, which may only be used just before L_fallthrough.
5548 #define final_jmp(label)                                                \
5549   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5550   else                            jmp(label)                /*omit semi*/
5551 
5552   // If the pointers are equal, we are done (e.g., String[] elements).
5553   // This self-check enables sharing of secondary supertype arrays among
5554   // non-primary types such as array-of-interface.  Otherwise, each such
5555   // type would need its own customized SSA.
5556   // We move this check to the front of the fast path because many
5557   // type checks are in fact trivially successful in this manner,
5558   // so we get a nicely predicted branch right at the start of the check.
5559   cmpptr(sub_klass, super_klass);
5560   local_jcc(Assembler::equal, *L_success);
5561 
5562   // Check the supertype display:
5563   if (must_load_sco) {
5564     // Positive movl does right thing on LP64.
5565     movl(temp_reg, super_check_offset_addr);
5566     super_check_offset = RegisterOrConstant(temp_reg);
5567   }
5568   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5569   cmpptr(super_klass, super_check_addr); // load displayed supertype
5570 
5571   // This check has worked decisively for primary supers.
5572   // Secondary supers are sought in the super_cache ('super_cache_addr').
5573   // (Secondary supers are interfaces and very deeply nested subtypes.)
5574   // This works in the same check above because of a tricky aliasing
5575   // between the super_cache and the primary super display elements.
5576   // (The 'super_check_addr' can address either, as the case requires.)
5577   // Note that the cache is updated below if it does not help us find
5578   // what we need immediately.
5579   // So if it was a primary super, we can just fail immediately.
5580   // Otherwise, it's the slow path for us (no success at this point).
5581 
5582   if (super_check_offset.is_register()) {
5583     local_jcc(Assembler::equal, *L_success);
5584     cmpl(super_check_offset.as_register(), sc_offset);
5585     if (L_failure == &L_fallthrough) {
5586       local_jcc(Assembler::equal, *L_slow_path);
5587     } else {
5588       local_jcc(Assembler::notEqual, *L_failure);
5589       final_jmp(*L_slow_path);
5590     }
5591   } else if (super_check_offset.as_constant() == sc_offset) {
5592     // Need a slow path; fast failure is impossible.
5593     if (L_slow_path == &L_fallthrough) {
5594       local_jcc(Assembler::equal, *L_success);
5595     } else {
5596       local_jcc(Assembler::notEqual, *L_slow_path);
5597       final_jmp(*L_success);
5598     }
5599   } else {
5600     // No slow path; it's a fast decision.
5601     if (L_failure == &L_fallthrough) {
5602       local_jcc(Assembler::equal, *L_success);
5603     } else {
5604       local_jcc(Assembler::notEqual, *L_failure);
5605       final_jmp(*L_success);
5606     }
5607   }
5608 
5609   bind(L_fallthrough);
5610 
5611 #undef local_jcc
5612 #undef final_jmp
5613 }
5614 
5615 
5616 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5617                                                    Register super_klass,
5618                                                    Register temp_reg,
5619                                                    Register temp2_reg,
5620                                                    Label* L_success,
5621                                                    Label* L_failure,
5622                                                    bool set_cond_codes) {
5623   assert_different_registers(sub_klass, super_klass, temp_reg);
5624   if (temp2_reg != noreg)
5625     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5626 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5627 
5628   Label L_fallthrough;
5629   int label_nulls = 0;
5630   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5631   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5632   assert(label_nulls <= 1, "at most one NULL in the batch");
5633 
5634   // a couple of useful fields in sub_klass:
5635   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5636   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5637   Address secondary_supers_addr(sub_klass, ss_offset);
5638   Address super_cache_addr(     sub_klass, sc_offset);
5639 
5640   // Do a linear scan of the secondary super-klass chain.
5641   // This code is rarely used, so simplicity is a virtue here.
5642   // The repne_scan instruction uses fixed registers, which we must spill.
5643   // Don't worry too much about pre-existing connections with the input regs.
5644 
5645   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5646   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5647 
5648   // Get super_klass value into rax (even if it was in rdi or rcx).
5649   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5650   if (super_klass != rax || UseCompressedOops) {
5651     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5652     mov(rax, super_klass);
5653   }
5654   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5655   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5656 
5657 #ifndef PRODUCT
5658   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5659   ExternalAddress pst_counter_addr((address) pst_counter);
5660   NOT_LP64(  incrementl(pst_counter_addr) );
5661   LP64_ONLY( lea(rcx, pst_counter_addr) );
5662   LP64_ONLY( incrementl(Address(rcx, 0)) );
5663 #endif //PRODUCT
5664 
5665   // We will consult the secondary-super array.
5666   movptr(rdi, secondary_supers_addr);
5667   // Load the array length.  (Positive movl does right thing on LP64.)
5668   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
5669   // Skip to start of data.
5670   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
5671 
5672   // Scan RCX words at [RDI] for an occurrence of RAX.
5673   // Set NZ/Z based on last compare.
5674   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
5675   // not change flags (only scas instruction which is repeated sets flags).
5676   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
5677 
5678     testptr(rax,rax); // Set Z = 0
5679     repne_scan();
5680 
5681   // Unspill the temp. registers:
5682   if (pushed_rdi)  pop(rdi);
5683   if (pushed_rcx)  pop(rcx);
5684   if (pushed_rax)  pop(rax);
5685 
5686   if (set_cond_codes) {
5687     // Special hack for the AD files:  rdi is guaranteed non-zero.
5688     assert(!pushed_rdi, "rdi must be left non-NULL");
5689     // Also, the condition codes are properly set Z/NZ on succeed/failure.
5690   }
5691 
5692   if (L_failure == &L_fallthrough)
5693         jccb(Assembler::notEqual, *L_failure);
5694   else  jcc(Assembler::notEqual, *L_failure);
5695 
5696   // Success.  Cache the super we found and proceed in triumph.
5697   movptr(super_cache_addr, super_klass);
5698 
5699   if (L_success != &L_fallthrough) {
5700     jmp(*L_success);
5701   }
5702 
5703 #undef IS_A_TEMP
5704 
5705   bind(L_fallthrough);
5706 }
5707 
5708 
5709 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
5710   if (VM_Version::supports_cmov()) {
5711     cmovl(cc, dst, src);
5712   } else {
5713     Label L;
5714     jccb(negate_condition(cc), L);
5715     movl(dst, src);
5716     bind(L);
5717   }
5718 }
5719 
5720 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
5721   if (VM_Version::supports_cmov()) {
5722     cmovl(cc, dst, src);
5723   } else {
5724     Label L;
5725     jccb(negate_condition(cc), L);
5726     movl(dst, src);
5727     bind(L);
5728   }
5729 }
5730 
5731 void MacroAssembler::verify_oop(Register reg, const char* s) {
5732   if (!VerifyOops) return;
5733 
5734   // Pass register number to verify_oop_subroutine
5735   const char* b = NULL;
5736   {
5737     ResourceMark rm;
5738     stringStream ss;
5739     ss.print("verify_oop: %s: %s", reg->name(), s);
5740     b = code_string(ss.as_string());
5741   }
5742   BLOCK_COMMENT("verify_oop {");
5743 #ifdef _LP64
5744   push(rscratch1);                    // save r10, trashed by movptr()
5745 #endif
5746   push(rax);                          // save rax,
5747   push(reg);                          // pass register argument
5748   ExternalAddress buffer((address) b);
5749   // avoid using pushptr, as it modifies scratch registers
5750   // and our contract is not to modify anything
5751   movptr(rax, buffer.addr());
5752   push(rax);
5753   // call indirectly to solve generation ordering problem
5754   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5755   call(rax);
5756   // Caller pops the arguments (oop, message) and restores rax, r10
5757   BLOCK_COMMENT("} verify_oop");
5758 }
5759 
5760 
5761 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
5762                                                       Register tmp,
5763                                                       int offset) {
5764   intptr_t value = *delayed_value_addr;
5765   if (value != 0)
5766     return RegisterOrConstant(value + offset);
5767 
5768   // load indirectly to solve generation ordering problem
5769   movptr(tmp, ExternalAddress((address) delayed_value_addr));
5770 
5771 #ifdef ASSERT
5772   { Label L;
5773     testptr(tmp, tmp);
5774     if (WizardMode) {
5775       const char* buf = NULL;
5776       {
5777         ResourceMark rm;
5778         stringStream ss;
5779         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
5780         buf = code_string(ss.as_string());
5781       }
5782       jcc(Assembler::notZero, L);
5783       STOP(buf);
5784     } else {
5785       jccb(Assembler::notZero, L);
5786       hlt();
5787     }
5788     bind(L);
5789   }
5790 #endif
5791 
5792   if (offset != 0)
5793     addptr(tmp, offset);
5794 
5795   return RegisterOrConstant(tmp);
5796 }
5797 
5798 
5799 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
5800                                          int extra_slot_offset) {
5801   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
5802   int stackElementSize = Interpreter::stackElementSize;
5803   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
5804 #ifdef ASSERT
5805   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
5806   assert(offset1 - offset == stackElementSize, "correct arithmetic");
5807 #endif
5808   Register             scale_reg    = noreg;
5809   Address::ScaleFactor scale_factor = Address::no_scale;
5810   if (arg_slot.is_constant()) {
5811     offset += arg_slot.as_constant() * stackElementSize;
5812   } else {
5813     scale_reg    = arg_slot.as_register();
5814     scale_factor = Address::times(stackElementSize);
5815   }
5816   offset += wordSize;           // return PC is on stack
5817   return Address(rsp, scale_reg, scale_factor, offset);
5818 }
5819 
5820 
5821 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
5822   if (!VerifyOops) return;
5823 
5824   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
5825   // Pass register number to verify_oop_subroutine
5826   const char* b = NULL;
5827   {
5828     ResourceMark rm;
5829     stringStream ss;
5830     ss.print("verify_oop_addr: %s", s);
5831     b = code_string(ss.as_string());
5832   }
5833 #ifdef _LP64
5834   push(rscratch1);                    // save r10, trashed by movptr()
5835 #endif
5836   push(rax);                          // save rax,
5837   // addr may contain rsp so we will have to adjust it based on the push
5838   // we just did (and on 64 bit we do two pushes)
5839   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
5840   // stores rax into addr which is backwards of what was intended.
5841   if (addr.uses(rsp)) {
5842     lea(rax, addr);
5843     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
5844   } else {
5845     pushptr(addr);
5846   }
5847 
5848   ExternalAddress buffer((address) b);
5849   // pass msg argument
5850   // avoid using pushptr, as it modifies scratch registers
5851   // and our contract is not to modify anything
5852   movptr(rax, buffer.addr());
5853   push(rax);
5854 
5855   // call indirectly to solve generation ordering problem
5856   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5857   call(rax);
5858   // Caller pops the arguments (addr, message) and restores rax, r10.
5859 }
5860 
5861 void MacroAssembler::verify_tlab() {
5862 #ifdef ASSERT
5863   if (UseTLAB && VerifyOops) {
5864     Label next, ok;
5865     Register t1 = rsi;
5866     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
5867 
5868     push(t1);
5869     NOT_LP64(push(thread_reg));
5870     NOT_LP64(get_thread(thread_reg));
5871 
5872     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5873     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5874     jcc(Assembler::aboveEqual, next);
5875     STOP("assert(top >= start)");
5876     should_not_reach_here();
5877 
5878     bind(next);
5879     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5880     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5881     jcc(Assembler::aboveEqual, ok);
5882     STOP("assert(top <= end)");
5883     should_not_reach_here();
5884 
5885     bind(ok);
5886     NOT_LP64(pop(thread_reg));
5887     pop(t1);
5888   }
5889 #endif
5890 }
5891 
5892 class ControlWord {
5893  public:
5894   int32_t _value;
5895 
5896   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
5897   int  precision_control() const       { return  (_value >>  8) & 3      ; }
5898   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5899   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5900   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5901   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5902   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5903   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5904 
5905   void print() const {
5906     // rounding control
5907     const char* rc;
5908     switch (rounding_control()) {
5909       case 0: rc = "round near"; break;
5910       case 1: rc = "round down"; break;
5911       case 2: rc = "round up  "; break;
5912       case 3: rc = "chop      "; break;
5913     };
5914     // precision control
5915     const char* pc;
5916     switch (precision_control()) {
5917       case 0: pc = "24 bits "; break;
5918       case 1: pc = "reserved"; break;
5919       case 2: pc = "53 bits "; break;
5920       case 3: pc = "64 bits "; break;
5921     };
5922     // flags
5923     char f[9];
5924     f[0] = ' ';
5925     f[1] = ' ';
5926     f[2] = (precision   ()) ? 'P' : 'p';
5927     f[3] = (underflow   ()) ? 'U' : 'u';
5928     f[4] = (overflow    ()) ? 'O' : 'o';
5929     f[5] = (zero_divide ()) ? 'Z' : 'z';
5930     f[6] = (denormalized()) ? 'D' : 'd';
5931     f[7] = (invalid     ()) ? 'I' : 'i';
5932     f[8] = '\x0';
5933     // output
5934     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
5935   }
5936 
5937 };
5938 
5939 class StatusWord {
5940  public:
5941   int32_t _value;
5942 
5943   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
5944   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
5945   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
5946   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
5947   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
5948   int  top() const                     { return  (_value >> 11) & 7      ; }
5949   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
5950   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
5951   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5952   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5953   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5954   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5955   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5956   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5957 
5958   void print() const {
5959     // condition codes
5960     char c[5];
5961     c[0] = (C3()) ? '3' : '-';
5962     c[1] = (C2()) ? '2' : '-';
5963     c[2] = (C1()) ? '1' : '-';
5964     c[3] = (C0()) ? '0' : '-';
5965     c[4] = '\x0';
5966     // flags
5967     char f[9];
5968     f[0] = (error_status()) ? 'E' : '-';
5969     f[1] = (stack_fault ()) ? 'S' : '-';
5970     f[2] = (precision   ()) ? 'P' : '-';
5971     f[3] = (underflow   ()) ? 'U' : '-';
5972     f[4] = (overflow    ()) ? 'O' : '-';
5973     f[5] = (zero_divide ()) ? 'Z' : '-';
5974     f[6] = (denormalized()) ? 'D' : '-';
5975     f[7] = (invalid     ()) ? 'I' : '-';
5976     f[8] = '\x0';
5977     // output
5978     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
5979   }
5980 
5981 };
5982 
5983 class TagWord {
5984  public:
5985   int32_t _value;
5986 
5987   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
5988 
5989   void print() const {
5990     printf("%04x", _value & 0xFFFF);
5991   }
5992 
5993 };
5994 
5995 class FPU_Register {
5996  public:
5997   int32_t _m0;
5998   int32_t _m1;
5999   int16_t _ex;
6000 
6001   bool is_indefinite() const           {
6002     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6003   }
6004 
6005   void print() const {
6006     char  sign = (_ex < 0) ? '-' : '+';
6007     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6008     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6009   };
6010 
6011 };
6012 
6013 class FPU_State {
6014  public:
6015   enum {
6016     register_size       = 10,
6017     number_of_registers =  8,
6018     register_mask       =  7
6019   };
6020 
6021   ControlWord  _control_word;
6022   StatusWord   _status_word;
6023   TagWord      _tag_word;
6024   int32_t      _error_offset;
6025   int32_t      _error_selector;
6026   int32_t      _data_offset;
6027   int32_t      _data_selector;
6028   int8_t       _register[register_size * number_of_registers];
6029 
6030   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6031   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6032 
6033   const char* tag_as_string(int tag) const {
6034     switch (tag) {
6035       case 0: return "valid";
6036       case 1: return "zero";
6037       case 2: return "special";
6038       case 3: return "empty";
6039     }
6040     ShouldNotReachHere();
6041     return NULL;
6042   }
6043 
6044   void print() const {
6045     // print computation registers
6046     { int t = _status_word.top();
6047       for (int i = 0; i < number_of_registers; i++) {
6048         int j = (i - t) & register_mask;
6049         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6050         st(j)->print();
6051         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6052       }
6053     }
6054     printf("\n");
6055     // print control registers
6056     printf("ctrl = "); _control_word.print(); printf("\n");
6057     printf("stat = "); _status_word .print(); printf("\n");
6058     printf("tags = "); _tag_word    .print(); printf("\n");
6059   }
6060 
6061 };
6062 
6063 class Flag_Register {
6064  public:
6065   int32_t _value;
6066 
6067   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6068   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6069   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6070   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6071   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6072   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6073   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6074 
6075   void print() const {
6076     // flags
6077     char f[8];
6078     f[0] = (overflow       ()) ? 'O' : '-';
6079     f[1] = (direction      ()) ? 'D' : '-';
6080     f[2] = (sign           ()) ? 'S' : '-';
6081     f[3] = (zero           ()) ? 'Z' : '-';
6082     f[4] = (auxiliary_carry()) ? 'A' : '-';
6083     f[5] = (parity         ()) ? 'P' : '-';
6084     f[6] = (carry          ()) ? 'C' : '-';
6085     f[7] = '\x0';
6086     // output
6087     printf("%08x  flags = %s", _value, f);
6088   }
6089 
6090 };
6091 
6092 class IU_Register {
6093  public:
6094   int32_t _value;
6095 
6096   void print() const {
6097     printf("%08x  %11d", _value, _value);
6098   }
6099 
6100 };
6101 
6102 class IU_State {
6103  public:
6104   Flag_Register _eflags;
6105   IU_Register   _rdi;
6106   IU_Register   _rsi;
6107   IU_Register   _rbp;
6108   IU_Register   _rsp;
6109   IU_Register   _rbx;
6110   IU_Register   _rdx;
6111   IU_Register   _rcx;
6112   IU_Register   _rax;
6113 
6114   void print() const {
6115     // computation registers
6116     printf("rax,  = "); _rax.print(); printf("\n");
6117     printf("rbx,  = "); _rbx.print(); printf("\n");
6118     printf("rcx  = "); _rcx.print(); printf("\n");
6119     printf("rdx  = "); _rdx.print(); printf("\n");
6120     printf("rdi  = "); _rdi.print(); printf("\n");
6121     printf("rsi  = "); _rsi.print(); printf("\n");
6122     printf("rbp,  = "); _rbp.print(); printf("\n");
6123     printf("rsp  = "); _rsp.print(); printf("\n");
6124     printf("\n");
6125     // control registers
6126     printf("flgs = "); _eflags.print(); printf("\n");
6127   }
6128 };
6129 
6130 
6131 class CPU_State {
6132  public:
6133   FPU_State _fpu_state;
6134   IU_State  _iu_state;
6135 
6136   void print() const {
6137     printf("--------------------------------------------------\n");
6138     _iu_state .print();
6139     printf("\n");
6140     _fpu_state.print();
6141     printf("--------------------------------------------------\n");
6142   }
6143 
6144 };
6145 
6146 
6147 static void _print_CPU_state(CPU_State* state) {
6148   state->print();
6149 };
6150 
6151 
6152 void MacroAssembler::print_CPU_state() {
6153   push_CPU_state();
6154   push(rsp);                // pass CPU state
6155   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6156   addptr(rsp, wordSize);       // discard argument
6157   pop_CPU_state();
6158 }
6159 
6160 
6161 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6162   static int counter = 0;
6163   FPU_State* fs = &state->_fpu_state;
6164   counter++;
6165   // For leaf calls, only verify that the top few elements remain empty.
6166   // We only need 1 empty at the top for C2 code.
6167   if( stack_depth < 0 ) {
6168     if( fs->tag_for_st(7) != 3 ) {
6169       printf("FPR7 not empty\n");
6170       state->print();
6171       assert(false, "error");
6172       return false;
6173     }
6174     return true;                // All other stack states do not matter
6175   }
6176 
6177   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6178          "bad FPU control word");
6179 
6180   // compute stack depth
6181   int i = 0;
6182   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6183   int d = i;
6184   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6185   // verify findings
6186   if (i != FPU_State::number_of_registers) {
6187     // stack not contiguous
6188     printf("%s: stack not contiguous at ST%d\n", s, i);
6189     state->print();
6190     assert(false, "error");
6191     return false;
6192   }
6193   // check if computed stack depth corresponds to expected stack depth
6194   if (stack_depth < 0) {
6195     // expected stack depth is -stack_depth or less
6196     if (d > -stack_depth) {
6197       // too many elements on the stack
6198       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6199       state->print();
6200       assert(false, "error");
6201       return false;
6202     }
6203   } else {
6204     // expected stack depth is stack_depth
6205     if (d != stack_depth) {
6206       // wrong stack depth
6207       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6208       state->print();
6209       assert(false, "error");
6210       return false;
6211     }
6212   }
6213   // everything is cool
6214   return true;
6215 }
6216 
6217 
6218 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6219   if (!VerifyFPU) return;
6220   push_CPU_state();
6221   push(rsp);                // pass CPU state
6222   ExternalAddress msg((address) s);
6223   // pass message string s
6224   pushptr(msg.addr());
6225   push(stack_depth);        // pass stack depth
6226   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6227   addptr(rsp, 3 * wordSize);   // discard arguments
6228   // check for error
6229   { Label L;
6230     testl(rax, rax);
6231     jcc(Assembler::notZero, L);
6232     int3();                  // break if error condition
6233     bind(L);
6234   }
6235   pop_CPU_state();
6236 }
6237 
6238 void MacroAssembler::restore_cpu_control_state_after_jni() {
6239   // Either restore the MXCSR register after returning from the JNI Call
6240   // or verify that it wasn't changed (with -Xcheck:jni flag).
6241   if (VM_Version::supports_sse()) {
6242     if (RestoreMXCSROnJNICalls) {
6243       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6244     } else if (CheckJNICalls) {
6245       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6246     }
6247   }
6248   if (VM_Version::supports_avx()) {
6249     // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6250     vzeroupper();
6251   }
6252 
6253 #ifndef _LP64
6254   // Either restore the x87 floating pointer control word after returning
6255   // from the JNI call or verify that it wasn't changed.
6256   if (CheckJNICalls) {
6257     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6258   }
6259 #endif // _LP64
6260 }
6261 
6262 void MacroAssembler::load_mirror(Register mirror, Register method) {
6263   // get mirror
6264   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6265   movptr(mirror, Address(method, Method::const_offset()));
6266   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6267   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6268   movptr(mirror, Address(mirror, mirror_offset));
6269 }
6270 
6271 void MacroAssembler::load_klass(Register dst, Register src) {
6272 #ifdef _LP64
6273   if (UseCompressedClassPointers) {
6274     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6275     decode_klass_not_null(dst);
6276   } else
6277 #endif
6278     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6279 }
6280 
6281 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6282   load_klass(dst, src);
6283   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6284 }
6285 
6286 void MacroAssembler::store_klass(Register dst, Register src) {
6287 #ifdef _LP64
6288   if (UseCompressedClassPointers) {
6289     encode_klass_not_null(src);
6290     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6291   } else
6292 #endif
6293     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6294 }
6295 
6296 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6297 #ifdef _LP64
6298   // FIXME: Must change all places where we try to load the klass.
6299   if (UseCompressedOops) {
6300     movl(dst, src);
6301     decode_heap_oop(dst);
6302   } else
6303 #endif
6304     movptr(dst, src);
6305 }
6306 
6307 // Doesn't do verfication, generates fixed size code
6308 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6309 #ifdef _LP64
6310   if (UseCompressedOops) {
6311     movl(dst, src);
6312     decode_heap_oop_not_null(dst);
6313   } else
6314 #endif
6315     movptr(dst, src);
6316 }
6317 
6318 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6319 #ifdef _LP64
6320   if (UseCompressedOops) {
6321     assert(!dst.uses(src), "not enough registers");
6322     encode_heap_oop(src);
6323     movl(dst, src);
6324   } else
6325 #endif
6326     movptr(dst, src);
6327 }
6328 
6329 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6330   assert_different_registers(src1, tmp);
6331 #ifdef _LP64
6332   if (UseCompressedOops) {
6333     bool did_push = false;
6334     if (tmp == noreg) {
6335       tmp = rax;
6336       push(tmp);
6337       did_push = true;
6338       assert(!src2.uses(rsp), "can't push");
6339     }
6340     load_heap_oop(tmp, src2);
6341     cmpptr(src1, tmp);
6342     if (did_push)  pop(tmp);
6343   } else
6344 #endif
6345     cmpptr(src1, src2);
6346 }
6347 
6348 // Used for storing NULLs.
6349 void MacroAssembler::store_heap_oop_null(Address dst) {
6350 #ifdef _LP64
6351   if (UseCompressedOops) {
6352     movl(dst, (int32_t)NULL_WORD);
6353   } else {
6354     movslq(dst, (int32_t)NULL_WORD);
6355   }
6356 #else
6357   movl(dst, (int32_t)NULL_WORD);
6358 #endif
6359 }
6360 
6361 #ifdef _LP64
6362 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6363   if (UseCompressedClassPointers) {
6364     // Store to klass gap in destination
6365     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6366   }
6367 }
6368 
6369 #ifdef ASSERT
6370 void MacroAssembler::verify_heapbase(const char* msg) {
6371   assert (UseCompressedOops, "should be compressed");
6372   assert (Universe::heap() != NULL, "java heap should be initialized");
6373   if (CheckCompressedOops) {
6374     Label ok;
6375     push(rscratch1); // cmpptr trashes rscratch1
6376     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6377     jcc(Assembler::equal, ok);
6378     STOP(msg);
6379     bind(ok);
6380     pop(rscratch1);
6381   }
6382 }
6383 #endif
6384 
6385 // Algorithm must match oop.inline.hpp encode_heap_oop.
6386 void MacroAssembler::encode_heap_oop(Register r) {
6387 #ifdef ASSERT
6388   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6389 #endif
6390   verify_oop(r, "broken oop in encode_heap_oop");
6391   if (Universe::narrow_oop_base() == NULL) {
6392     if (Universe::narrow_oop_shift() != 0) {
6393       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6394       shrq(r, LogMinObjAlignmentInBytes);
6395     }
6396     return;
6397   }
6398   testq(r, r);
6399   cmovq(Assembler::equal, r, r12_heapbase);
6400   subq(r, r12_heapbase);
6401   shrq(r, LogMinObjAlignmentInBytes);
6402 }
6403 
6404 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6405 #ifdef ASSERT
6406   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6407   if (CheckCompressedOops) {
6408     Label ok;
6409     testq(r, r);
6410     jcc(Assembler::notEqual, ok);
6411     STOP("null oop passed to encode_heap_oop_not_null");
6412     bind(ok);
6413   }
6414 #endif
6415   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6416   if (Universe::narrow_oop_base() != NULL) {
6417     subq(r, r12_heapbase);
6418   }
6419   if (Universe::narrow_oop_shift() != 0) {
6420     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6421     shrq(r, LogMinObjAlignmentInBytes);
6422   }
6423 }
6424 
6425 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6426 #ifdef ASSERT
6427   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6428   if (CheckCompressedOops) {
6429     Label ok;
6430     testq(src, src);
6431     jcc(Assembler::notEqual, ok);
6432     STOP("null oop passed to encode_heap_oop_not_null2");
6433     bind(ok);
6434   }
6435 #endif
6436   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6437   if (dst != src) {
6438     movq(dst, src);
6439   }
6440   if (Universe::narrow_oop_base() != NULL) {
6441     subq(dst, r12_heapbase);
6442   }
6443   if (Universe::narrow_oop_shift() != 0) {
6444     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6445     shrq(dst, LogMinObjAlignmentInBytes);
6446   }
6447 }
6448 
6449 void  MacroAssembler::decode_heap_oop(Register r) {
6450 #ifdef ASSERT
6451   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6452 #endif
6453   if (Universe::narrow_oop_base() == NULL) {
6454     if (Universe::narrow_oop_shift() != 0) {
6455       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6456       shlq(r, LogMinObjAlignmentInBytes);
6457     }
6458   } else {
6459     Label done;
6460     shlq(r, LogMinObjAlignmentInBytes);
6461     jccb(Assembler::equal, done);
6462     addq(r, r12_heapbase);
6463     bind(done);
6464   }
6465   verify_oop(r, "broken oop in decode_heap_oop");
6466 }
6467 
6468 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6469   // Note: it will change flags
6470   assert (UseCompressedOops, "should only be used for compressed headers");
6471   assert (Universe::heap() != NULL, "java heap should be initialized");
6472   // Cannot assert, unverified entry point counts instructions (see .ad file)
6473   // vtableStubs also counts instructions in pd_code_size_limit.
6474   // Also do not verify_oop as this is called by verify_oop.
6475   if (Universe::narrow_oop_shift() != 0) {
6476     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6477     shlq(r, LogMinObjAlignmentInBytes);
6478     if (Universe::narrow_oop_base() != NULL) {
6479       addq(r, r12_heapbase);
6480     }
6481   } else {
6482     assert (Universe::narrow_oop_base() == NULL, "sanity");
6483   }
6484 }
6485 
6486 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6487   // Note: it will change flags
6488   assert (UseCompressedOops, "should only be used for compressed headers");
6489   assert (Universe::heap() != NULL, "java heap should be initialized");
6490   // Cannot assert, unverified entry point counts instructions (see .ad file)
6491   // vtableStubs also counts instructions in pd_code_size_limit.
6492   // Also do not verify_oop as this is called by verify_oop.
6493   if (Universe::narrow_oop_shift() != 0) {
6494     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6495     if (LogMinObjAlignmentInBytes == Address::times_8) {
6496       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6497     } else {
6498       if (dst != src) {
6499         movq(dst, src);
6500       }
6501       shlq(dst, LogMinObjAlignmentInBytes);
6502       if (Universe::narrow_oop_base() != NULL) {
6503         addq(dst, r12_heapbase);
6504       }
6505     }
6506   } else {
6507     assert (Universe::narrow_oop_base() == NULL, "sanity");
6508     if (dst != src) {
6509       movq(dst, src);
6510     }
6511   }
6512 }
6513 
6514 void MacroAssembler::encode_klass_not_null(Register r) {
6515   if (Universe::narrow_klass_base() != NULL) {
6516     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6517     assert(r != r12_heapbase, "Encoding a klass in r12");
6518     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6519     subq(r, r12_heapbase);
6520   }
6521   if (Universe::narrow_klass_shift() != 0) {
6522     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6523     shrq(r, LogKlassAlignmentInBytes);
6524   }
6525   if (Universe::narrow_klass_base() != NULL) {
6526     reinit_heapbase();
6527   }
6528 }
6529 
6530 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6531   if (dst == src) {
6532     encode_klass_not_null(src);
6533   } else {
6534     if (Universe::narrow_klass_base() != NULL) {
6535       mov64(dst, (int64_t)Universe::narrow_klass_base());
6536       negq(dst);
6537       addq(dst, src);
6538     } else {
6539       movptr(dst, src);
6540     }
6541     if (Universe::narrow_klass_shift() != 0) {
6542       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6543       shrq(dst, LogKlassAlignmentInBytes);
6544     }
6545   }
6546 }
6547 
6548 // Function instr_size_for_decode_klass_not_null() counts the instructions
6549 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6550 // when (Universe::heap() != NULL).  Hence, if the instructions they
6551 // generate change, then this method needs to be updated.
6552 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6553   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6554   if (Universe::narrow_klass_base() != NULL) {
6555     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6556     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6557   } else {
6558     // longest load decode klass function, mov64, leaq
6559     return 16;
6560   }
6561 }
6562 
6563 // !!! If the instructions that get generated here change then function
6564 // instr_size_for_decode_klass_not_null() needs to get updated.
6565 void  MacroAssembler::decode_klass_not_null(Register r) {
6566   // Note: it will change flags
6567   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6568   assert(r != r12_heapbase, "Decoding a klass in r12");
6569   // Cannot assert, unverified entry point counts instructions (see .ad file)
6570   // vtableStubs also counts instructions in pd_code_size_limit.
6571   // Also do not verify_oop as this is called by verify_oop.
6572   if (Universe::narrow_klass_shift() != 0) {
6573     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6574     shlq(r, LogKlassAlignmentInBytes);
6575   }
6576   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6577   if (Universe::narrow_klass_base() != NULL) {
6578     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6579     addq(r, r12_heapbase);
6580     reinit_heapbase();
6581   }
6582 }
6583 
6584 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6585   // Note: it will change flags
6586   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6587   if (dst == src) {
6588     decode_klass_not_null(dst);
6589   } else {
6590     // Cannot assert, unverified entry point counts instructions (see .ad file)
6591     // vtableStubs also counts instructions in pd_code_size_limit.
6592     // Also do not verify_oop as this is called by verify_oop.
6593     mov64(dst, (int64_t)Universe::narrow_klass_base());
6594     if (Universe::narrow_klass_shift() != 0) {
6595       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6596       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6597       leaq(dst, Address(dst, src, Address::times_8, 0));
6598     } else {
6599       addq(dst, src);
6600     }
6601   }
6602 }
6603 
6604 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6605   assert (UseCompressedOops, "should only be used for compressed headers");
6606   assert (Universe::heap() != NULL, "java heap should be initialized");
6607   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6608   int oop_index = oop_recorder()->find_index(obj);
6609   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6610   mov_narrow_oop(dst, oop_index, rspec);
6611 }
6612 
6613 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6614   assert (UseCompressedOops, "should only be used for compressed headers");
6615   assert (Universe::heap() != NULL, "java heap should be initialized");
6616   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6617   int oop_index = oop_recorder()->find_index(obj);
6618   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6619   mov_narrow_oop(dst, oop_index, rspec);
6620 }
6621 
6622 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6623   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6624   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6625   int klass_index = oop_recorder()->find_index(k);
6626   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6627   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6628 }
6629 
6630 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
6631   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6632   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6633   int klass_index = oop_recorder()->find_index(k);
6634   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6635   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6636 }
6637 
6638 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
6639   assert (UseCompressedOops, "should only be used for compressed headers");
6640   assert (Universe::heap() != NULL, "java heap should be initialized");
6641   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6642   int oop_index = oop_recorder()->find_index(obj);
6643   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6644   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6645 }
6646 
6647 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
6648   assert (UseCompressedOops, "should only be used for compressed headers");
6649   assert (Universe::heap() != NULL, "java heap should be initialized");
6650   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6651   int oop_index = oop_recorder()->find_index(obj);
6652   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6653   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6654 }
6655 
6656 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
6657   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6658   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6659   int klass_index = oop_recorder()->find_index(k);
6660   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6661   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6662 }
6663 
6664 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
6665   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6666   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6667   int klass_index = oop_recorder()->find_index(k);
6668   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6669   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6670 }
6671 
6672 void MacroAssembler::reinit_heapbase() {
6673   if (UseCompressedOops || UseCompressedClassPointers) {
6674     if (Universe::heap() != NULL) {
6675       if (Universe::narrow_oop_base() == NULL) {
6676         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
6677       } else {
6678         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
6679       }
6680     } else {
6681       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6682     }
6683   }
6684 }
6685 
6686 #endif // _LP64
6687 
6688 
6689 // C2 compiled method's prolog code.
6690 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
6691 
6692   // WARNING: Initial instruction MUST be 5 bytes or longer so that
6693   // NativeJump::patch_verified_entry will be able to patch out the entry
6694   // code safely. The push to verify stack depth is ok at 5 bytes,
6695   // the frame allocation can be either 3 or 6 bytes. So if we don't do
6696   // stack bang then we must use the 6 byte frame allocation even if
6697   // we have no frame. :-(
6698   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
6699 
6700   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6701   // Remove word for return addr
6702   framesize -= wordSize;
6703   stack_bang_size -= wordSize;
6704 
6705   // Calls to C2R adapters often do not accept exceptional returns.
6706   // We require that their callers must bang for them.  But be careful, because
6707   // some VM calls (such as call site linkage) can use several kilobytes of
6708   // stack.  But the stack safety zone should account for that.
6709   // See bugs 4446381, 4468289, 4497237.
6710   if (stack_bang_size > 0) {
6711     generate_stack_overflow_check(stack_bang_size);
6712 
6713     // We always push rbp, so that on return to interpreter rbp, will be
6714     // restored correctly and we can correct the stack.
6715     push(rbp);
6716     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6717     if (PreserveFramePointer) {
6718       mov(rbp, rsp);
6719     }
6720     // Remove word for ebp
6721     framesize -= wordSize;
6722 
6723     // Create frame
6724     if (framesize) {
6725       subptr(rsp, framesize);
6726     }
6727   } else {
6728     // Create frame (force generation of a 4 byte immediate value)
6729     subptr_imm32(rsp, framesize);
6730 
6731     // Save RBP register now.
6732     framesize -= wordSize;
6733     movptr(Address(rsp, framesize), rbp);
6734     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6735     if (PreserveFramePointer) {
6736       movptr(rbp, rsp);
6737       if (framesize > 0) {
6738         addptr(rbp, framesize);
6739       }
6740     }
6741   }
6742 
6743   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
6744     framesize -= wordSize;
6745     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
6746   }
6747 
6748 #ifndef _LP64
6749   // If method sets FPU control word do it now
6750   if (fp_mode_24b) {
6751     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
6752   }
6753   if (UseSSE >= 2 && VerifyFPU) {
6754     verify_FPU(0, "FPU stack must be clean on entry");
6755   }
6756 #endif
6757 
6758 #ifdef ASSERT
6759   if (VerifyStackAtCalls) {
6760     Label L;
6761     push(rax);
6762     mov(rax, rsp);
6763     andptr(rax, StackAlignmentInBytes-1);
6764     cmpptr(rax, StackAlignmentInBytes-wordSize);
6765     pop(rax);
6766     jcc(Assembler::equal, L);
6767     STOP("Stack is not properly aligned!");
6768     bind(L);
6769   }
6770 #endif
6771 
6772 }
6773 
6774 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
6775   // cnt - number of qwords (8-byte words).
6776   // base - start address, qword aligned.
6777   // is_large - if optimizers know cnt is larger than InitArrayShortSize
6778   assert(base==rdi, "base register must be edi for rep stos");
6779   assert(tmp==rax,   "tmp register must be eax for rep stos");
6780   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
6781   assert(InitArrayShortSize % BytesPerLong == 0,
6782     "InitArrayShortSize should be the multiple of BytesPerLong");
6783 
6784   Label DONE;
6785 
6786   xorptr(tmp, tmp);
6787 
6788   if (!is_large) {
6789     Label LOOP, LONG;
6790     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
6791     jccb(Assembler::greater, LONG);
6792 
6793     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6794 
6795     decrement(cnt);
6796     jccb(Assembler::negative, DONE); // Zero length
6797 
6798     // Use individual pointer-sized stores for small counts:
6799     BIND(LOOP);
6800     movptr(Address(base, cnt, Address::times_ptr), tmp);
6801     decrement(cnt);
6802     jccb(Assembler::greaterEqual, LOOP);
6803     jmpb(DONE);
6804 
6805     BIND(LONG);
6806   }
6807 
6808   // Use longer rep-prefixed ops for non-small counts:
6809   if (UseFastStosb) {
6810     shlptr(cnt, 3); // convert to number of bytes
6811     rep_stosb();
6812   } else {
6813     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6814     rep_stos();
6815   }
6816 
6817   BIND(DONE);
6818 }
6819 
6820 #ifdef COMPILER2
6821 
6822 // IndexOf for constant substrings with size >= 8 chars
6823 // which don't need to be loaded through stack.
6824 void MacroAssembler::string_indexofC8(Register str1, Register str2,
6825                                       Register cnt1, Register cnt2,
6826                                       int int_cnt2,  Register result,
6827                                       XMMRegister vec, Register tmp,
6828                                       int ae) {
6829   ShortBranchVerifier sbv(this);
6830   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6831   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6832 
6833   // This method uses the pcmpestri instruction with bound registers
6834   //   inputs:
6835   //     xmm - substring
6836   //     rax - substring length (elements count)
6837   //     mem - scanned string
6838   //     rdx - string length (elements count)
6839   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6840   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6841   //   outputs:
6842   //     rcx - matched index in string
6843   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6844   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
6845   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
6846   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
6847   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
6848 
6849   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
6850         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
6851         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
6852 
6853   // Note, inline_string_indexOf() generates checks:
6854   // if (substr.count > string.count) return -1;
6855   // if (substr.count == 0) return 0;
6856   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
6857 
6858   // Load substring.
6859   if (ae == StrIntrinsicNode::UL) {
6860     pmovzxbw(vec, Address(str2, 0));
6861   } else {
6862     movdqu(vec, Address(str2, 0));
6863   }
6864   movl(cnt2, int_cnt2);
6865   movptr(result, str1); // string addr
6866 
6867   if (int_cnt2 > stride) {
6868     jmpb(SCAN_TO_SUBSTR);
6869 
6870     // Reload substr for rescan, this code
6871     // is executed only for large substrings (> 8 chars)
6872     bind(RELOAD_SUBSTR);
6873     if (ae == StrIntrinsicNode::UL) {
6874       pmovzxbw(vec, Address(str2, 0));
6875     } else {
6876       movdqu(vec, Address(str2, 0));
6877     }
6878     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
6879 
6880     bind(RELOAD_STR);
6881     // We came here after the beginning of the substring was
6882     // matched but the rest of it was not so we need to search
6883     // again. Start from the next element after the previous match.
6884 
6885     // cnt2 is number of substring reminding elements and
6886     // cnt1 is number of string reminding elements when cmp failed.
6887     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
6888     subl(cnt1, cnt2);
6889     addl(cnt1, int_cnt2);
6890     movl(cnt2, int_cnt2); // Now restore cnt2
6891 
6892     decrementl(cnt1);     // Shift to next element
6893     cmpl(cnt1, cnt2);
6894     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6895 
6896     addptr(result, (1<<scale1));
6897 
6898   } // (int_cnt2 > 8)
6899 
6900   // Scan string for start of substr in 16-byte vectors
6901   bind(SCAN_TO_SUBSTR);
6902   pcmpestri(vec, Address(result, 0), mode);
6903   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6904   subl(cnt1, stride);
6905   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6906   cmpl(cnt1, cnt2);
6907   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6908   addptr(result, 16);
6909   jmpb(SCAN_TO_SUBSTR);
6910 
6911   // Found a potential substr
6912   bind(FOUND_CANDIDATE);
6913   // Matched whole vector if first element matched (tmp(rcx) == 0).
6914   if (int_cnt2 == stride) {
6915     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
6916   } else { // int_cnt2 > 8
6917     jccb(Assembler::overflow, FOUND_SUBSTR);
6918   }
6919   // After pcmpestri tmp(rcx) contains matched element index
6920   // Compute start addr of substr
6921   lea(result, Address(result, tmp, scale1));
6922 
6923   // Make sure string is still long enough
6924   subl(cnt1, tmp);
6925   cmpl(cnt1, cnt2);
6926   if (int_cnt2 == stride) {
6927     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6928   } else { // int_cnt2 > 8
6929     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
6930   }
6931   // Left less then substring.
6932 
6933   bind(RET_NOT_FOUND);
6934   movl(result, -1);
6935   jmp(EXIT);
6936 
6937   if (int_cnt2 > stride) {
6938     // This code is optimized for the case when whole substring
6939     // is matched if its head is matched.
6940     bind(MATCH_SUBSTR_HEAD);
6941     pcmpestri(vec, Address(result, 0), mode);
6942     // Reload only string if does not match
6943     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
6944 
6945     Label CONT_SCAN_SUBSTR;
6946     // Compare the rest of substring (> 8 chars).
6947     bind(FOUND_SUBSTR);
6948     // First 8 chars are already matched.
6949     negptr(cnt2);
6950     addptr(cnt2, stride);
6951 
6952     bind(SCAN_SUBSTR);
6953     subl(cnt1, stride);
6954     cmpl(cnt2, -stride); // Do not read beyond substring
6955     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
6956     // Back-up strings to avoid reading beyond substring:
6957     // cnt1 = cnt1 - cnt2 + 8
6958     addl(cnt1, cnt2); // cnt2 is negative
6959     addl(cnt1, stride);
6960     movl(cnt2, stride); negptr(cnt2);
6961     bind(CONT_SCAN_SUBSTR);
6962     if (int_cnt2 < (int)G) {
6963       int tail_off1 = int_cnt2<<scale1;
6964       int tail_off2 = int_cnt2<<scale2;
6965       if (ae == StrIntrinsicNode::UL) {
6966         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
6967       } else {
6968         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
6969       }
6970       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
6971     } else {
6972       // calculate index in register to avoid integer overflow (int_cnt2*2)
6973       movl(tmp, int_cnt2);
6974       addptr(tmp, cnt2);
6975       if (ae == StrIntrinsicNode::UL) {
6976         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
6977       } else {
6978         movdqu(vec, Address(str2, tmp, scale2, 0));
6979       }
6980       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
6981     }
6982     // Need to reload strings pointers if not matched whole vector
6983     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
6984     addptr(cnt2, stride);
6985     jcc(Assembler::negative, SCAN_SUBSTR);
6986     // Fall through if found full substring
6987 
6988   } // (int_cnt2 > 8)
6989 
6990   bind(RET_FOUND);
6991   // Found result if we matched full small substring.
6992   // Compute substr offset
6993   subptr(result, str1);
6994   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
6995     shrl(result, 1); // index
6996   }
6997   bind(EXIT);
6998 
6999 } // string_indexofC8
7000 
7001 // Small strings are loaded through stack if they cross page boundary.
7002 void MacroAssembler::string_indexof(Register str1, Register str2,
7003                                     Register cnt1, Register cnt2,
7004                                     int int_cnt2,  Register result,
7005                                     XMMRegister vec, Register tmp,
7006                                     int ae) {
7007   ShortBranchVerifier sbv(this);
7008   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7009   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7010 
7011   //
7012   // int_cnt2 is length of small (< 8 chars) constant substring
7013   // or (-1) for non constant substring in which case its length
7014   // is in cnt2 register.
7015   //
7016   // Note, inline_string_indexOf() generates checks:
7017   // if (substr.count > string.count) return -1;
7018   // if (substr.count == 0) return 0;
7019   //
7020   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7021   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7022   // This method uses the pcmpestri instruction with bound registers
7023   //   inputs:
7024   //     xmm - substring
7025   //     rax - substring length (elements count)
7026   //     mem - scanned string
7027   //     rdx - string length (elements count)
7028   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7029   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7030   //   outputs:
7031   //     rcx - matched index in string
7032   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7033   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7034   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7035   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7036 
7037   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7038         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7039         FOUND_CANDIDATE;
7040 
7041   { //========================================================
7042     // We don't know where these strings are located
7043     // and we can't read beyond them. Load them through stack.
7044     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7045 
7046     movptr(tmp, rsp); // save old SP
7047 
7048     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7049       if (int_cnt2 == (1>>scale2)) { // One byte
7050         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7051         load_unsigned_byte(result, Address(str2, 0));
7052         movdl(vec, result); // move 32 bits
7053       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7054         // Not enough header space in 32-bit VM: 12+3 = 15.
7055         movl(result, Address(str2, -1));
7056         shrl(result, 8);
7057         movdl(vec, result); // move 32 bits
7058       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7059         load_unsigned_short(result, Address(str2, 0));
7060         movdl(vec, result); // move 32 bits
7061       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7062         movdl(vec, Address(str2, 0)); // move 32 bits
7063       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7064         movq(vec, Address(str2, 0));  // move 64 bits
7065       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7066         // Array header size is 12 bytes in 32-bit VM
7067         // + 6 bytes for 3 chars == 18 bytes,
7068         // enough space to load vec and shift.
7069         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7070         if (ae == StrIntrinsicNode::UL) {
7071           int tail_off = int_cnt2-8;
7072           pmovzxbw(vec, Address(str2, tail_off));
7073           psrldq(vec, -2*tail_off);
7074         }
7075         else {
7076           int tail_off = int_cnt2*(1<<scale2);
7077           movdqu(vec, Address(str2, tail_off-16));
7078           psrldq(vec, 16-tail_off);
7079         }
7080       }
7081     } else { // not constant substring
7082       cmpl(cnt2, stride);
7083       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7084 
7085       // We can read beyond string if srt+16 does not cross page boundary
7086       // since heaps are aligned and mapped by pages.
7087       assert(os::vm_page_size() < (int)G, "default page should be small");
7088       movl(result, str2); // We need only low 32 bits
7089       andl(result, (os::vm_page_size()-1));
7090       cmpl(result, (os::vm_page_size()-16));
7091       jccb(Assembler::belowEqual, CHECK_STR);
7092 
7093       // Move small strings to stack to allow load 16 bytes into vec.
7094       subptr(rsp, 16);
7095       int stk_offset = wordSize-(1<<scale2);
7096       push(cnt2);
7097 
7098       bind(COPY_SUBSTR);
7099       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7100         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7101         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7102       } else if (ae == StrIntrinsicNode::UU) {
7103         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7104         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7105       }
7106       decrement(cnt2);
7107       jccb(Assembler::notZero, COPY_SUBSTR);
7108 
7109       pop(cnt2);
7110       movptr(str2, rsp);  // New substring address
7111     } // non constant
7112 
7113     bind(CHECK_STR);
7114     cmpl(cnt1, stride);
7115     jccb(Assembler::aboveEqual, BIG_STRINGS);
7116 
7117     // Check cross page boundary.
7118     movl(result, str1); // We need only low 32 bits
7119     andl(result, (os::vm_page_size()-1));
7120     cmpl(result, (os::vm_page_size()-16));
7121     jccb(Assembler::belowEqual, BIG_STRINGS);
7122 
7123     subptr(rsp, 16);
7124     int stk_offset = -(1<<scale1);
7125     if (int_cnt2 < 0) { // not constant
7126       push(cnt2);
7127       stk_offset += wordSize;
7128     }
7129     movl(cnt2, cnt1);
7130 
7131     bind(COPY_STR);
7132     if (ae == StrIntrinsicNode::LL) {
7133       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7134       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7135     } else {
7136       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7137       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7138     }
7139     decrement(cnt2);
7140     jccb(Assembler::notZero, COPY_STR);
7141 
7142     if (int_cnt2 < 0) { // not constant
7143       pop(cnt2);
7144     }
7145     movptr(str1, rsp);  // New string address
7146 
7147     bind(BIG_STRINGS);
7148     // Load substring.
7149     if (int_cnt2 < 0) { // -1
7150       if (ae == StrIntrinsicNode::UL) {
7151         pmovzxbw(vec, Address(str2, 0));
7152       } else {
7153         movdqu(vec, Address(str2, 0));
7154       }
7155       push(cnt2);       // substr count
7156       push(str2);       // substr addr
7157       push(str1);       // string addr
7158     } else {
7159       // Small (< 8 chars) constant substrings are loaded already.
7160       movl(cnt2, int_cnt2);
7161     }
7162     push(tmp);  // original SP
7163 
7164   } // Finished loading
7165 
7166   //========================================================
7167   // Start search
7168   //
7169 
7170   movptr(result, str1); // string addr
7171 
7172   if (int_cnt2  < 0) {  // Only for non constant substring
7173     jmpb(SCAN_TO_SUBSTR);
7174 
7175     // SP saved at sp+0
7176     // String saved at sp+1*wordSize
7177     // Substr saved at sp+2*wordSize
7178     // Substr count saved at sp+3*wordSize
7179 
7180     // Reload substr for rescan, this code
7181     // is executed only for large substrings (> 8 chars)
7182     bind(RELOAD_SUBSTR);
7183     movptr(str2, Address(rsp, 2*wordSize));
7184     movl(cnt2, Address(rsp, 3*wordSize));
7185     if (ae == StrIntrinsicNode::UL) {
7186       pmovzxbw(vec, Address(str2, 0));
7187     } else {
7188       movdqu(vec, Address(str2, 0));
7189     }
7190     // We came here after the beginning of the substring was
7191     // matched but the rest of it was not so we need to search
7192     // again. Start from the next element after the previous match.
7193     subptr(str1, result); // Restore counter
7194     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7195       shrl(str1, 1);
7196     }
7197     addl(cnt1, str1);
7198     decrementl(cnt1);   // Shift to next element
7199     cmpl(cnt1, cnt2);
7200     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7201 
7202     addptr(result, (1<<scale1));
7203   } // non constant
7204 
7205   // Scan string for start of substr in 16-byte vectors
7206   bind(SCAN_TO_SUBSTR);
7207   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7208   pcmpestri(vec, Address(result, 0), mode);
7209   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7210   subl(cnt1, stride);
7211   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7212   cmpl(cnt1, cnt2);
7213   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7214   addptr(result, 16);
7215 
7216   bind(ADJUST_STR);
7217   cmpl(cnt1, stride); // Do not read beyond string
7218   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7219   // Back-up string to avoid reading beyond string.
7220   lea(result, Address(result, cnt1, scale1, -16));
7221   movl(cnt1, stride);
7222   jmpb(SCAN_TO_SUBSTR);
7223 
7224   // Found a potential substr
7225   bind(FOUND_CANDIDATE);
7226   // After pcmpestri tmp(rcx) contains matched element index
7227 
7228   // Make sure string is still long enough
7229   subl(cnt1, tmp);
7230   cmpl(cnt1, cnt2);
7231   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7232   // Left less then substring.
7233 
7234   bind(RET_NOT_FOUND);
7235   movl(result, -1);
7236   jmpb(CLEANUP);
7237 
7238   bind(FOUND_SUBSTR);
7239   // Compute start addr of substr
7240   lea(result, Address(result, tmp, scale1));
7241   if (int_cnt2 > 0) { // Constant substring
7242     // Repeat search for small substring (< 8 chars)
7243     // from new point without reloading substring.
7244     // Have to check that we don't read beyond string.
7245     cmpl(tmp, stride-int_cnt2);
7246     jccb(Assembler::greater, ADJUST_STR);
7247     // Fall through if matched whole substring.
7248   } else { // non constant
7249     assert(int_cnt2 == -1, "should be != 0");
7250 
7251     addl(tmp, cnt2);
7252     // Found result if we matched whole substring.
7253     cmpl(tmp, stride);
7254     jccb(Assembler::lessEqual, RET_FOUND);
7255 
7256     // Repeat search for small substring (<= 8 chars)
7257     // from new point 'str1' without reloading substring.
7258     cmpl(cnt2, stride);
7259     // Have to check that we don't read beyond string.
7260     jccb(Assembler::lessEqual, ADJUST_STR);
7261 
7262     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7263     // Compare the rest of substring (> 8 chars).
7264     movptr(str1, result);
7265 
7266     cmpl(tmp, cnt2);
7267     // First 8 chars are already matched.
7268     jccb(Assembler::equal, CHECK_NEXT);
7269 
7270     bind(SCAN_SUBSTR);
7271     pcmpestri(vec, Address(str1, 0), mode);
7272     // Need to reload strings pointers if not matched whole vector
7273     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7274 
7275     bind(CHECK_NEXT);
7276     subl(cnt2, stride);
7277     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7278     addptr(str1, 16);
7279     if (ae == StrIntrinsicNode::UL) {
7280       addptr(str2, 8);
7281     } else {
7282       addptr(str2, 16);
7283     }
7284     subl(cnt1, stride);
7285     cmpl(cnt2, stride); // Do not read beyond substring
7286     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7287     // Back-up strings to avoid reading beyond substring.
7288 
7289     if (ae == StrIntrinsicNode::UL) {
7290       lea(str2, Address(str2, cnt2, scale2, -8));
7291       lea(str1, Address(str1, cnt2, scale1, -16));
7292     } else {
7293       lea(str2, Address(str2, cnt2, scale2, -16));
7294       lea(str1, Address(str1, cnt2, scale1, -16));
7295     }
7296     subl(cnt1, cnt2);
7297     movl(cnt2, stride);
7298     addl(cnt1, stride);
7299     bind(CONT_SCAN_SUBSTR);
7300     if (ae == StrIntrinsicNode::UL) {
7301       pmovzxbw(vec, Address(str2, 0));
7302     } else {
7303       movdqu(vec, Address(str2, 0));
7304     }
7305     jmp(SCAN_SUBSTR);
7306 
7307     bind(RET_FOUND_LONG);
7308     movptr(str1, Address(rsp, wordSize));
7309   } // non constant
7310 
7311   bind(RET_FOUND);
7312   // Compute substr offset
7313   subptr(result, str1);
7314   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7315     shrl(result, 1); // index
7316   }
7317   bind(CLEANUP);
7318   pop(rsp); // restore SP
7319 
7320 } // string_indexof
7321 
7322 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7323                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7324   ShortBranchVerifier sbv(this);
7325   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7326 
7327   int stride = 8;
7328 
7329   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7330         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7331         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7332         FOUND_SEQ_CHAR, DONE_LABEL;
7333 
7334   movptr(result, str1);
7335   if (UseAVX >= 2) {
7336     cmpl(cnt1, stride);
7337     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7338     cmpl(cnt1, 2*stride);
7339     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7340     movdl(vec1, ch);
7341     vpbroadcastw(vec1, vec1);
7342     vpxor(vec2, vec2);
7343     movl(tmp, cnt1);
7344     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7345     andl(cnt1,0x0000000F);  //tail count (in chars)
7346 
7347     bind(SCAN_TO_16_CHAR_LOOP);
7348     vmovdqu(vec3, Address(result, 0));
7349     vpcmpeqw(vec3, vec3, vec1, 1);
7350     vptest(vec2, vec3);
7351     jcc(Assembler::carryClear, FOUND_CHAR);
7352     addptr(result, 32);
7353     subl(tmp, 2*stride);
7354     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7355     jmp(SCAN_TO_8_CHAR);
7356     bind(SCAN_TO_8_CHAR_INIT);
7357     movdl(vec1, ch);
7358     pshuflw(vec1, vec1, 0x00);
7359     pshufd(vec1, vec1, 0);
7360     pxor(vec2, vec2);
7361   }
7362   bind(SCAN_TO_8_CHAR);
7363   cmpl(cnt1, stride);
7364   if (UseAVX >= 2) {
7365     jcc(Assembler::less, SCAN_TO_CHAR);
7366   } else {
7367     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7368     movdl(vec1, ch);
7369     pshuflw(vec1, vec1, 0x00);
7370     pshufd(vec1, vec1, 0);
7371     pxor(vec2, vec2);
7372   }
7373   movl(tmp, cnt1);
7374   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7375   andl(cnt1,0x00000007);  //tail count (in chars)
7376 
7377   bind(SCAN_TO_8_CHAR_LOOP);
7378   movdqu(vec3, Address(result, 0));
7379   pcmpeqw(vec3, vec1);
7380   ptest(vec2, vec3);
7381   jcc(Assembler::carryClear, FOUND_CHAR);
7382   addptr(result, 16);
7383   subl(tmp, stride);
7384   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7385   bind(SCAN_TO_CHAR);
7386   testl(cnt1, cnt1);
7387   jcc(Assembler::zero, RET_NOT_FOUND);
7388   bind(SCAN_TO_CHAR_LOOP);
7389   load_unsigned_short(tmp, Address(result, 0));
7390   cmpl(ch, tmp);
7391   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7392   addptr(result, 2);
7393   subl(cnt1, 1);
7394   jccb(Assembler::zero, RET_NOT_FOUND);
7395   jmp(SCAN_TO_CHAR_LOOP);
7396 
7397   bind(RET_NOT_FOUND);
7398   movl(result, -1);
7399   jmpb(DONE_LABEL);
7400 
7401   bind(FOUND_CHAR);
7402   if (UseAVX >= 2) {
7403     vpmovmskb(tmp, vec3);
7404   } else {
7405     pmovmskb(tmp, vec3);
7406   }
7407   bsfl(ch, tmp);
7408   addl(result, ch);
7409 
7410   bind(FOUND_SEQ_CHAR);
7411   subptr(result, str1);
7412   shrl(result, 1);
7413 
7414   bind(DONE_LABEL);
7415 } // string_indexof_char
7416 
7417 // helper function for string_compare
7418 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7419                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7420                                         Address::ScaleFactor scale2, Register index, int ae) {
7421   if (ae == StrIntrinsicNode::LL) {
7422     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7423     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7424   } else if (ae == StrIntrinsicNode::UU) {
7425     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7426     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7427   } else {
7428     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7429     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7430   }
7431 }
7432 
7433 // Compare strings, used for char[] and byte[].
7434 void MacroAssembler::string_compare(Register str1, Register str2,
7435                                     Register cnt1, Register cnt2, Register result,
7436                                     XMMRegister vec1, int ae) {
7437   ShortBranchVerifier sbv(this);
7438   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7439   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7440   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7441   int stride2x2 = 0x40;
7442   Address::ScaleFactor scale = Address::no_scale;
7443   Address::ScaleFactor scale1 = Address::no_scale;
7444   Address::ScaleFactor scale2 = Address::no_scale;
7445 
7446   if (ae != StrIntrinsicNode::LL) {
7447     stride2x2 = 0x20;
7448   }
7449 
7450   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7451     shrl(cnt2, 1);
7452   }
7453   // Compute the minimum of the string lengths and the
7454   // difference of the string lengths (stack).
7455   // Do the conditional move stuff
7456   movl(result, cnt1);
7457   subl(cnt1, cnt2);
7458   push(cnt1);
7459   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7460 
7461   // Is the minimum length zero?
7462   testl(cnt2, cnt2);
7463   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7464   if (ae == StrIntrinsicNode::LL) {
7465     // Load first bytes
7466     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7467     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7468   } else if (ae == StrIntrinsicNode::UU) {
7469     // Load first characters
7470     load_unsigned_short(result, Address(str1, 0));
7471     load_unsigned_short(cnt1, Address(str2, 0));
7472   } else {
7473     load_unsigned_byte(result, Address(str1, 0));
7474     load_unsigned_short(cnt1, Address(str2, 0));
7475   }
7476   subl(result, cnt1);
7477   jcc(Assembler::notZero,  POP_LABEL);
7478 
7479   if (ae == StrIntrinsicNode::UU) {
7480     // Divide length by 2 to get number of chars
7481     shrl(cnt2, 1);
7482   }
7483   cmpl(cnt2, 1);
7484   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7485 
7486   // Check if the strings start at the same location and setup scale and stride
7487   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7488     cmpptr(str1, str2);
7489     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7490     if (ae == StrIntrinsicNode::LL) {
7491       scale = Address::times_1;
7492       stride = 16;
7493     } else {
7494       scale = Address::times_2;
7495       stride = 8;
7496     }
7497   } else {
7498     scale1 = Address::times_1;
7499     scale2 = Address::times_2;
7500     // scale not used
7501     stride = 8;
7502   }
7503 
7504   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7505     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7506     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7507     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7508     Label COMPARE_TAIL_LONG;
7509     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7510 
7511     int pcmpmask = 0x19;
7512     if (ae == StrIntrinsicNode::LL) {
7513       pcmpmask &= ~0x01;
7514     }
7515 
7516     // Setup to compare 16-chars (32-bytes) vectors,
7517     // start from first character again because it has aligned address.
7518     if (ae == StrIntrinsicNode::LL) {
7519       stride2 = 32;
7520     } else {
7521       stride2 = 16;
7522     }
7523     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7524       adr_stride = stride << scale;
7525     } else {
7526       adr_stride1 = 8;  //stride << scale1;
7527       adr_stride2 = 16; //stride << scale2;
7528     }
7529 
7530     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7531     // rax and rdx are used by pcmpestri as elements counters
7532     movl(result, cnt2);
7533     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7534     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7535 
7536     // fast path : compare first 2 8-char vectors.
7537     bind(COMPARE_16_CHARS);
7538     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7539       movdqu(vec1, Address(str1, 0));
7540     } else {
7541       pmovzxbw(vec1, Address(str1, 0));
7542     }
7543     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7544     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7545 
7546     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7547       movdqu(vec1, Address(str1, adr_stride));
7548       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7549     } else {
7550       pmovzxbw(vec1, Address(str1, adr_stride1));
7551       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7552     }
7553     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7554     addl(cnt1, stride);
7555 
7556     // Compare the characters at index in cnt1
7557     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7558     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7559     subl(result, cnt2);
7560     jmp(POP_LABEL);
7561 
7562     // Setup the registers to start vector comparison loop
7563     bind(COMPARE_WIDE_VECTORS);
7564     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7565       lea(str1, Address(str1, result, scale));
7566       lea(str2, Address(str2, result, scale));
7567     } else {
7568       lea(str1, Address(str1, result, scale1));
7569       lea(str2, Address(str2, result, scale2));
7570     }
7571     subl(result, stride2);
7572     subl(cnt2, stride2);
7573     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7574     negptr(result);
7575 
7576     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7577     bind(COMPARE_WIDE_VECTORS_LOOP);
7578 
7579 #ifdef _LP64
7580     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7581       cmpl(cnt2, stride2x2);
7582       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7583       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7584       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7585 
7586       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7587       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7588         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7589         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7590       } else {
7591         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7592         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7593       }
7594       kortestql(k7, k7);
7595       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7596       addptr(result, stride2x2);  // update since we already compared at this addr
7597       subl(cnt2, stride2x2);      // and sub the size too
7598       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7599 
7600       vpxor(vec1, vec1);
7601       jmpb(COMPARE_WIDE_TAIL);
7602     }//if (VM_Version::supports_avx512vlbw())
7603 #endif // _LP64
7604 
7605 
7606     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7607     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7608       vmovdqu(vec1, Address(str1, result, scale));
7609       vpxor(vec1, Address(str2, result, scale));
7610     } else {
7611       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7612       vpxor(vec1, Address(str2, result, scale2));
7613     }
7614     vptest(vec1, vec1);
7615     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7616     addptr(result, stride2);
7617     subl(cnt2, stride2);
7618     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7619     // clean upper bits of YMM registers
7620     vpxor(vec1, vec1);
7621 
7622     // compare wide vectors tail
7623     bind(COMPARE_WIDE_TAIL);
7624     testptr(result, result);
7625     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7626 
7627     movl(result, stride2);
7628     movl(cnt2, result);
7629     negptr(result);
7630     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7631 
7632     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7633     bind(VECTOR_NOT_EQUAL);
7634     // clean upper bits of YMM registers
7635     vpxor(vec1, vec1);
7636     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7637       lea(str1, Address(str1, result, scale));
7638       lea(str2, Address(str2, result, scale));
7639     } else {
7640       lea(str1, Address(str1, result, scale1));
7641       lea(str2, Address(str2, result, scale2));
7642     }
7643     jmp(COMPARE_16_CHARS);
7644 
7645     // Compare tail chars, length between 1 to 15 chars
7646     bind(COMPARE_TAIL_LONG);
7647     movl(cnt2, result);
7648     cmpl(cnt2, stride);
7649     jcc(Assembler::less, COMPARE_SMALL_STR);
7650 
7651     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7652       movdqu(vec1, Address(str1, 0));
7653     } else {
7654       pmovzxbw(vec1, Address(str1, 0));
7655     }
7656     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7657     jcc(Assembler::below, COMPARE_INDEX_CHAR);
7658     subptr(cnt2, stride);
7659     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7660     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7661       lea(str1, Address(str1, result, scale));
7662       lea(str2, Address(str2, result, scale));
7663     } else {
7664       lea(str1, Address(str1, result, scale1));
7665       lea(str2, Address(str2, result, scale2));
7666     }
7667     negptr(cnt2);
7668     jmpb(WHILE_HEAD_LABEL);
7669 
7670     bind(COMPARE_SMALL_STR);
7671   } else if (UseSSE42Intrinsics) {
7672     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
7673     int pcmpmask = 0x19;
7674     // Setup to compare 8-char (16-byte) vectors,
7675     // start from first character again because it has aligned address.
7676     movl(result, cnt2);
7677     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
7678     if (ae == StrIntrinsicNode::LL) {
7679       pcmpmask &= ~0x01;
7680     }
7681     jcc(Assembler::zero, COMPARE_TAIL);
7682     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7683       lea(str1, Address(str1, result, scale));
7684       lea(str2, Address(str2, result, scale));
7685     } else {
7686       lea(str1, Address(str1, result, scale1));
7687       lea(str2, Address(str2, result, scale2));
7688     }
7689     negptr(result);
7690 
7691     // pcmpestri
7692     //   inputs:
7693     //     vec1- substring
7694     //     rax - negative string length (elements count)
7695     //     mem - scanned string
7696     //     rdx - string length (elements count)
7697     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
7698     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
7699     //   outputs:
7700     //     rcx - first mismatched element index
7701     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7702 
7703     bind(COMPARE_WIDE_VECTORS);
7704     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7705       movdqu(vec1, Address(str1, result, scale));
7706       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7707     } else {
7708       pmovzxbw(vec1, Address(str1, result, scale1));
7709       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7710     }
7711     // After pcmpestri cnt1(rcx) contains mismatched element index
7712 
7713     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
7714     addptr(result, stride);
7715     subptr(cnt2, stride);
7716     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
7717 
7718     // compare wide vectors tail
7719     testptr(result, result);
7720     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7721 
7722     movl(cnt2, stride);
7723     movl(result, stride);
7724     negptr(result);
7725     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7726       movdqu(vec1, Address(str1, result, scale));
7727       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7728     } else {
7729       pmovzxbw(vec1, Address(str1, result, scale1));
7730       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7731     }
7732     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
7733 
7734     // Mismatched characters in the vectors
7735     bind(VECTOR_NOT_EQUAL);
7736     addptr(cnt1, result);
7737     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7738     subl(result, cnt2);
7739     jmpb(POP_LABEL);
7740 
7741     bind(COMPARE_TAIL); // limit is zero
7742     movl(cnt2, result);
7743     // Fallthru to tail compare
7744   }
7745   // Shift str2 and str1 to the end of the arrays, negate min
7746   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7747     lea(str1, Address(str1, cnt2, scale));
7748     lea(str2, Address(str2, cnt2, scale));
7749   } else {
7750     lea(str1, Address(str1, cnt2, scale1));
7751     lea(str2, Address(str2, cnt2, scale2));
7752   }
7753   decrementl(cnt2);  // first character was compared already
7754   negptr(cnt2);
7755 
7756   // Compare the rest of the elements
7757   bind(WHILE_HEAD_LABEL);
7758   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
7759   subl(result, cnt1);
7760   jccb(Assembler::notZero, POP_LABEL);
7761   increment(cnt2);
7762   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
7763 
7764   // Strings are equal up to min length.  Return the length difference.
7765   bind(LENGTH_DIFF_LABEL);
7766   pop(result);
7767   if (ae == StrIntrinsicNode::UU) {
7768     // Divide diff by 2 to get number of chars
7769     sarl(result, 1);
7770   }
7771   jmpb(DONE_LABEL);
7772 
7773 #ifdef _LP64
7774   if (VM_Version::supports_avx512vlbw()) {
7775 
7776     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
7777 
7778     kmovql(cnt1, k7);
7779     notq(cnt1);
7780     bsfq(cnt2, cnt1);
7781     if (ae != StrIntrinsicNode::LL) {
7782       // Divide diff by 2 to get number of chars
7783       sarl(cnt2, 1);
7784     }
7785     addq(result, cnt2);
7786     if (ae == StrIntrinsicNode::LL) {
7787       load_unsigned_byte(cnt1, Address(str2, result));
7788       load_unsigned_byte(result, Address(str1, result));
7789     } else if (ae == StrIntrinsicNode::UU) {
7790       load_unsigned_short(cnt1, Address(str2, result, scale));
7791       load_unsigned_short(result, Address(str1, result, scale));
7792     } else {
7793       load_unsigned_short(cnt1, Address(str2, result, scale2));
7794       load_unsigned_byte(result, Address(str1, result, scale1));
7795     }
7796     subl(result, cnt1);
7797     jmpb(POP_LABEL);
7798   }//if (VM_Version::supports_avx512vlbw())
7799 #endif // _LP64
7800 
7801   // Discard the stored length difference
7802   bind(POP_LABEL);
7803   pop(cnt1);
7804 
7805   // That's it
7806   bind(DONE_LABEL);
7807   if(ae == StrIntrinsicNode::UL) {
7808     negl(result);
7809   }
7810 
7811 }
7812 
7813 // Search for Non-ASCII character (Negative byte value) in a byte array,
7814 // return true if it has any and false otherwise.
7815 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
7816 //   @HotSpotIntrinsicCandidate
7817 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
7818 //     for (int i = off; i < off + len; i++) {
7819 //       if (ba[i] < 0) {
7820 //         return true;
7821 //       }
7822 //     }
7823 //     return false;
7824 //   }
7825 void MacroAssembler::has_negatives(Register ary1, Register len,
7826   Register result, Register tmp1,
7827   XMMRegister vec1, XMMRegister vec2) {
7828   // rsi: byte array
7829   // rcx: len
7830   // rax: result
7831   ShortBranchVerifier sbv(this);
7832   assert_different_registers(ary1, len, result, tmp1);
7833   assert_different_registers(vec1, vec2);
7834   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
7835 
7836   // len == 0
7837   testl(len, len);
7838   jcc(Assembler::zero, FALSE_LABEL);
7839 
7840   if ((UseAVX > 2) && // AVX512
7841     VM_Version::supports_avx512vlbw() &&
7842     VM_Version::supports_bmi2()) {
7843 
7844     set_vector_masking();  // opening of the stub context for programming mask registers
7845 
7846     Label test_64_loop, test_tail;
7847     Register tmp3_aliased = len;
7848 
7849     movl(tmp1, len);
7850     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
7851 
7852     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
7853     andl(len, ~(64 - 1));    // vector count (in chars)
7854     jccb(Assembler::zero, test_tail);
7855 
7856     lea(ary1, Address(ary1, len, Address::times_1));
7857     negptr(len);
7858 
7859     bind(test_64_loop);
7860     // Check whether our 64 elements of size byte contain negatives
7861     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
7862     kortestql(k2, k2);
7863     jcc(Assembler::notZero, TRUE_LABEL);
7864 
7865     addptr(len, 64);
7866     jccb(Assembler::notZero, test_64_loop);
7867 
7868 
7869     bind(test_tail);
7870     // bail out when there is nothing to be done
7871     testl(tmp1, -1);
7872     jcc(Assembler::zero, FALSE_LABEL);
7873 
7874     // Save k1
7875     kmovql(k3, k1);
7876 
7877     // ~(~0 << len) applied up to two times (for 32-bit scenario)
7878 #ifdef _LP64
7879     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
7880     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
7881     notq(tmp3_aliased);
7882     kmovql(k1, tmp3_aliased);
7883 #else
7884     Label k_init;
7885     jmp(k_init);
7886 
7887     // We could not read 64-bits from a general purpose register thus we move
7888     // data required to compose 64 1's to the instruction stream
7889     // We emit 64 byte wide series of elements from 0..63 which later on would
7890     // be used as a compare targets with tail count contained in tmp1 register.
7891     // Result would be a k1 register having tmp1 consecutive number or 1
7892     // counting from least significant bit.
7893     address tmp = pc();
7894     emit_int64(0x0706050403020100);
7895     emit_int64(0x0F0E0D0C0B0A0908);
7896     emit_int64(0x1716151413121110);
7897     emit_int64(0x1F1E1D1C1B1A1918);
7898     emit_int64(0x2726252423222120);
7899     emit_int64(0x2F2E2D2C2B2A2928);
7900     emit_int64(0x3736353433323130);
7901     emit_int64(0x3F3E3D3C3B3A3938);
7902 
7903     bind(k_init);
7904     lea(len, InternalAddress(tmp));
7905     // create mask to test for negative byte inside a vector
7906     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
7907     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
7908 
7909 #endif
7910     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
7911     ktestq(k2, k1);
7912     // Restore k1
7913     kmovql(k1, k3);
7914     jcc(Assembler::notZero, TRUE_LABEL);
7915 
7916     jmp(FALSE_LABEL);
7917 
7918     clear_vector_masking();   // closing of the stub context for programming mask registers
7919   } else {
7920     movl(result, len); // copy
7921 
7922     if (UseAVX == 2 && UseSSE >= 2) {
7923       // With AVX2, use 32-byte vector compare
7924       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7925 
7926       // Compare 32-byte vectors
7927       andl(result, 0x0000001f);  //   tail count (in bytes)
7928       andl(len, 0xffffffe0);   // vector count (in bytes)
7929       jccb(Assembler::zero, COMPARE_TAIL);
7930 
7931       lea(ary1, Address(ary1, len, Address::times_1));
7932       negptr(len);
7933 
7934       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
7935       movdl(vec2, tmp1);
7936       vpbroadcastd(vec2, vec2);
7937 
7938       bind(COMPARE_WIDE_VECTORS);
7939       vmovdqu(vec1, Address(ary1, len, Address::times_1));
7940       vptest(vec1, vec2);
7941       jccb(Assembler::notZero, TRUE_LABEL);
7942       addptr(len, 32);
7943       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7944 
7945       testl(result, result);
7946       jccb(Assembler::zero, FALSE_LABEL);
7947 
7948       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7949       vptest(vec1, vec2);
7950       jccb(Assembler::notZero, TRUE_LABEL);
7951       jmpb(FALSE_LABEL);
7952 
7953       bind(COMPARE_TAIL); // len is zero
7954       movl(len, result);
7955       // Fallthru to tail compare
7956     } else if (UseSSE42Intrinsics) {
7957       // With SSE4.2, use double quad vector compare
7958       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7959 
7960       // Compare 16-byte vectors
7961       andl(result, 0x0000000f);  //   tail count (in bytes)
7962       andl(len, 0xfffffff0);   // vector count (in bytes)
7963       jccb(Assembler::zero, COMPARE_TAIL);
7964 
7965       lea(ary1, Address(ary1, len, Address::times_1));
7966       negptr(len);
7967 
7968       movl(tmp1, 0x80808080);
7969       movdl(vec2, tmp1);
7970       pshufd(vec2, vec2, 0);
7971 
7972       bind(COMPARE_WIDE_VECTORS);
7973       movdqu(vec1, Address(ary1, len, Address::times_1));
7974       ptest(vec1, vec2);
7975       jccb(Assembler::notZero, TRUE_LABEL);
7976       addptr(len, 16);
7977       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7978 
7979       testl(result, result);
7980       jccb(Assembler::zero, FALSE_LABEL);
7981 
7982       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
7983       ptest(vec1, vec2);
7984       jccb(Assembler::notZero, TRUE_LABEL);
7985       jmpb(FALSE_LABEL);
7986 
7987       bind(COMPARE_TAIL); // len is zero
7988       movl(len, result);
7989       // Fallthru to tail compare
7990     }
7991   }
7992   // Compare 4-byte vectors
7993   andl(len, 0xfffffffc); // vector count (in bytes)
7994   jccb(Assembler::zero, COMPARE_CHAR);
7995 
7996   lea(ary1, Address(ary1, len, Address::times_1));
7997   negptr(len);
7998 
7999   bind(COMPARE_VECTORS);
8000   movl(tmp1, Address(ary1, len, Address::times_1));
8001   andl(tmp1, 0x80808080);
8002   jccb(Assembler::notZero, TRUE_LABEL);
8003   addptr(len, 4);
8004   jcc(Assembler::notZero, COMPARE_VECTORS);
8005 
8006   // Compare trailing char (final 2 bytes), if any
8007   bind(COMPARE_CHAR);
8008   testl(result, 0x2);   // tail  char
8009   jccb(Assembler::zero, COMPARE_BYTE);
8010   load_unsigned_short(tmp1, Address(ary1, 0));
8011   andl(tmp1, 0x00008080);
8012   jccb(Assembler::notZero, TRUE_LABEL);
8013   subptr(result, 2);
8014   lea(ary1, Address(ary1, 2));
8015 
8016   bind(COMPARE_BYTE);
8017   testl(result, 0x1);   // tail  byte
8018   jccb(Assembler::zero, FALSE_LABEL);
8019   load_unsigned_byte(tmp1, Address(ary1, 0));
8020   andl(tmp1, 0x00000080);
8021   jccb(Assembler::notEqual, TRUE_LABEL);
8022   jmpb(FALSE_LABEL);
8023 
8024   bind(TRUE_LABEL);
8025   movl(result, 1);   // return true
8026   jmpb(DONE);
8027 
8028   bind(FALSE_LABEL);
8029   xorl(result, result); // return false
8030 
8031   // That's it
8032   bind(DONE);
8033   if (UseAVX >= 2 && UseSSE >= 2) {
8034     // clean upper bits of YMM registers
8035     vpxor(vec1, vec1);
8036     vpxor(vec2, vec2);
8037   }
8038 }
8039 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8040 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8041                                    Register limit, Register result, Register chr,
8042                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8043   ShortBranchVerifier sbv(this);
8044   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8045 
8046   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8047   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8048 
8049   if (is_array_equ) {
8050     // Check the input args
8051     cmpptr(ary1, ary2);
8052     jcc(Assembler::equal, TRUE_LABEL);
8053 
8054     // Need additional checks for arrays_equals.
8055     testptr(ary1, ary1);
8056     jcc(Assembler::zero, FALSE_LABEL);
8057     testptr(ary2, ary2);
8058     jcc(Assembler::zero, FALSE_LABEL);
8059 
8060     // Check the lengths
8061     movl(limit, Address(ary1, length_offset));
8062     cmpl(limit, Address(ary2, length_offset));
8063     jcc(Assembler::notEqual, FALSE_LABEL);
8064   }
8065 
8066   // count == 0
8067   testl(limit, limit);
8068   jcc(Assembler::zero, TRUE_LABEL);
8069 
8070   if (is_array_equ) {
8071     // Load array address
8072     lea(ary1, Address(ary1, base_offset));
8073     lea(ary2, Address(ary2, base_offset));
8074   }
8075 
8076   if (is_array_equ && is_char) {
8077     // arrays_equals when used for char[].
8078     shll(limit, 1);      // byte count != 0
8079   }
8080   movl(result, limit); // copy
8081 
8082   if (UseAVX >= 2) {
8083     // With AVX2, use 32-byte vector compare
8084     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8085 
8086     // Compare 32-byte vectors
8087     andl(result, 0x0000001f);  //   tail count (in bytes)
8088     andl(limit, 0xffffffe0);   // vector count (in bytes)
8089     jcc(Assembler::zero, COMPARE_TAIL);
8090 
8091     lea(ary1, Address(ary1, limit, Address::times_1));
8092     lea(ary2, Address(ary2, limit, Address::times_1));
8093     negptr(limit);
8094 
8095     bind(COMPARE_WIDE_VECTORS);
8096 
8097 #ifdef _LP64
8098     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8099       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8100 
8101       cmpl(limit, -64);
8102       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8103 
8104       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8105 
8106       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8107       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8108       kortestql(k7, k7);
8109       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8110       addptr(limit, 64);  // update since we already compared at this addr
8111       cmpl(limit, -64);
8112       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8113 
8114       // At this point we may still need to compare -limit+result bytes.
8115       // We could execute the next two instruction and just continue via non-wide path:
8116       //  cmpl(limit, 0);
8117       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8118       // But since we stopped at the points ary{1,2}+limit which are
8119       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8120       // (|limit| <= 32 and result < 32),
8121       // we may just compare the last 64 bytes.
8122       //
8123       addptr(result, -64);   // it is safe, bc we just came from this area
8124       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8125       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8126       kortestql(k7, k7);
8127       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8128 
8129       jmp(TRUE_LABEL);
8130 
8131       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8132 
8133     }//if (VM_Version::supports_avx512vlbw())
8134 #endif //_LP64
8135 
8136     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8137     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8138     vpxor(vec1, vec2);
8139 
8140     vptest(vec1, vec1);
8141     jcc(Assembler::notZero, FALSE_LABEL);
8142     addptr(limit, 32);
8143     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8144 
8145     testl(result, result);
8146     jcc(Assembler::zero, TRUE_LABEL);
8147 
8148     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8149     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8150     vpxor(vec1, vec2);
8151 
8152     vptest(vec1, vec1);
8153     jccb(Assembler::notZero, FALSE_LABEL);
8154     jmpb(TRUE_LABEL);
8155 
8156     bind(COMPARE_TAIL); // limit is zero
8157     movl(limit, result);
8158     // Fallthru to tail compare
8159   } else if (UseSSE42Intrinsics) {
8160     // With SSE4.2, use double quad vector compare
8161     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8162 
8163     // Compare 16-byte vectors
8164     andl(result, 0x0000000f);  //   tail count (in bytes)
8165     andl(limit, 0xfffffff0);   // vector count (in bytes)
8166     jcc(Assembler::zero, COMPARE_TAIL);
8167 
8168     lea(ary1, Address(ary1, limit, Address::times_1));
8169     lea(ary2, Address(ary2, limit, Address::times_1));
8170     negptr(limit);
8171 
8172     bind(COMPARE_WIDE_VECTORS);
8173     movdqu(vec1, Address(ary1, limit, Address::times_1));
8174     movdqu(vec2, Address(ary2, limit, Address::times_1));
8175     pxor(vec1, vec2);
8176 
8177     ptest(vec1, vec1);
8178     jcc(Assembler::notZero, FALSE_LABEL);
8179     addptr(limit, 16);
8180     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8181 
8182     testl(result, result);
8183     jcc(Assembler::zero, TRUE_LABEL);
8184 
8185     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8186     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8187     pxor(vec1, vec2);
8188 
8189     ptest(vec1, vec1);
8190     jccb(Assembler::notZero, FALSE_LABEL);
8191     jmpb(TRUE_LABEL);
8192 
8193     bind(COMPARE_TAIL); // limit is zero
8194     movl(limit, result);
8195     // Fallthru to tail compare
8196   }
8197 
8198   // Compare 4-byte vectors
8199   andl(limit, 0xfffffffc); // vector count (in bytes)
8200   jccb(Assembler::zero, COMPARE_CHAR);
8201 
8202   lea(ary1, Address(ary1, limit, Address::times_1));
8203   lea(ary2, Address(ary2, limit, Address::times_1));
8204   negptr(limit);
8205 
8206   bind(COMPARE_VECTORS);
8207   movl(chr, Address(ary1, limit, Address::times_1));
8208   cmpl(chr, Address(ary2, limit, Address::times_1));
8209   jccb(Assembler::notEqual, FALSE_LABEL);
8210   addptr(limit, 4);
8211   jcc(Assembler::notZero, COMPARE_VECTORS);
8212 
8213   // Compare trailing char (final 2 bytes), if any
8214   bind(COMPARE_CHAR);
8215   testl(result, 0x2);   // tail  char
8216   jccb(Assembler::zero, COMPARE_BYTE);
8217   load_unsigned_short(chr, Address(ary1, 0));
8218   load_unsigned_short(limit, Address(ary2, 0));
8219   cmpl(chr, limit);
8220   jccb(Assembler::notEqual, FALSE_LABEL);
8221 
8222   if (is_array_equ && is_char) {
8223     bind(COMPARE_BYTE);
8224   } else {
8225     lea(ary1, Address(ary1, 2));
8226     lea(ary2, Address(ary2, 2));
8227 
8228     bind(COMPARE_BYTE);
8229     testl(result, 0x1);   // tail  byte
8230     jccb(Assembler::zero, TRUE_LABEL);
8231     load_unsigned_byte(chr, Address(ary1, 0));
8232     load_unsigned_byte(limit, Address(ary2, 0));
8233     cmpl(chr, limit);
8234     jccb(Assembler::notEqual, FALSE_LABEL);
8235   }
8236   bind(TRUE_LABEL);
8237   movl(result, 1);   // return true
8238   jmpb(DONE);
8239 
8240   bind(FALSE_LABEL);
8241   xorl(result, result); // return false
8242 
8243   // That's it
8244   bind(DONE);
8245   if (UseAVX >= 2) {
8246     // clean upper bits of YMM registers
8247     vpxor(vec1, vec1);
8248     vpxor(vec2, vec2);
8249   }
8250 }
8251 
8252 #endif
8253 
8254 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8255                                    Register to, Register value, Register count,
8256                                    Register rtmp, XMMRegister xtmp) {
8257   ShortBranchVerifier sbv(this);
8258   assert_different_registers(to, value, count, rtmp);
8259   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8260   Label L_fill_2_bytes, L_fill_4_bytes;
8261 
8262   int shift = -1;
8263   switch (t) {
8264     case T_BYTE:
8265       shift = 2;
8266       break;
8267     case T_SHORT:
8268       shift = 1;
8269       break;
8270     case T_INT:
8271       shift = 0;
8272       break;
8273     default: ShouldNotReachHere();
8274   }
8275 
8276   if (t == T_BYTE) {
8277     andl(value, 0xff);
8278     movl(rtmp, value);
8279     shll(rtmp, 8);
8280     orl(value, rtmp);
8281   }
8282   if (t == T_SHORT) {
8283     andl(value, 0xffff);
8284   }
8285   if (t == T_BYTE || t == T_SHORT) {
8286     movl(rtmp, value);
8287     shll(rtmp, 16);
8288     orl(value, rtmp);
8289   }
8290 
8291   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8292   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8293   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8294     // align source address at 4 bytes address boundary
8295     if (t == T_BYTE) {
8296       // One byte misalignment happens only for byte arrays
8297       testptr(to, 1);
8298       jccb(Assembler::zero, L_skip_align1);
8299       movb(Address(to, 0), value);
8300       increment(to);
8301       decrement(count);
8302       BIND(L_skip_align1);
8303     }
8304     // Two bytes misalignment happens only for byte and short (char) arrays
8305     testptr(to, 2);
8306     jccb(Assembler::zero, L_skip_align2);
8307     movw(Address(to, 0), value);
8308     addptr(to, 2);
8309     subl(count, 1<<(shift-1));
8310     BIND(L_skip_align2);
8311   }
8312   if (UseSSE < 2) {
8313     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8314     // Fill 32-byte chunks
8315     subl(count, 8 << shift);
8316     jcc(Assembler::less, L_check_fill_8_bytes);
8317     align(16);
8318 
8319     BIND(L_fill_32_bytes_loop);
8320 
8321     for (int i = 0; i < 32; i += 4) {
8322       movl(Address(to, i), value);
8323     }
8324 
8325     addptr(to, 32);
8326     subl(count, 8 << shift);
8327     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8328     BIND(L_check_fill_8_bytes);
8329     addl(count, 8 << shift);
8330     jccb(Assembler::zero, L_exit);
8331     jmpb(L_fill_8_bytes);
8332 
8333     //
8334     // length is too short, just fill qwords
8335     //
8336     BIND(L_fill_8_bytes_loop);
8337     movl(Address(to, 0), value);
8338     movl(Address(to, 4), value);
8339     addptr(to, 8);
8340     BIND(L_fill_8_bytes);
8341     subl(count, 1 << (shift + 1));
8342     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8343     // fall through to fill 4 bytes
8344   } else {
8345     Label L_fill_32_bytes;
8346     if (!UseUnalignedLoadStores) {
8347       // align to 8 bytes, we know we are 4 byte aligned to start
8348       testptr(to, 4);
8349       jccb(Assembler::zero, L_fill_32_bytes);
8350       movl(Address(to, 0), value);
8351       addptr(to, 4);
8352       subl(count, 1<<shift);
8353     }
8354     BIND(L_fill_32_bytes);
8355     {
8356       assert( UseSSE >= 2, "supported cpu only" );
8357       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8358       if (UseAVX > 2) {
8359         movl(rtmp, 0xffff);
8360         kmovwl(k1, rtmp);
8361       }
8362       movdl(xtmp, value);
8363       if (UseAVX > 2 && UseUnalignedLoadStores) {
8364         // Fill 64-byte chunks
8365         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8366         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8367 
8368         subl(count, 16 << shift);
8369         jcc(Assembler::less, L_check_fill_32_bytes);
8370         align(16);
8371 
8372         BIND(L_fill_64_bytes_loop);
8373         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8374         addptr(to, 64);
8375         subl(count, 16 << shift);
8376         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8377 
8378         BIND(L_check_fill_32_bytes);
8379         addl(count, 8 << shift);
8380         jccb(Assembler::less, L_check_fill_8_bytes);
8381         vmovdqu(Address(to, 0), xtmp);
8382         addptr(to, 32);
8383         subl(count, 8 << shift);
8384 
8385         BIND(L_check_fill_8_bytes);
8386       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8387         // Fill 64-byte chunks
8388         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8389         vpbroadcastd(xtmp, xtmp);
8390 
8391         subl(count, 16 << shift);
8392         jcc(Assembler::less, L_check_fill_32_bytes);
8393         align(16);
8394 
8395         BIND(L_fill_64_bytes_loop);
8396         vmovdqu(Address(to, 0), xtmp);
8397         vmovdqu(Address(to, 32), xtmp);
8398         addptr(to, 64);
8399         subl(count, 16 << shift);
8400         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8401 
8402         BIND(L_check_fill_32_bytes);
8403         addl(count, 8 << shift);
8404         jccb(Assembler::less, L_check_fill_8_bytes);
8405         vmovdqu(Address(to, 0), xtmp);
8406         addptr(to, 32);
8407         subl(count, 8 << shift);
8408 
8409         BIND(L_check_fill_8_bytes);
8410         // clean upper bits of YMM registers
8411         movdl(xtmp, value);
8412         pshufd(xtmp, xtmp, 0);
8413       } else {
8414         // Fill 32-byte chunks
8415         pshufd(xtmp, xtmp, 0);
8416 
8417         subl(count, 8 << shift);
8418         jcc(Assembler::less, L_check_fill_8_bytes);
8419         align(16);
8420 
8421         BIND(L_fill_32_bytes_loop);
8422 
8423         if (UseUnalignedLoadStores) {
8424           movdqu(Address(to, 0), xtmp);
8425           movdqu(Address(to, 16), xtmp);
8426         } else {
8427           movq(Address(to, 0), xtmp);
8428           movq(Address(to, 8), xtmp);
8429           movq(Address(to, 16), xtmp);
8430           movq(Address(to, 24), xtmp);
8431         }
8432 
8433         addptr(to, 32);
8434         subl(count, 8 << shift);
8435         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8436 
8437         BIND(L_check_fill_8_bytes);
8438       }
8439       addl(count, 8 << shift);
8440       jccb(Assembler::zero, L_exit);
8441       jmpb(L_fill_8_bytes);
8442 
8443       //
8444       // length is too short, just fill qwords
8445       //
8446       BIND(L_fill_8_bytes_loop);
8447       movq(Address(to, 0), xtmp);
8448       addptr(to, 8);
8449       BIND(L_fill_8_bytes);
8450       subl(count, 1 << (shift + 1));
8451       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8452     }
8453   }
8454   // fill trailing 4 bytes
8455   BIND(L_fill_4_bytes);
8456   testl(count, 1<<shift);
8457   jccb(Assembler::zero, L_fill_2_bytes);
8458   movl(Address(to, 0), value);
8459   if (t == T_BYTE || t == T_SHORT) {
8460     addptr(to, 4);
8461     BIND(L_fill_2_bytes);
8462     // fill trailing 2 bytes
8463     testl(count, 1<<(shift-1));
8464     jccb(Assembler::zero, L_fill_byte);
8465     movw(Address(to, 0), value);
8466     if (t == T_BYTE) {
8467       addptr(to, 2);
8468       BIND(L_fill_byte);
8469       // fill trailing byte
8470       testl(count, 1);
8471       jccb(Assembler::zero, L_exit);
8472       movb(Address(to, 0), value);
8473     } else {
8474       BIND(L_fill_byte);
8475     }
8476   } else {
8477     BIND(L_fill_2_bytes);
8478   }
8479   BIND(L_exit);
8480 }
8481 
8482 // encode char[] to byte[] in ISO_8859_1
8483    //@HotSpotIntrinsicCandidate
8484    //private static int implEncodeISOArray(byte[] sa, int sp,
8485    //byte[] da, int dp, int len) {
8486    //  int i = 0;
8487    //  for (; i < len; i++) {
8488    //    char c = StringUTF16.getChar(sa, sp++);
8489    //    if (c > '\u00FF')
8490    //      break;
8491    //    da[dp++] = (byte)c;
8492    //  }
8493    //  return i;
8494    //}
8495 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8496   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8497   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8498   Register tmp5, Register result) {
8499 
8500   // rsi: src
8501   // rdi: dst
8502   // rdx: len
8503   // rcx: tmp5
8504   // rax: result
8505   ShortBranchVerifier sbv(this);
8506   assert_different_registers(src, dst, len, tmp5, result);
8507   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8508 
8509   // set result
8510   xorl(result, result);
8511   // check for zero length
8512   testl(len, len);
8513   jcc(Assembler::zero, L_done);
8514 
8515   movl(result, len);
8516 
8517   // Setup pointers
8518   lea(src, Address(src, len, Address::times_2)); // char[]
8519   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8520   negptr(len);
8521 
8522   if (UseSSE42Intrinsics || UseAVX >= 2) {
8523     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8524     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8525 
8526     if (UseAVX >= 2) {
8527       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8528       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8529       movdl(tmp1Reg, tmp5);
8530       vpbroadcastd(tmp1Reg, tmp1Reg);
8531       jmp(L_chars_32_check);
8532 
8533       bind(L_copy_32_chars);
8534       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8535       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8536       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8537       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8538       jccb(Assembler::notZero, L_copy_32_chars_exit);
8539       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8540       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8541       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8542 
8543       bind(L_chars_32_check);
8544       addptr(len, 32);
8545       jcc(Assembler::lessEqual, L_copy_32_chars);
8546 
8547       bind(L_copy_32_chars_exit);
8548       subptr(len, 16);
8549       jccb(Assembler::greater, L_copy_16_chars_exit);
8550 
8551     } else if (UseSSE42Intrinsics) {
8552       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8553       movdl(tmp1Reg, tmp5);
8554       pshufd(tmp1Reg, tmp1Reg, 0);
8555       jmpb(L_chars_16_check);
8556     }
8557 
8558     bind(L_copy_16_chars);
8559     if (UseAVX >= 2) {
8560       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8561       vptest(tmp2Reg, tmp1Reg);
8562       jcc(Assembler::notZero, L_copy_16_chars_exit);
8563       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8564       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8565     } else {
8566       if (UseAVX > 0) {
8567         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8568         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8569         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8570       } else {
8571         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8572         por(tmp2Reg, tmp3Reg);
8573         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8574         por(tmp2Reg, tmp4Reg);
8575       }
8576       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8577       jccb(Assembler::notZero, L_copy_16_chars_exit);
8578       packuswb(tmp3Reg, tmp4Reg);
8579     }
8580     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8581 
8582     bind(L_chars_16_check);
8583     addptr(len, 16);
8584     jcc(Assembler::lessEqual, L_copy_16_chars);
8585 
8586     bind(L_copy_16_chars_exit);
8587     if (UseAVX >= 2) {
8588       // clean upper bits of YMM registers
8589       vpxor(tmp2Reg, tmp2Reg);
8590       vpxor(tmp3Reg, tmp3Reg);
8591       vpxor(tmp4Reg, tmp4Reg);
8592       movdl(tmp1Reg, tmp5);
8593       pshufd(tmp1Reg, tmp1Reg, 0);
8594     }
8595     subptr(len, 8);
8596     jccb(Assembler::greater, L_copy_8_chars_exit);
8597 
8598     bind(L_copy_8_chars);
8599     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8600     ptest(tmp3Reg, tmp1Reg);
8601     jccb(Assembler::notZero, L_copy_8_chars_exit);
8602     packuswb(tmp3Reg, tmp1Reg);
8603     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8604     addptr(len, 8);
8605     jccb(Assembler::lessEqual, L_copy_8_chars);
8606 
8607     bind(L_copy_8_chars_exit);
8608     subptr(len, 8);
8609     jccb(Assembler::zero, L_done);
8610   }
8611 
8612   bind(L_copy_1_char);
8613   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8614   testl(tmp5, 0xff00);      // check if Unicode char
8615   jccb(Assembler::notZero, L_copy_1_char_exit);
8616   movb(Address(dst, len, Address::times_1, 0), tmp5);
8617   addptr(len, 1);
8618   jccb(Assembler::less, L_copy_1_char);
8619 
8620   bind(L_copy_1_char_exit);
8621   addptr(result, len); // len is negative count of not processed elements
8622 
8623   bind(L_done);
8624 }
8625 
8626 #ifdef _LP64
8627 /**
8628  * Helper for multiply_to_len().
8629  */
8630 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8631   addq(dest_lo, src1);
8632   adcq(dest_hi, 0);
8633   addq(dest_lo, src2);
8634   adcq(dest_hi, 0);
8635 }
8636 
8637 /**
8638  * Multiply 64 bit by 64 bit first loop.
8639  */
8640 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8641                                            Register y, Register y_idx, Register z,
8642                                            Register carry, Register product,
8643                                            Register idx, Register kdx) {
8644   //
8645   //  jlong carry, x[], y[], z[];
8646   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8647   //    huge_128 product = y[idx] * x[xstart] + carry;
8648   //    z[kdx] = (jlong)product;
8649   //    carry  = (jlong)(product >>> 64);
8650   //  }
8651   //  z[xstart] = carry;
8652   //
8653 
8654   Label L_first_loop, L_first_loop_exit;
8655   Label L_one_x, L_one_y, L_multiply;
8656 
8657   decrementl(xstart);
8658   jcc(Assembler::negative, L_one_x);
8659 
8660   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8661   rorq(x_xstart, 32); // convert big-endian to little-endian
8662 
8663   bind(L_first_loop);
8664   decrementl(idx);
8665   jcc(Assembler::negative, L_first_loop_exit);
8666   decrementl(idx);
8667   jcc(Assembler::negative, L_one_y);
8668   movq(y_idx, Address(y, idx, Address::times_4,  0));
8669   rorq(y_idx, 32); // convert big-endian to little-endian
8670   bind(L_multiply);
8671   movq(product, x_xstart);
8672   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8673   addq(product, carry);
8674   adcq(rdx, 0);
8675   subl(kdx, 2);
8676   movl(Address(z, kdx, Address::times_4,  4), product);
8677   shrq(product, 32);
8678   movl(Address(z, kdx, Address::times_4,  0), product);
8679   movq(carry, rdx);
8680   jmp(L_first_loop);
8681 
8682   bind(L_one_y);
8683   movl(y_idx, Address(y,  0));
8684   jmp(L_multiply);
8685 
8686   bind(L_one_x);
8687   movl(x_xstart, Address(x,  0));
8688   jmp(L_first_loop);
8689 
8690   bind(L_first_loop_exit);
8691 }
8692 
8693 /**
8694  * Multiply 64 bit by 64 bit and add 128 bit.
8695  */
8696 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8697                                             Register yz_idx, Register idx,
8698                                             Register carry, Register product, int offset) {
8699   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8700   //     z[kdx] = (jlong)product;
8701 
8702   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8703   rorq(yz_idx, 32); // convert big-endian to little-endian
8704   movq(product, x_xstart);
8705   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8706   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8707   rorq(yz_idx, 32); // convert big-endian to little-endian
8708 
8709   add2_with_carry(rdx, product, carry, yz_idx);
8710 
8711   movl(Address(z, idx, Address::times_4,  offset+4), product);
8712   shrq(product, 32);
8713   movl(Address(z, idx, Address::times_4,  offset), product);
8714 
8715 }
8716 
8717 /**
8718  * Multiply 128 bit by 128 bit. Unrolled inner loop.
8719  */
8720 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
8721                                              Register yz_idx, Register idx, Register jdx,
8722                                              Register carry, Register product,
8723                                              Register carry2) {
8724   //   jlong carry, x[], y[], z[];
8725   //   int kdx = ystart+1;
8726   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8727   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
8728   //     z[kdx+idx+1] = (jlong)product;
8729   //     jlong carry2  = (jlong)(product >>> 64);
8730   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
8731   //     z[kdx+idx] = (jlong)product;
8732   //     carry  = (jlong)(product >>> 64);
8733   //   }
8734   //   idx += 2;
8735   //   if (idx > 0) {
8736   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
8737   //     z[kdx+idx] = (jlong)product;
8738   //     carry  = (jlong)(product >>> 64);
8739   //   }
8740   //
8741 
8742   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8743 
8744   movl(jdx, idx);
8745   andl(jdx, 0xFFFFFFFC);
8746   shrl(jdx, 2);
8747 
8748   bind(L_third_loop);
8749   subl(jdx, 1);
8750   jcc(Assembler::negative, L_third_loop_exit);
8751   subl(idx, 4);
8752 
8753   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
8754   movq(carry2, rdx);
8755 
8756   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
8757   movq(carry, rdx);
8758   jmp(L_third_loop);
8759 
8760   bind (L_third_loop_exit);
8761 
8762   andl (idx, 0x3);
8763   jcc(Assembler::zero, L_post_third_loop_done);
8764 
8765   Label L_check_1;
8766   subl(idx, 2);
8767   jcc(Assembler::negative, L_check_1);
8768 
8769   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
8770   movq(carry, rdx);
8771 
8772   bind (L_check_1);
8773   addl (idx, 0x2);
8774   andl (idx, 0x1);
8775   subl(idx, 1);
8776   jcc(Assembler::negative, L_post_third_loop_done);
8777 
8778   movl(yz_idx, Address(y, idx, Address::times_4,  0));
8779   movq(product, x_xstart);
8780   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
8781   movl(yz_idx, Address(z, idx, Address::times_4,  0));
8782 
8783   add2_with_carry(rdx, product, yz_idx, carry);
8784 
8785   movl(Address(z, idx, Address::times_4,  0), product);
8786   shrq(product, 32);
8787 
8788   shlq(rdx, 32);
8789   orq(product, rdx);
8790   movq(carry, product);
8791 
8792   bind(L_post_third_loop_done);
8793 }
8794 
8795 /**
8796  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
8797  *
8798  */
8799 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
8800                                                   Register carry, Register carry2,
8801                                                   Register idx, Register jdx,
8802                                                   Register yz_idx1, Register yz_idx2,
8803                                                   Register tmp, Register tmp3, Register tmp4) {
8804   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
8805 
8806   //   jlong carry, x[], y[], z[];
8807   //   int kdx = ystart+1;
8808   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8809   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
8810   //     jlong carry2  = (jlong)(tmp3 >>> 64);
8811   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
8812   //     carry  = (jlong)(tmp4 >>> 64);
8813   //     z[kdx+idx+1] = (jlong)tmp3;
8814   //     z[kdx+idx] = (jlong)tmp4;
8815   //   }
8816   //   idx += 2;
8817   //   if (idx > 0) {
8818   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
8819   //     z[kdx+idx] = (jlong)yz_idx1;
8820   //     carry  = (jlong)(yz_idx1 >>> 64);
8821   //   }
8822   //
8823 
8824   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8825 
8826   movl(jdx, idx);
8827   andl(jdx, 0xFFFFFFFC);
8828   shrl(jdx, 2);
8829 
8830   bind(L_third_loop);
8831   subl(jdx, 1);
8832   jcc(Assembler::negative, L_third_loop_exit);
8833   subl(idx, 4);
8834 
8835   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
8836   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
8837   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
8838   rorxq(yz_idx2, yz_idx2, 32);
8839 
8840   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
8841   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
8842 
8843   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
8844   rorxq(yz_idx1, yz_idx1, 32);
8845   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8846   rorxq(yz_idx2, yz_idx2, 32);
8847 
8848   if (VM_Version::supports_adx()) {
8849     adcxq(tmp3, carry);
8850     adoxq(tmp3, yz_idx1);
8851 
8852     adcxq(tmp4, tmp);
8853     adoxq(tmp4, yz_idx2);
8854 
8855     movl(carry, 0); // does not affect flags
8856     adcxq(carry2, carry);
8857     adoxq(carry2, carry);
8858   } else {
8859     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
8860     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
8861   }
8862   movq(carry, carry2);
8863 
8864   movl(Address(z, idx, Address::times_4, 12), tmp3);
8865   shrq(tmp3, 32);
8866   movl(Address(z, idx, Address::times_4,  8), tmp3);
8867 
8868   movl(Address(z, idx, Address::times_4,  4), tmp4);
8869   shrq(tmp4, 32);
8870   movl(Address(z, idx, Address::times_4,  0), tmp4);
8871 
8872   jmp(L_third_loop);
8873 
8874   bind (L_third_loop_exit);
8875 
8876   andl (idx, 0x3);
8877   jcc(Assembler::zero, L_post_third_loop_done);
8878 
8879   Label L_check_1;
8880   subl(idx, 2);
8881   jcc(Assembler::negative, L_check_1);
8882 
8883   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
8884   rorxq(yz_idx1, yz_idx1, 32);
8885   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
8886   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8887   rorxq(yz_idx2, yz_idx2, 32);
8888 
8889   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
8890 
8891   movl(Address(z, idx, Address::times_4,  4), tmp3);
8892   shrq(tmp3, 32);
8893   movl(Address(z, idx, Address::times_4,  0), tmp3);
8894   movq(carry, tmp4);
8895 
8896   bind (L_check_1);
8897   addl (idx, 0x2);
8898   andl (idx, 0x1);
8899   subl(idx, 1);
8900   jcc(Assembler::negative, L_post_third_loop_done);
8901   movl(tmp4, Address(y, idx, Address::times_4,  0));
8902   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
8903   movl(tmp4, Address(z, idx, Address::times_4,  0));
8904 
8905   add2_with_carry(carry2, tmp3, tmp4, carry);
8906 
8907   movl(Address(z, idx, Address::times_4,  0), tmp3);
8908   shrq(tmp3, 32);
8909 
8910   shlq(carry2, 32);
8911   orq(tmp3, carry2);
8912   movq(carry, tmp3);
8913 
8914   bind(L_post_third_loop_done);
8915 }
8916 
8917 /**
8918  * Code for BigInteger::multiplyToLen() instrinsic.
8919  *
8920  * rdi: x
8921  * rax: xlen
8922  * rsi: y
8923  * rcx: ylen
8924  * r8:  z
8925  * r11: zlen
8926  * r12: tmp1
8927  * r13: tmp2
8928  * r14: tmp3
8929  * r15: tmp4
8930  * rbx: tmp5
8931  *
8932  */
8933 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
8934                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
8935   ShortBranchVerifier sbv(this);
8936   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
8937 
8938   push(tmp1);
8939   push(tmp2);
8940   push(tmp3);
8941   push(tmp4);
8942   push(tmp5);
8943 
8944   push(xlen);
8945   push(zlen);
8946 
8947   const Register idx = tmp1;
8948   const Register kdx = tmp2;
8949   const Register xstart = tmp3;
8950 
8951   const Register y_idx = tmp4;
8952   const Register carry = tmp5;
8953   const Register product  = xlen;
8954   const Register x_xstart = zlen;  // reuse register
8955 
8956   // First Loop.
8957   //
8958   //  final static long LONG_MASK = 0xffffffffL;
8959   //  int xstart = xlen - 1;
8960   //  int ystart = ylen - 1;
8961   //  long carry = 0;
8962   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8963   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
8964   //    z[kdx] = (int)product;
8965   //    carry = product >>> 32;
8966   //  }
8967   //  z[xstart] = (int)carry;
8968   //
8969 
8970   movl(idx, ylen);      // idx = ylen;
8971   movl(kdx, zlen);      // kdx = xlen+ylen;
8972   xorq(carry, carry);   // carry = 0;
8973 
8974   Label L_done;
8975 
8976   movl(xstart, xlen);
8977   decrementl(xstart);
8978   jcc(Assembler::negative, L_done);
8979 
8980   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
8981 
8982   Label L_second_loop;
8983   testl(kdx, kdx);
8984   jcc(Assembler::zero, L_second_loop);
8985 
8986   Label L_carry;
8987   subl(kdx, 1);
8988   jcc(Assembler::zero, L_carry);
8989 
8990   movl(Address(z, kdx, Address::times_4,  0), carry);
8991   shrq(carry, 32);
8992   subl(kdx, 1);
8993 
8994   bind(L_carry);
8995   movl(Address(z, kdx, Address::times_4,  0), carry);
8996 
8997   // Second and third (nested) loops.
8998   //
8999   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9000   //   carry = 0;
9001   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9002   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9003   //                    (z[k] & LONG_MASK) + carry;
9004   //     z[k] = (int)product;
9005   //     carry = product >>> 32;
9006   //   }
9007   //   z[i] = (int)carry;
9008   // }
9009   //
9010   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9011 
9012   const Register jdx = tmp1;
9013 
9014   bind(L_second_loop);
9015   xorl(carry, carry);    // carry = 0;
9016   movl(jdx, ylen);       // j = ystart+1
9017 
9018   subl(xstart, 1);       // i = xstart-1;
9019   jcc(Assembler::negative, L_done);
9020 
9021   push (z);
9022 
9023   Label L_last_x;
9024   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9025   subl(xstart, 1);       // i = xstart-1;
9026   jcc(Assembler::negative, L_last_x);
9027 
9028   if (UseBMI2Instructions) {
9029     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9030     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9031   } else {
9032     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9033     rorq(x_xstart, 32);  // convert big-endian to little-endian
9034   }
9035 
9036   Label L_third_loop_prologue;
9037   bind(L_third_loop_prologue);
9038 
9039   push (x);
9040   push (xstart);
9041   push (ylen);
9042 
9043 
9044   if (UseBMI2Instructions) {
9045     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9046   } else { // !UseBMI2Instructions
9047     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9048   }
9049 
9050   pop(ylen);
9051   pop(xlen);
9052   pop(x);
9053   pop(z);
9054 
9055   movl(tmp3, xlen);
9056   addl(tmp3, 1);
9057   movl(Address(z, tmp3, Address::times_4,  0), carry);
9058   subl(tmp3, 1);
9059   jccb(Assembler::negative, L_done);
9060 
9061   shrq(carry, 32);
9062   movl(Address(z, tmp3, Address::times_4,  0), carry);
9063   jmp(L_second_loop);
9064 
9065   // Next infrequent code is moved outside loops.
9066   bind(L_last_x);
9067   if (UseBMI2Instructions) {
9068     movl(rdx, Address(x,  0));
9069   } else {
9070     movl(x_xstart, Address(x,  0));
9071   }
9072   jmp(L_third_loop_prologue);
9073 
9074   bind(L_done);
9075 
9076   pop(zlen);
9077   pop(xlen);
9078 
9079   pop(tmp5);
9080   pop(tmp4);
9081   pop(tmp3);
9082   pop(tmp2);
9083   pop(tmp1);
9084 }
9085 
9086 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9087   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9088   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9089   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9090   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9091   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9092   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9093   Label SAME_TILL_END, DONE;
9094   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9095 
9096   //scale is in rcx in both Win64 and Unix
9097   ShortBranchVerifier sbv(this);
9098 
9099   shlq(length);
9100   xorq(result, result);
9101 
9102   if ((UseAVX > 2) &&
9103       VM_Version::supports_avx512vlbw()) {
9104     set_vector_masking();  // opening of the stub context for programming mask registers
9105     cmpq(length, 64);
9106     jcc(Assembler::less, VECTOR32_TAIL);
9107     movq(tmp1, length);
9108     andq(tmp1, 0x3F);      // tail count
9109     andq(length, ~(0x3F)); //vector count
9110 
9111     bind(VECTOR64_LOOP);
9112     // AVX512 code to compare 64 byte vectors.
9113     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9114     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9115     kortestql(k7, k7);
9116     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9117     addq(result, 64);
9118     subq(length, 64);
9119     jccb(Assembler::notZero, VECTOR64_LOOP);
9120 
9121     //bind(VECTOR64_TAIL);
9122     testq(tmp1, tmp1);
9123     jcc(Assembler::zero, SAME_TILL_END);
9124 
9125     bind(VECTOR64_TAIL);
9126     // AVX512 code to compare upto 63 byte vectors.
9127     // Save k1
9128     kmovql(k3, k1);
9129     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9130     shlxq(tmp2, tmp2, tmp1);
9131     notq(tmp2);
9132     kmovql(k1, tmp2);
9133 
9134     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9135     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9136 
9137     ktestql(k7, k1);
9138     // Restore k1
9139     kmovql(k1, k3);
9140     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9141 
9142     bind(VECTOR64_NOT_EQUAL);
9143     kmovql(tmp1, k7);
9144     notq(tmp1);
9145     tzcntq(tmp1, tmp1);
9146     addq(result, tmp1);
9147     shrq(result);
9148     jmp(DONE);
9149     bind(VECTOR32_TAIL);
9150     clear_vector_masking();   // closing of the stub context for programming mask registers
9151   }
9152 
9153   cmpq(length, 8);
9154   jcc(Assembler::equal, VECTOR8_LOOP);
9155   jcc(Assembler::less, VECTOR4_TAIL);
9156 
9157   if (UseAVX >= 2) {
9158 
9159     cmpq(length, 16);
9160     jcc(Assembler::equal, VECTOR16_LOOP);
9161     jcc(Assembler::less, VECTOR8_LOOP);
9162 
9163     cmpq(length, 32);
9164     jccb(Assembler::less, VECTOR16_TAIL);
9165 
9166     subq(length, 32);
9167     bind(VECTOR32_LOOP);
9168     vmovdqu(rymm0, Address(obja, result));
9169     vmovdqu(rymm1, Address(objb, result));
9170     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9171     vptest(rymm2, rymm2);
9172     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9173     addq(result, 32);
9174     subq(length, 32);
9175     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9176     addq(length, 32);
9177     jcc(Assembler::equal, SAME_TILL_END);
9178     //falling through if less than 32 bytes left //close the branch here.
9179 
9180     bind(VECTOR16_TAIL);
9181     cmpq(length, 16);
9182     jccb(Assembler::less, VECTOR8_TAIL);
9183     bind(VECTOR16_LOOP);
9184     movdqu(rymm0, Address(obja, result));
9185     movdqu(rymm1, Address(objb, result));
9186     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9187     ptest(rymm2, rymm2);
9188     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9189     addq(result, 16);
9190     subq(length, 16);
9191     jcc(Assembler::equal, SAME_TILL_END);
9192     //falling through if less than 16 bytes left
9193   } else {//regular intrinsics
9194 
9195     cmpq(length, 16);
9196     jccb(Assembler::less, VECTOR8_TAIL);
9197 
9198     subq(length, 16);
9199     bind(VECTOR16_LOOP);
9200     movdqu(rymm0, Address(obja, result));
9201     movdqu(rymm1, Address(objb, result));
9202     pxor(rymm0, rymm1);
9203     ptest(rymm0, rymm0);
9204     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9205     addq(result, 16);
9206     subq(length, 16);
9207     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9208     addq(length, 16);
9209     jcc(Assembler::equal, SAME_TILL_END);
9210     //falling through if less than 16 bytes left
9211   }
9212 
9213   bind(VECTOR8_TAIL);
9214   cmpq(length, 8);
9215   jccb(Assembler::less, VECTOR4_TAIL);
9216   bind(VECTOR8_LOOP);
9217   movq(tmp1, Address(obja, result));
9218   movq(tmp2, Address(objb, result));
9219   xorq(tmp1, tmp2);
9220   testq(tmp1, tmp1);
9221   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9222   addq(result, 8);
9223   subq(length, 8);
9224   jcc(Assembler::equal, SAME_TILL_END);
9225   //falling through if less than 8 bytes left
9226 
9227   bind(VECTOR4_TAIL);
9228   cmpq(length, 4);
9229   jccb(Assembler::less, BYTES_TAIL);
9230   bind(VECTOR4_LOOP);
9231   movl(tmp1, Address(obja, result));
9232   xorl(tmp1, Address(objb, result));
9233   testl(tmp1, tmp1);
9234   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9235   addq(result, 4);
9236   subq(length, 4);
9237   jcc(Assembler::equal, SAME_TILL_END);
9238   //falling through if less than 4 bytes left
9239 
9240   bind(BYTES_TAIL);
9241   bind(BYTES_LOOP);
9242   load_unsigned_byte(tmp1, Address(obja, result));
9243   load_unsigned_byte(tmp2, Address(objb, result));
9244   xorl(tmp1, tmp2);
9245   testl(tmp1, tmp1);
9246   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9247   decq(length);
9248   jccb(Assembler::zero, SAME_TILL_END);
9249   incq(result);
9250   load_unsigned_byte(tmp1, Address(obja, result));
9251   load_unsigned_byte(tmp2, Address(objb, result));
9252   xorl(tmp1, tmp2);
9253   testl(tmp1, tmp1);
9254   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9255   decq(length);
9256   jccb(Assembler::zero, SAME_TILL_END);
9257   incq(result);
9258   load_unsigned_byte(tmp1, Address(obja, result));
9259   load_unsigned_byte(tmp2, Address(objb, result));
9260   xorl(tmp1, tmp2);
9261   testl(tmp1, tmp1);
9262   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9263   jmpb(SAME_TILL_END);
9264 
9265   if (UseAVX >= 2) {
9266     bind(VECTOR32_NOT_EQUAL);
9267     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9268     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9269     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9270     vpmovmskb(tmp1, rymm0);
9271     bsfq(tmp1, tmp1);
9272     addq(result, tmp1);
9273     shrq(result);
9274     jmpb(DONE);
9275   }
9276 
9277   bind(VECTOR16_NOT_EQUAL);
9278   if (UseAVX >= 2) {
9279     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9280     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9281     pxor(rymm0, rymm2);
9282   } else {
9283     pcmpeqb(rymm2, rymm2);
9284     pxor(rymm0, rymm1);
9285     pcmpeqb(rymm0, rymm1);
9286     pxor(rymm0, rymm2);
9287   }
9288   pmovmskb(tmp1, rymm0);
9289   bsfq(tmp1, tmp1);
9290   addq(result, tmp1);
9291   shrq(result);
9292   jmpb(DONE);
9293 
9294   bind(VECTOR8_NOT_EQUAL);
9295   bind(VECTOR4_NOT_EQUAL);
9296   bsfq(tmp1, tmp1);
9297   shrq(tmp1, 3);
9298   addq(result, tmp1);
9299   bind(BYTES_NOT_EQUAL);
9300   shrq(result);
9301   jmpb(DONE);
9302 
9303   bind(SAME_TILL_END);
9304   mov64(result, -1);
9305 
9306   bind(DONE);
9307 }
9308 
9309 //Helper functions for square_to_len()
9310 
9311 /**
9312  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9313  * Preserves x and z and modifies rest of the registers.
9314  */
9315 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9316   // Perform square and right shift by 1
9317   // Handle odd xlen case first, then for even xlen do the following
9318   // jlong carry = 0;
9319   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9320   //     huge_128 product = x[j:j+1] * x[j:j+1];
9321   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9322   //     z[i+2:i+3] = (jlong)(product >>> 1);
9323   //     carry = (jlong)product;
9324   // }
9325 
9326   xorq(tmp5, tmp5);     // carry
9327   xorq(rdxReg, rdxReg);
9328   xorl(tmp1, tmp1);     // index for x
9329   xorl(tmp4, tmp4);     // index for z
9330 
9331   Label L_first_loop, L_first_loop_exit;
9332 
9333   testl(xlen, 1);
9334   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9335 
9336   // Square and right shift by 1 the odd element using 32 bit multiply
9337   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9338   imulq(raxReg, raxReg);
9339   shrq(raxReg, 1);
9340   adcq(tmp5, 0);
9341   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9342   incrementl(tmp1);
9343   addl(tmp4, 2);
9344 
9345   // Square and  right shift by 1 the rest using 64 bit multiply
9346   bind(L_first_loop);
9347   cmpptr(tmp1, xlen);
9348   jccb(Assembler::equal, L_first_loop_exit);
9349 
9350   // Square
9351   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9352   rorq(raxReg, 32);    // convert big-endian to little-endian
9353   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9354 
9355   // Right shift by 1 and save carry
9356   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9357   rcrq(rdxReg, 1);
9358   rcrq(raxReg, 1);
9359   adcq(tmp5, 0);
9360 
9361   // Store result in z
9362   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9363   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9364 
9365   // Update indices for x and z
9366   addl(tmp1, 2);
9367   addl(tmp4, 4);
9368   jmp(L_first_loop);
9369 
9370   bind(L_first_loop_exit);
9371 }
9372 
9373 
9374 /**
9375  * Perform the following multiply add operation using BMI2 instructions
9376  * carry:sum = sum + op1*op2 + carry
9377  * op2 should be in rdx
9378  * op2 is preserved, all other registers are modified
9379  */
9380 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9381   // assert op2 is rdx
9382   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9383   addq(sum, carry);
9384   adcq(tmp2, 0);
9385   addq(sum, op1);
9386   adcq(tmp2, 0);
9387   movq(carry, tmp2);
9388 }
9389 
9390 /**
9391  * Perform the following multiply add operation:
9392  * carry:sum = sum + op1*op2 + carry
9393  * Preserves op1, op2 and modifies rest of registers
9394  */
9395 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9396   // rdx:rax = op1 * op2
9397   movq(raxReg, op2);
9398   mulq(op1);
9399 
9400   //  rdx:rax = sum + carry + rdx:rax
9401   addq(sum, carry);
9402   adcq(rdxReg, 0);
9403   addq(sum, raxReg);
9404   adcq(rdxReg, 0);
9405 
9406   // carry:sum = rdx:sum
9407   movq(carry, rdxReg);
9408 }
9409 
9410 /**
9411  * Add 64 bit long carry into z[] with carry propogation.
9412  * Preserves z and carry register values and modifies rest of registers.
9413  *
9414  */
9415 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9416   Label L_fourth_loop, L_fourth_loop_exit;
9417 
9418   movl(tmp1, 1);
9419   subl(zlen, 2);
9420   addq(Address(z, zlen, Address::times_4, 0), carry);
9421 
9422   bind(L_fourth_loop);
9423   jccb(Assembler::carryClear, L_fourth_loop_exit);
9424   subl(zlen, 2);
9425   jccb(Assembler::negative, L_fourth_loop_exit);
9426   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9427   jmp(L_fourth_loop);
9428   bind(L_fourth_loop_exit);
9429 }
9430 
9431 /**
9432  * Shift z[] left by 1 bit.
9433  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9434  *
9435  */
9436 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9437 
9438   Label L_fifth_loop, L_fifth_loop_exit;
9439 
9440   // Fifth loop
9441   // Perform primitiveLeftShift(z, zlen, 1)
9442 
9443   const Register prev_carry = tmp1;
9444   const Register new_carry = tmp4;
9445   const Register value = tmp2;
9446   const Register zidx = tmp3;
9447 
9448   // int zidx, carry;
9449   // long value;
9450   // carry = 0;
9451   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9452   //    (carry:value)  = (z[i] << 1) | carry ;
9453   //    z[i] = value;
9454   // }
9455 
9456   movl(zidx, zlen);
9457   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9458 
9459   bind(L_fifth_loop);
9460   decl(zidx);  // Use decl to preserve carry flag
9461   decl(zidx);
9462   jccb(Assembler::negative, L_fifth_loop_exit);
9463 
9464   if (UseBMI2Instructions) {
9465      movq(value, Address(z, zidx, Address::times_4, 0));
9466      rclq(value, 1);
9467      rorxq(value, value, 32);
9468      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9469   }
9470   else {
9471     // clear new_carry
9472     xorl(new_carry, new_carry);
9473 
9474     // Shift z[i] by 1, or in previous carry and save new carry
9475     movq(value, Address(z, zidx, Address::times_4, 0));
9476     shlq(value, 1);
9477     adcl(new_carry, 0);
9478 
9479     orq(value, prev_carry);
9480     rorq(value, 0x20);
9481     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9482 
9483     // Set previous carry = new carry
9484     movl(prev_carry, new_carry);
9485   }
9486   jmp(L_fifth_loop);
9487 
9488   bind(L_fifth_loop_exit);
9489 }
9490 
9491 
9492 /**
9493  * Code for BigInteger::squareToLen() intrinsic
9494  *
9495  * rdi: x
9496  * rsi: len
9497  * r8:  z
9498  * rcx: zlen
9499  * r12: tmp1
9500  * r13: tmp2
9501  * r14: tmp3
9502  * r15: tmp4
9503  * rbx: tmp5
9504  *
9505  */
9506 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) {
9507 
9508   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;
9509   push(tmp1);
9510   push(tmp2);
9511   push(tmp3);
9512   push(tmp4);
9513   push(tmp5);
9514 
9515   // First loop
9516   // Store the squares, right shifted one bit (i.e., divided by 2).
9517   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9518 
9519   // Add in off-diagonal sums.
9520   //
9521   // Second, third (nested) and fourth loops.
9522   // zlen +=2;
9523   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9524   //    carry = 0;
9525   //    long op2 = x[xidx:xidx+1];
9526   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9527   //       k -= 2;
9528   //       long op1 = x[j:j+1];
9529   //       long sum = z[k:k+1];
9530   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9531   //       z[k:k+1] = sum;
9532   //    }
9533   //    add_one_64(z, k, carry, tmp_regs);
9534   // }
9535 
9536   const Register carry = tmp5;
9537   const Register sum = tmp3;
9538   const Register op1 = tmp4;
9539   Register op2 = tmp2;
9540 
9541   push(zlen);
9542   push(len);
9543   addl(zlen,2);
9544   bind(L_second_loop);
9545   xorq(carry, carry);
9546   subl(zlen, 4);
9547   subl(len, 2);
9548   push(zlen);
9549   push(len);
9550   cmpl(len, 0);
9551   jccb(Assembler::lessEqual, L_second_loop_exit);
9552 
9553   // Multiply an array by one 64 bit long.
9554   if (UseBMI2Instructions) {
9555     op2 = rdxReg;
9556     movq(op2, Address(x, len, Address::times_4,  0));
9557     rorxq(op2, op2, 32);
9558   }
9559   else {
9560     movq(op2, Address(x, len, Address::times_4,  0));
9561     rorq(op2, 32);
9562   }
9563 
9564   bind(L_third_loop);
9565   decrementl(len);
9566   jccb(Assembler::negative, L_third_loop_exit);
9567   decrementl(len);
9568   jccb(Assembler::negative, L_last_x);
9569 
9570   movq(op1, Address(x, len, Address::times_4,  0));
9571   rorq(op1, 32);
9572 
9573   bind(L_multiply);
9574   subl(zlen, 2);
9575   movq(sum, Address(z, zlen, Address::times_4,  0));
9576 
9577   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9578   if (UseBMI2Instructions) {
9579     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9580   }
9581   else {
9582     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9583   }
9584 
9585   movq(Address(z, zlen, Address::times_4, 0), sum);
9586 
9587   jmp(L_third_loop);
9588   bind(L_third_loop_exit);
9589 
9590   // Fourth loop
9591   // Add 64 bit long carry into z with carry propogation.
9592   // Uses offsetted zlen.
9593   add_one_64(z, zlen, carry, tmp1);
9594 
9595   pop(len);
9596   pop(zlen);
9597   jmp(L_second_loop);
9598 
9599   // Next infrequent code is moved outside loops.
9600   bind(L_last_x);
9601   movl(op1, Address(x, 0));
9602   jmp(L_multiply);
9603 
9604   bind(L_second_loop_exit);
9605   pop(len);
9606   pop(zlen);
9607   pop(len);
9608   pop(zlen);
9609 
9610   // Fifth loop
9611   // Shift z left 1 bit.
9612   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9613 
9614   // z[zlen-1] |= x[len-1] & 1;
9615   movl(tmp3, Address(x, len, Address::times_4, -4));
9616   andl(tmp3, 1);
9617   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9618 
9619   pop(tmp5);
9620   pop(tmp4);
9621   pop(tmp3);
9622   pop(tmp2);
9623   pop(tmp1);
9624 }
9625 
9626 /**
9627  * Helper function for mul_add()
9628  * Multiply the in[] by int k and add to out[] starting at offset offs using
9629  * 128 bit by 32 bit multiply and return the carry in tmp5.
9630  * Only quad int aligned length of in[] is operated on in this function.
9631  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9632  * This function preserves out, in and k registers.
9633  * len and offset point to the appropriate index in "in" & "out" correspondingly
9634  * tmp5 has the carry.
9635  * other registers are temporary and are modified.
9636  *
9637  */
9638 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9639   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9640   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9641 
9642   Label L_first_loop, L_first_loop_exit;
9643 
9644   movl(tmp1, len);
9645   shrl(tmp1, 2);
9646 
9647   bind(L_first_loop);
9648   subl(tmp1, 1);
9649   jccb(Assembler::negative, L_first_loop_exit);
9650 
9651   subl(len, 4);
9652   subl(offset, 4);
9653 
9654   Register op2 = tmp2;
9655   const Register sum = tmp3;
9656   const Register op1 = tmp4;
9657   const Register carry = tmp5;
9658 
9659   if (UseBMI2Instructions) {
9660     op2 = rdxReg;
9661   }
9662 
9663   movq(op1, Address(in, len, Address::times_4,  8));
9664   rorq(op1, 32);
9665   movq(sum, Address(out, offset, Address::times_4,  8));
9666   rorq(sum, 32);
9667   if (UseBMI2Instructions) {
9668     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9669   }
9670   else {
9671     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9672   }
9673   // Store back in big endian from little endian
9674   rorq(sum, 0x20);
9675   movq(Address(out, offset, Address::times_4,  8), sum);
9676 
9677   movq(op1, Address(in, len, Address::times_4,  0));
9678   rorq(op1, 32);
9679   movq(sum, Address(out, offset, Address::times_4,  0));
9680   rorq(sum, 32);
9681   if (UseBMI2Instructions) {
9682     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9683   }
9684   else {
9685     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9686   }
9687   // Store back in big endian from little endian
9688   rorq(sum, 0x20);
9689   movq(Address(out, offset, Address::times_4,  0), sum);
9690 
9691   jmp(L_first_loop);
9692   bind(L_first_loop_exit);
9693 }
9694 
9695 /**
9696  * Code for BigInteger::mulAdd() intrinsic
9697  *
9698  * rdi: out
9699  * rsi: in
9700  * r11: offs (out.length - offset)
9701  * rcx: len
9702  * r8:  k
9703  * r12: tmp1
9704  * r13: tmp2
9705  * r14: tmp3
9706  * r15: tmp4
9707  * rbx: tmp5
9708  * Multiply the in[] by word k and add to out[], return the carry in rax
9709  */
9710 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9711    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9712    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9713 
9714   Label L_carry, L_last_in, L_done;
9715 
9716 // carry = 0;
9717 // for (int j=len-1; j >= 0; j--) {
9718 //    long product = (in[j] & LONG_MASK) * kLong +
9719 //                   (out[offs] & LONG_MASK) + carry;
9720 //    out[offs--] = (int)product;
9721 //    carry = product >>> 32;
9722 // }
9723 //
9724   push(tmp1);
9725   push(tmp2);
9726   push(tmp3);
9727   push(tmp4);
9728   push(tmp5);
9729 
9730   Register op2 = tmp2;
9731   const Register sum = tmp3;
9732   const Register op1 = tmp4;
9733   const Register carry =  tmp5;
9734 
9735   if (UseBMI2Instructions) {
9736     op2 = rdxReg;
9737     movl(op2, k);
9738   }
9739   else {
9740     movl(op2, k);
9741   }
9742 
9743   xorq(carry, carry);
9744 
9745   //First loop
9746 
9747   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9748   //The carry is in tmp5
9749   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9750 
9751   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9752   decrementl(len);
9753   jccb(Assembler::negative, L_carry);
9754   decrementl(len);
9755   jccb(Assembler::negative, L_last_in);
9756 
9757   movq(op1, Address(in, len, Address::times_4,  0));
9758   rorq(op1, 32);
9759 
9760   subl(offs, 2);
9761   movq(sum, Address(out, offs, Address::times_4,  0));
9762   rorq(sum, 32);
9763 
9764   if (UseBMI2Instructions) {
9765     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9766   }
9767   else {
9768     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9769   }
9770 
9771   // Store back in big endian from little endian
9772   rorq(sum, 0x20);
9773   movq(Address(out, offs, Address::times_4,  0), sum);
9774 
9775   testl(len, len);
9776   jccb(Assembler::zero, L_carry);
9777 
9778   //Multiply the last in[] entry, if any
9779   bind(L_last_in);
9780   movl(op1, Address(in, 0));
9781   movl(sum, Address(out, offs, Address::times_4,  -4));
9782 
9783   movl(raxReg, k);
9784   mull(op1); //tmp4 * eax -> edx:eax
9785   addl(sum, carry);
9786   adcl(rdxReg, 0);
9787   addl(sum, raxReg);
9788   adcl(rdxReg, 0);
9789   movl(carry, rdxReg);
9790 
9791   movl(Address(out, offs, Address::times_4,  -4), sum);
9792 
9793   bind(L_carry);
9794   //return tmp5/carry as carry in rax
9795   movl(rax, carry);
9796 
9797   bind(L_done);
9798   pop(tmp5);
9799   pop(tmp4);
9800   pop(tmp3);
9801   pop(tmp2);
9802   pop(tmp1);
9803 }
9804 #endif
9805 
9806 /**
9807  * Emits code to update CRC-32 with a byte value according to constants in table
9808  *
9809  * @param [in,out]crc   Register containing the crc.
9810  * @param [in]val       Register containing the byte to fold into the CRC.
9811  * @param [in]table     Register containing the table of crc constants.
9812  *
9813  * uint32_t crc;
9814  * val = crc_table[(val ^ crc) & 0xFF];
9815  * crc = val ^ (crc >> 8);
9816  *
9817  */
9818 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9819   xorl(val, crc);
9820   andl(val, 0xFF);
9821   shrl(crc, 8); // unsigned shift
9822   xorl(crc, Address(table, val, Address::times_4, 0));
9823 }
9824 
9825 /**
9826  * Fold 128-bit data chunk
9827  */
9828 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9829   if (UseAVX > 0) {
9830     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9831     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9832     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9833     pxor(xcrc, xtmp);
9834   } else {
9835     movdqa(xtmp, xcrc);
9836     pclmulhdq(xtmp, xK);   // [123:64]
9837     pclmulldq(xcrc, xK);   // [63:0]
9838     pxor(xcrc, xtmp);
9839     movdqu(xtmp, Address(buf, offset));
9840     pxor(xcrc, xtmp);
9841   }
9842 }
9843 
9844 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9845   if (UseAVX > 0) {
9846     vpclmulhdq(xtmp, xK, xcrc);
9847     vpclmulldq(xcrc, xK, xcrc);
9848     pxor(xcrc, xbuf);
9849     pxor(xcrc, xtmp);
9850   } else {
9851     movdqa(xtmp, xcrc);
9852     pclmulhdq(xtmp, xK);
9853     pclmulldq(xcrc, xK);
9854     pxor(xcrc, xbuf);
9855     pxor(xcrc, xtmp);
9856   }
9857 }
9858 
9859 /**
9860  * 8-bit folds to compute 32-bit CRC
9861  *
9862  * uint64_t xcrc;
9863  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9864  */
9865 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9866   movdl(tmp, xcrc);
9867   andl(tmp, 0xFF);
9868   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
9869   psrldq(xcrc, 1); // unsigned shift one byte
9870   pxor(xcrc, xtmp);
9871 }
9872 
9873 /**
9874  * uint32_t crc;
9875  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
9876  */
9877 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
9878   movl(tmp, crc);
9879   andl(tmp, 0xFF);
9880   shrl(crc, 8);
9881   xorl(crc, Address(table, tmp, Address::times_4, 0));
9882 }
9883 
9884 /**
9885  * @param crc   register containing existing CRC (32-bit)
9886  * @param buf   register pointing to input byte buffer (byte*)
9887  * @param len   register containing number of bytes
9888  * @param table register that will contain address of CRC table
9889  * @param tmp   scratch register
9890  */
9891 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
9892   assert_different_registers(crc, buf, len, table, tmp, rax);
9893 
9894   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
9895   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
9896 
9897   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
9898   // context for the registers used, where all instructions below are using 128-bit mode
9899   // On EVEX without VL and BW, these instructions will all be AVX.
9900   if (VM_Version::supports_avx512vlbw()) {
9901     movl(tmp, 0xffff);
9902     kmovwl(k1, tmp);
9903   }
9904 
9905   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
9906   notl(crc); // ~crc
9907   cmpl(len, 16);
9908   jcc(Assembler::less, L_tail);
9909 
9910   // Align buffer to 16 bytes
9911   movl(tmp, buf);
9912   andl(tmp, 0xF);
9913   jccb(Assembler::zero, L_aligned);
9914   subl(tmp,  16);
9915   addl(len, tmp);
9916 
9917   align(4);
9918   BIND(L_align_loop);
9919   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9920   update_byte_crc32(crc, rax, table);
9921   increment(buf);
9922   incrementl(tmp);
9923   jccb(Assembler::less, L_align_loop);
9924 
9925   BIND(L_aligned);
9926   movl(tmp, len); // save
9927   shrl(len, 4);
9928   jcc(Assembler::zero, L_tail_restore);
9929 
9930   // Fold crc into first bytes of vector
9931   movdqa(xmm1, Address(buf, 0));
9932   movdl(rax, xmm1);
9933   xorl(crc, rax);
9934   if (VM_Version::supports_sse4_1()) {
9935     pinsrd(xmm1, crc, 0);
9936   } else {
9937     pinsrw(xmm1, crc, 0);
9938     shrl(crc, 16);
9939     pinsrw(xmm1, crc, 1);
9940   }
9941   addptr(buf, 16);
9942   subl(len, 4); // len > 0
9943   jcc(Assembler::less, L_fold_tail);
9944 
9945   movdqa(xmm2, Address(buf,  0));
9946   movdqa(xmm3, Address(buf, 16));
9947   movdqa(xmm4, Address(buf, 32));
9948   addptr(buf, 48);
9949   subl(len, 3);
9950   jcc(Assembler::lessEqual, L_fold_512b);
9951 
9952   // Fold total 512 bits of polynomial on each iteration,
9953   // 128 bits per each of 4 parallel streams.
9954   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9955 
9956   align(32);
9957   BIND(L_fold_512b_loop);
9958   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
9959   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
9960   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
9961   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
9962   addptr(buf, 64);
9963   subl(len, 4);
9964   jcc(Assembler::greater, L_fold_512b_loop);
9965 
9966   // Fold 512 bits to 128 bits.
9967   BIND(L_fold_512b);
9968   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
9969   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
9970   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
9971   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
9972 
9973   // Fold the rest of 128 bits data chunks
9974   BIND(L_fold_tail);
9975   addl(len, 3);
9976   jccb(Assembler::lessEqual, L_fold_128b);
9977   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
9978 
9979   BIND(L_fold_tail_loop);
9980   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
9981   addptr(buf, 16);
9982   decrementl(len);
9983   jccb(Assembler::greater, L_fold_tail_loop);
9984 
9985   // Fold 128 bits in xmm1 down into 32 bits in crc register.
9986   BIND(L_fold_128b);
9987   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
9988   if (UseAVX > 0) {
9989     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
9990     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
9991     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
9992   } else {
9993     movdqa(xmm2, xmm0);
9994     pclmulqdq(xmm2, xmm1, 0x1);
9995     movdqa(xmm3, xmm0);
9996     pand(xmm3, xmm2);
9997     pclmulqdq(xmm0, xmm3, 0x1);
9998   }
9999   psrldq(xmm1, 8);
10000   psrldq(xmm2, 4);
10001   pxor(xmm0, xmm1);
10002   pxor(xmm0, xmm2);
10003 
10004   // 8 8-bit folds to compute 32-bit CRC.
10005   for (int j = 0; j < 4; j++) {
10006     fold_8bit_crc32(xmm0, table, xmm1, rax);
10007   }
10008   movdl(crc, xmm0); // mov 32 bits to general register
10009   for (int j = 0; j < 4; j++) {
10010     fold_8bit_crc32(crc, table, rax);
10011   }
10012 
10013   BIND(L_tail_restore);
10014   movl(len, tmp); // restore
10015   BIND(L_tail);
10016   andl(len, 0xf);
10017   jccb(Assembler::zero, L_exit);
10018 
10019   // Fold the rest of bytes
10020   align(4);
10021   BIND(L_tail_loop);
10022   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10023   update_byte_crc32(crc, rax, table);
10024   increment(buf);
10025   decrementl(len);
10026   jccb(Assembler::greater, L_tail_loop);
10027 
10028   BIND(L_exit);
10029   notl(crc); // ~c
10030 }
10031 
10032 #ifdef _LP64
10033 // S. Gueron / Information Processing Letters 112 (2012) 184
10034 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10035 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10036 // Output: the 64-bit carry-less product of B * CONST
10037 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10038                                      Register tmp1, Register tmp2, Register tmp3) {
10039   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10040   if (n > 0) {
10041     addq(tmp3, n * 256 * 8);
10042   }
10043   //    Q1 = TABLEExt[n][B & 0xFF];
10044   movl(tmp1, in);
10045   andl(tmp1, 0x000000FF);
10046   shll(tmp1, 3);
10047   addq(tmp1, tmp3);
10048   movq(tmp1, Address(tmp1, 0));
10049 
10050   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10051   movl(tmp2, in);
10052   shrl(tmp2, 8);
10053   andl(tmp2, 0x000000FF);
10054   shll(tmp2, 3);
10055   addq(tmp2, tmp3);
10056   movq(tmp2, Address(tmp2, 0));
10057 
10058   shlq(tmp2, 8);
10059   xorq(tmp1, tmp2);
10060 
10061   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10062   movl(tmp2, in);
10063   shrl(tmp2, 16);
10064   andl(tmp2, 0x000000FF);
10065   shll(tmp2, 3);
10066   addq(tmp2, tmp3);
10067   movq(tmp2, Address(tmp2, 0));
10068 
10069   shlq(tmp2, 16);
10070   xorq(tmp1, tmp2);
10071 
10072   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10073   shrl(in, 24);
10074   andl(in, 0x000000FF);
10075   shll(in, 3);
10076   addq(in, tmp3);
10077   movq(in, Address(in, 0));
10078 
10079   shlq(in, 24);
10080   xorq(in, tmp1);
10081   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10082 }
10083 
10084 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10085                                       Register in_out,
10086                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10087                                       XMMRegister w_xtmp2,
10088                                       Register tmp1,
10089                                       Register n_tmp2, Register n_tmp3) {
10090   if (is_pclmulqdq_supported) {
10091     movdl(w_xtmp1, in_out); // modified blindly
10092 
10093     movl(tmp1, const_or_pre_comp_const_index);
10094     movdl(w_xtmp2, tmp1);
10095     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10096 
10097     movdq(in_out, w_xtmp1);
10098   } else {
10099     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10100   }
10101 }
10102 
10103 // Recombination Alternative 2: No bit-reflections
10104 // T1 = (CRC_A * U1) << 1
10105 // T2 = (CRC_B * U2) << 1
10106 // C1 = T1 >> 32
10107 // C2 = T2 >> 32
10108 // T1 = T1 & 0xFFFFFFFF
10109 // T2 = T2 & 0xFFFFFFFF
10110 // T1 = CRC32(0, T1)
10111 // T2 = CRC32(0, T2)
10112 // C1 = C1 ^ T1
10113 // C2 = C2 ^ T2
10114 // CRC = C1 ^ C2 ^ CRC_C
10115 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,
10116                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10117                                      Register tmp1, Register tmp2,
10118                                      Register n_tmp3) {
10119   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10120   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10121   shlq(in_out, 1);
10122   movl(tmp1, in_out);
10123   shrq(in_out, 32);
10124   xorl(tmp2, tmp2);
10125   crc32(tmp2, tmp1, 4);
10126   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10127   shlq(in1, 1);
10128   movl(tmp1, in1);
10129   shrq(in1, 32);
10130   xorl(tmp2, tmp2);
10131   crc32(tmp2, tmp1, 4);
10132   xorl(in1, tmp2);
10133   xorl(in_out, in1);
10134   xorl(in_out, in2);
10135 }
10136 
10137 // Set N to predefined value
10138 // Subtract from a lenght of a buffer
10139 // execute in a loop:
10140 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10141 // for i = 1 to N do
10142 //  CRC_A = CRC32(CRC_A, A[i])
10143 //  CRC_B = CRC32(CRC_B, B[i])
10144 //  CRC_C = CRC32(CRC_C, C[i])
10145 // end for
10146 // Recombine
10147 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,
10148                                        Register in_out1, Register in_out2, Register in_out3,
10149                                        Register tmp1, Register tmp2, Register tmp3,
10150                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10151                                        Register tmp4, Register tmp5,
10152                                        Register n_tmp6) {
10153   Label L_processPartitions;
10154   Label L_processPartition;
10155   Label L_exit;
10156 
10157   bind(L_processPartitions);
10158   cmpl(in_out1, 3 * size);
10159   jcc(Assembler::less, L_exit);
10160     xorl(tmp1, tmp1);
10161     xorl(tmp2, tmp2);
10162     movq(tmp3, in_out2);
10163     addq(tmp3, size);
10164 
10165     bind(L_processPartition);
10166       crc32(in_out3, Address(in_out2, 0), 8);
10167       crc32(tmp1, Address(in_out2, size), 8);
10168       crc32(tmp2, Address(in_out2, size * 2), 8);
10169       addq(in_out2, 8);
10170       cmpq(in_out2, tmp3);
10171       jcc(Assembler::less, L_processPartition);
10172     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10173             w_xtmp1, w_xtmp2, w_xtmp3,
10174             tmp4, tmp5,
10175             n_tmp6);
10176     addq(in_out2, 2 * size);
10177     subl(in_out1, 3 * size);
10178     jmp(L_processPartitions);
10179 
10180   bind(L_exit);
10181 }
10182 #else
10183 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10184                                      Register tmp1, Register tmp2, Register tmp3,
10185                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10186   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10187   if (n > 0) {
10188     addl(tmp3, n * 256 * 8);
10189   }
10190   //    Q1 = TABLEExt[n][B & 0xFF];
10191   movl(tmp1, in_out);
10192   andl(tmp1, 0x000000FF);
10193   shll(tmp1, 3);
10194   addl(tmp1, tmp3);
10195   movq(xtmp1, Address(tmp1, 0));
10196 
10197   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10198   movl(tmp2, in_out);
10199   shrl(tmp2, 8);
10200   andl(tmp2, 0x000000FF);
10201   shll(tmp2, 3);
10202   addl(tmp2, tmp3);
10203   movq(xtmp2, Address(tmp2, 0));
10204 
10205   psllq(xtmp2, 8);
10206   pxor(xtmp1, xtmp2);
10207 
10208   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10209   movl(tmp2, in_out);
10210   shrl(tmp2, 16);
10211   andl(tmp2, 0x000000FF);
10212   shll(tmp2, 3);
10213   addl(tmp2, tmp3);
10214   movq(xtmp2, Address(tmp2, 0));
10215 
10216   psllq(xtmp2, 16);
10217   pxor(xtmp1, xtmp2);
10218 
10219   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10220   shrl(in_out, 24);
10221   andl(in_out, 0x000000FF);
10222   shll(in_out, 3);
10223   addl(in_out, tmp3);
10224   movq(xtmp2, Address(in_out, 0));
10225 
10226   psllq(xtmp2, 24);
10227   pxor(xtmp1, xtmp2); // Result in CXMM
10228   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10229 }
10230 
10231 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10232                                       Register in_out,
10233                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10234                                       XMMRegister w_xtmp2,
10235                                       Register tmp1,
10236                                       Register n_tmp2, Register n_tmp3) {
10237   if (is_pclmulqdq_supported) {
10238     movdl(w_xtmp1, in_out);
10239 
10240     movl(tmp1, const_or_pre_comp_const_index);
10241     movdl(w_xtmp2, tmp1);
10242     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10243     // Keep result in XMM since GPR is 32 bit in length
10244   } else {
10245     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10246   }
10247 }
10248 
10249 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,
10250                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10251                                      Register tmp1, Register tmp2,
10252                                      Register n_tmp3) {
10253   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10254   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10255 
10256   psllq(w_xtmp1, 1);
10257   movdl(tmp1, w_xtmp1);
10258   psrlq(w_xtmp1, 32);
10259   movdl(in_out, w_xtmp1);
10260 
10261   xorl(tmp2, tmp2);
10262   crc32(tmp2, tmp1, 4);
10263   xorl(in_out, tmp2);
10264 
10265   psllq(w_xtmp2, 1);
10266   movdl(tmp1, w_xtmp2);
10267   psrlq(w_xtmp2, 32);
10268   movdl(in1, w_xtmp2);
10269 
10270   xorl(tmp2, tmp2);
10271   crc32(tmp2, tmp1, 4);
10272   xorl(in1, tmp2);
10273   xorl(in_out, in1);
10274   xorl(in_out, in2);
10275 }
10276 
10277 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,
10278                                        Register in_out1, Register in_out2, Register in_out3,
10279                                        Register tmp1, Register tmp2, Register tmp3,
10280                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10281                                        Register tmp4, Register tmp5,
10282                                        Register n_tmp6) {
10283   Label L_processPartitions;
10284   Label L_processPartition;
10285   Label L_exit;
10286 
10287   bind(L_processPartitions);
10288   cmpl(in_out1, 3 * size);
10289   jcc(Assembler::less, L_exit);
10290     xorl(tmp1, tmp1);
10291     xorl(tmp2, tmp2);
10292     movl(tmp3, in_out2);
10293     addl(tmp3, size);
10294 
10295     bind(L_processPartition);
10296       crc32(in_out3, Address(in_out2, 0), 4);
10297       crc32(tmp1, Address(in_out2, size), 4);
10298       crc32(tmp2, Address(in_out2, size*2), 4);
10299       crc32(in_out3, Address(in_out2, 0+4), 4);
10300       crc32(tmp1, Address(in_out2, size+4), 4);
10301       crc32(tmp2, Address(in_out2, size*2+4), 4);
10302       addl(in_out2, 8);
10303       cmpl(in_out2, tmp3);
10304       jcc(Assembler::less, L_processPartition);
10305 
10306         push(tmp3);
10307         push(in_out1);
10308         push(in_out2);
10309         tmp4 = tmp3;
10310         tmp5 = in_out1;
10311         n_tmp6 = in_out2;
10312 
10313       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10314             w_xtmp1, w_xtmp2, w_xtmp3,
10315             tmp4, tmp5,
10316             n_tmp6);
10317 
10318         pop(in_out2);
10319         pop(in_out1);
10320         pop(tmp3);
10321 
10322     addl(in_out2, 2 * size);
10323     subl(in_out1, 3 * size);
10324     jmp(L_processPartitions);
10325 
10326   bind(L_exit);
10327 }
10328 #endif //LP64
10329 
10330 #ifdef _LP64
10331 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10332 // Input: A buffer I of L bytes.
10333 // Output: the CRC32C value of the buffer.
10334 // Notations:
10335 // Write L = 24N + r, with N = floor (L/24).
10336 // r = L mod 24 (0 <= r < 24).
10337 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10338 // N quadwords, and R consists of r bytes.
10339 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10340 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10341 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10342 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10343 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10344                                           Register tmp1, Register tmp2, Register tmp3,
10345                                           Register tmp4, Register tmp5, Register tmp6,
10346                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10347                                           bool is_pclmulqdq_supported) {
10348   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10349   Label L_wordByWord;
10350   Label L_byteByByteProlog;
10351   Label L_byteByByte;
10352   Label L_exit;
10353 
10354   if (is_pclmulqdq_supported ) {
10355     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10356     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10357 
10358     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10359     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10360 
10361     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10362     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10363     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10364   } else {
10365     const_or_pre_comp_const_index[0] = 1;
10366     const_or_pre_comp_const_index[1] = 0;
10367 
10368     const_or_pre_comp_const_index[2] = 3;
10369     const_or_pre_comp_const_index[3] = 2;
10370 
10371     const_or_pre_comp_const_index[4] = 5;
10372     const_or_pre_comp_const_index[5] = 4;
10373    }
10374   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10375                     in2, in1, in_out,
10376                     tmp1, tmp2, tmp3,
10377                     w_xtmp1, w_xtmp2, w_xtmp3,
10378                     tmp4, tmp5,
10379                     tmp6);
10380   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10381                     in2, in1, in_out,
10382                     tmp1, tmp2, tmp3,
10383                     w_xtmp1, w_xtmp2, w_xtmp3,
10384                     tmp4, tmp5,
10385                     tmp6);
10386   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10387                     in2, in1, in_out,
10388                     tmp1, tmp2, tmp3,
10389                     w_xtmp1, w_xtmp2, w_xtmp3,
10390                     tmp4, tmp5,
10391                     tmp6);
10392   movl(tmp1, in2);
10393   andl(tmp1, 0x00000007);
10394   negl(tmp1);
10395   addl(tmp1, in2);
10396   addq(tmp1, in1);
10397 
10398   BIND(L_wordByWord);
10399   cmpq(in1, tmp1);
10400   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10401     crc32(in_out, Address(in1, 0), 4);
10402     addq(in1, 4);
10403     jmp(L_wordByWord);
10404 
10405   BIND(L_byteByByteProlog);
10406   andl(in2, 0x00000007);
10407   movl(tmp2, 1);
10408 
10409   BIND(L_byteByByte);
10410   cmpl(tmp2, in2);
10411   jccb(Assembler::greater, L_exit);
10412     crc32(in_out, Address(in1, 0), 1);
10413     incq(in1);
10414     incl(tmp2);
10415     jmp(L_byteByByte);
10416 
10417   BIND(L_exit);
10418 }
10419 #else
10420 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10421                                           Register tmp1, Register  tmp2, Register tmp3,
10422                                           Register tmp4, Register  tmp5, Register tmp6,
10423                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10424                                           bool is_pclmulqdq_supported) {
10425   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10426   Label L_wordByWord;
10427   Label L_byteByByteProlog;
10428   Label L_byteByByte;
10429   Label L_exit;
10430 
10431   if (is_pclmulqdq_supported) {
10432     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10433     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10434 
10435     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10436     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10437 
10438     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10439     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10440   } else {
10441     const_or_pre_comp_const_index[0] = 1;
10442     const_or_pre_comp_const_index[1] = 0;
10443 
10444     const_or_pre_comp_const_index[2] = 3;
10445     const_or_pre_comp_const_index[3] = 2;
10446 
10447     const_or_pre_comp_const_index[4] = 5;
10448     const_or_pre_comp_const_index[5] = 4;
10449   }
10450   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10451                     in2, in1, in_out,
10452                     tmp1, tmp2, tmp3,
10453                     w_xtmp1, w_xtmp2, w_xtmp3,
10454                     tmp4, tmp5,
10455                     tmp6);
10456   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10457                     in2, in1, in_out,
10458                     tmp1, tmp2, tmp3,
10459                     w_xtmp1, w_xtmp2, w_xtmp3,
10460                     tmp4, tmp5,
10461                     tmp6);
10462   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10463                     in2, in1, in_out,
10464                     tmp1, tmp2, tmp3,
10465                     w_xtmp1, w_xtmp2, w_xtmp3,
10466                     tmp4, tmp5,
10467                     tmp6);
10468   movl(tmp1, in2);
10469   andl(tmp1, 0x00000007);
10470   negl(tmp1);
10471   addl(tmp1, in2);
10472   addl(tmp1, in1);
10473 
10474   BIND(L_wordByWord);
10475   cmpl(in1, tmp1);
10476   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10477     crc32(in_out, Address(in1,0), 4);
10478     addl(in1, 4);
10479     jmp(L_wordByWord);
10480 
10481   BIND(L_byteByByteProlog);
10482   andl(in2, 0x00000007);
10483   movl(tmp2, 1);
10484 
10485   BIND(L_byteByByte);
10486   cmpl(tmp2, in2);
10487   jccb(Assembler::greater, L_exit);
10488     movb(tmp1, Address(in1, 0));
10489     crc32(in_out, tmp1, 1);
10490     incl(in1);
10491     incl(tmp2);
10492     jmp(L_byteByByte);
10493 
10494   BIND(L_exit);
10495 }
10496 #endif // LP64
10497 #undef BIND
10498 #undef BLOCK_COMMENT
10499 
10500 // Compress char[] array to byte[].
10501 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10502 //   @HotSpotIntrinsicCandidate
10503 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10504 //     for (int i = 0; i < len; i++) {
10505 //       int c = src[srcOff++];
10506 //       if (c >>> 8 != 0) {
10507 //         return 0;
10508 //       }
10509 //       dst[dstOff++] = (byte)c;
10510 //     }
10511 //     return len;
10512 //   }
10513 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10514   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10515   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10516   Register tmp5, Register result) {
10517   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10518 
10519   // rsi: src
10520   // rdi: dst
10521   // rdx: len
10522   // rcx: tmp5
10523   // rax: result
10524 
10525   // rsi holds start addr of source char[] to be compressed
10526   // rdi holds start addr of destination byte[]
10527   // rdx holds length
10528 
10529   assert(len != result, "");
10530 
10531   // save length for return
10532   push(len);
10533 
10534   if ((UseAVX > 2) && // AVX512
10535     VM_Version::supports_avx512vlbw() &&
10536     VM_Version::supports_bmi2()) {
10537 
10538     set_vector_masking();  // opening of the stub context for programming mask registers
10539 
10540     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10541 
10542     // alignement
10543     Label post_alignement;
10544 
10545     // if length of the string is less than 16, handle it in an old fashioned
10546     // way
10547     testl(len, -32);
10548     jcc(Assembler::zero, below_threshold);
10549 
10550     // First check whether a character is compressable ( <= 0xFF).
10551     // Create mask to test for Unicode chars inside zmm vector
10552     movl(result, 0x00FF);
10553     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10554 
10555     // Save k1
10556     kmovql(k3, k1);
10557 
10558     testl(len, -64);
10559     jcc(Assembler::zero, post_alignement);
10560 
10561     movl(tmp5, dst);
10562     andl(tmp5, (32 - 1));
10563     negl(tmp5);
10564     andl(tmp5, (32 - 1));
10565 
10566     // bail out when there is nothing to be done
10567     testl(tmp5, 0xFFFFFFFF);
10568     jcc(Assembler::zero, post_alignement);
10569 
10570     // ~(~0 << len), where len is the # of remaining elements to process
10571     movl(result, 0xFFFFFFFF);
10572     shlxl(result, result, tmp5);
10573     notl(result);
10574     kmovdl(k1, result);
10575 
10576     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10577     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10578     ktestd(k2, k1);
10579     jcc(Assembler::carryClear, restore_k1_return_zero);
10580 
10581     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10582 
10583     addptr(src, tmp5);
10584     addptr(src, tmp5);
10585     addptr(dst, tmp5);
10586     subl(len, tmp5);
10587 
10588     bind(post_alignement);
10589     // end of alignement
10590 
10591     movl(tmp5, len);
10592     andl(tmp5, (32 - 1));    // tail count (in chars)
10593     andl(len, ~(32 - 1));    // vector count (in chars)
10594     jcc(Assembler::zero, copy_loop_tail);
10595 
10596     lea(src, Address(src, len, Address::times_2));
10597     lea(dst, Address(dst, len, Address::times_1));
10598     negptr(len);
10599 
10600     bind(copy_32_loop);
10601     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10602     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10603     kortestdl(k2, k2);
10604     jcc(Assembler::carryClear, restore_k1_return_zero);
10605 
10606     // All elements in current processed chunk are valid candidates for
10607     // compression. Write a truncated byte elements to the memory.
10608     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10609     addptr(len, 32);
10610     jcc(Assembler::notZero, copy_32_loop);
10611 
10612     bind(copy_loop_tail);
10613     // bail out when there is nothing to be done
10614     testl(tmp5, 0xFFFFFFFF);
10615     // Restore k1
10616     kmovql(k1, k3);
10617     jcc(Assembler::zero, return_length);
10618 
10619     movl(len, tmp5);
10620 
10621     // ~(~0 << len), where len is the # of remaining elements to process
10622     movl(result, 0xFFFFFFFF);
10623     shlxl(result, result, len);
10624     notl(result);
10625 
10626     kmovdl(k1, result);
10627 
10628     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10629     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10630     ktestd(k2, k1);
10631     jcc(Assembler::carryClear, restore_k1_return_zero);
10632 
10633     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10634     // Restore k1
10635     kmovql(k1, k3);
10636     jmp(return_length);
10637 
10638     bind(restore_k1_return_zero);
10639     // Restore k1
10640     kmovql(k1, k3);
10641     jmp(return_zero);
10642 
10643     clear_vector_masking();   // closing of the stub context for programming mask registers
10644   }
10645   if (UseSSE42Intrinsics) {
10646     Label copy_32_loop, copy_16, copy_tail;
10647 
10648     bind(below_threshold);
10649 
10650     movl(result, len);
10651 
10652     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10653 
10654     // vectored compression
10655     andl(len, 0xfffffff0);    // vector count (in chars)
10656     andl(result, 0x0000000f);    // tail count (in chars)
10657     testl(len, len);
10658     jccb(Assembler::zero, copy_16);
10659 
10660     // compress 16 chars per iter
10661     movdl(tmp1Reg, tmp5);
10662     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10663     pxor(tmp4Reg, tmp4Reg);
10664 
10665     lea(src, Address(src, len, Address::times_2));
10666     lea(dst, Address(dst, len, Address::times_1));
10667     negptr(len);
10668 
10669     bind(copy_32_loop);
10670     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10671     por(tmp4Reg, tmp2Reg);
10672     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10673     por(tmp4Reg, tmp3Reg);
10674     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10675     jcc(Assembler::notZero, return_zero);
10676     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10677     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10678     addptr(len, 16);
10679     jcc(Assembler::notZero, copy_32_loop);
10680 
10681     // compress next vector of 8 chars (if any)
10682     bind(copy_16);
10683     movl(len, result);
10684     andl(len, 0xfffffff8);    // vector count (in chars)
10685     andl(result, 0x00000007);    // tail count (in chars)
10686     testl(len, len);
10687     jccb(Assembler::zero, copy_tail);
10688 
10689     movdl(tmp1Reg, tmp5);
10690     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10691     pxor(tmp3Reg, tmp3Reg);
10692 
10693     movdqu(tmp2Reg, Address(src, 0));
10694     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10695     jccb(Assembler::notZero, return_zero);
10696     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10697     movq(Address(dst, 0), tmp2Reg);
10698     addptr(src, 16);
10699     addptr(dst, 8);
10700 
10701     bind(copy_tail);
10702     movl(len, result);
10703   }
10704   // compress 1 char per iter
10705   testl(len, len);
10706   jccb(Assembler::zero, return_length);
10707   lea(src, Address(src, len, Address::times_2));
10708   lea(dst, Address(dst, len, Address::times_1));
10709   negptr(len);
10710 
10711   bind(copy_chars_loop);
10712   load_unsigned_short(result, Address(src, len, Address::times_2));
10713   testl(result, 0xff00);      // check if Unicode char
10714   jccb(Assembler::notZero, return_zero);
10715   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10716   increment(len);
10717   jcc(Assembler::notZero, copy_chars_loop);
10718 
10719   // if compression succeeded, return length
10720   bind(return_length);
10721   pop(result);
10722   jmpb(done);
10723 
10724   // if compression failed, return 0
10725   bind(return_zero);
10726   xorl(result, result);
10727   addptr(rsp, wordSize);
10728 
10729   bind(done);
10730 }
10731 
10732 // Inflate byte[] array to char[].
10733 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
10734 //   @HotSpotIntrinsicCandidate
10735 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
10736 //     for (int i = 0; i < len; i++) {
10737 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
10738 //     }
10739 //   }
10740 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10741   XMMRegister tmp1, Register tmp2) {
10742   Label copy_chars_loop, done, below_threshold;
10743   // rsi: src
10744   // rdi: dst
10745   // rdx: len
10746   // rcx: tmp2
10747 
10748   // rsi holds start addr of source byte[] to be inflated
10749   // rdi holds start addr of destination char[]
10750   // rdx holds length
10751   assert_different_registers(src, dst, len, tmp2);
10752 
10753   if ((UseAVX > 2) && // AVX512
10754     VM_Version::supports_avx512vlbw() &&
10755     VM_Version::supports_bmi2()) {
10756 
10757     set_vector_masking();  // opening of the stub context for programming mask registers
10758 
10759     Label copy_32_loop, copy_tail;
10760     Register tmp3_aliased = len;
10761 
10762     // if length of the string is less than 16, handle it in an old fashioned
10763     // way
10764     testl(len, -16);
10765     jcc(Assembler::zero, below_threshold);
10766 
10767     // In order to use only one arithmetic operation for the main loop we use
10768     // this pre-calculation
10769     movl(tmp2, len);
10770     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
10771     andl(len, -32);     // vector count
10772     jccb(Assembler::zero, copy_tail);
10773 
10774     lea(src, Address(src, len, Address::times_1));
10775     lea(dst, Address(dst, len, Address::times_2));
10776     negptr(len);
10777 
10778 
10779     // inflate 32 chars per iter
10780     bind(copy_32_loop);
10781     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
10782     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
10783     addptr(len, 32);
10784     jcc(Assembler::notZero, copy_32_loop);
10785 
10786     bind(copy_tail);
10787     // bail out when there is nothing to be done
10788     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
10789     jcc(Assembler::zero, done);
10790 
10791     // Save k1
10792     kmovql(k2, k1);
10793 
10794     // ~(~0 << length), where length is the # of remaining elements to process
10795     movl(tmp3_aliased, -1);
10796     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
10797     notl(tmp3_aliased);
10798     kmovdl(k1, tmp3_aliased);
10799     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
10800     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
10801 
10802     // Restore k1
10803     kmovql(k1, k2);
10804     jmp(done);
10805 
10806     clear_vector_masking();   // closing of the stub context for programming mask registers
10807   }
10808   if (UseSSE42Intrinsics) {
10809     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
10810 
10811     movl(tmp2, len);
10812 
10813     if (UseAVX > 1) {
10814       andl(tmp2, (16 - 1));
10815       andl(len, -16);
10816       jccb(Assembler::zero, copy_new_tail);
10817     } else {
10818       andl(tmp2, 0x00000007);   // tail count (in chars)
10819       andl(len, 0xfffffff8);    // vector count (in chars)
10820       jccb(Assembler::zero, copy_tail);
10821     }
10822 
10823     // vectored inflation
10824     lea(src, Address(src, len, Address::times_1));
10825     lea(dst, Address(dst, len, Address::times_2));
10826     negptr(len);
10827 
10828     if (UseAVX > 1) {
10829       bind(copy_16_loop);
10830       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
10831       vmovdqu(Address(dst, len, Address::times_2), tmp1);
10832       addptr(len, 16);
10833       jcc(Assembler::notZero, copy_16_loop);
10834 
10835       bind(below_threshold);
10836       bind(copy_new_tail);
10837       if ((UseAVX > 2) &&
10838         VM_Version::supports_avx512vlbw() &&
10839         VM_Version::supports_bmi2()) {
10840         movl(tmp2, len);
10841       } else {
10842         movl(len, tmp2);
10843       }
10844       andl(tmp2, 0x00000007);
10845       andl(len, 0xFFFFFFF8);
10846       jccb(Assembler::zero, copy_tail);
10847 
10848       pmovzxbw(tmp1, Address(src, 0));
10849       movdqu(Address(dst, 0), tmp1);
10850       addptr(src, 8);
10851       addptr(dst, 2 * 8);
10852 
10853       jmp(copy_tail, true);
10854     }
10855 
10856     // inflate 8 chars per iter
10857     bind(copy_8_loop);
10858     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10859     movdqu(Address(dst, len, Address::times_2), tmp1);
10860     addptr(len, 8);
10861     jcc(Assembler::notZero, copy_8_loop);
10862 
10863     bind(copy_tail);
10864     movl(len, tmp2);
10865 
10866     cmpl(len, 4);
10867     jccb(Assembler::less, copy_bytes);
10868 
10869     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10870     pmovzxbw(tmp1, tmp1);
10871     movq(Address(dst, 0), tmp1);
10872     subptr(len, 4);
10873     addptr(src, 4);
10874     addptr(dst, 8);
10875 
10876     bind(copy_bytes);
10877   }
10878   testl(len, len);
10879   jccb(Assembler::zero, done);
10880   lea(src, Address(src, len, Address::times_1));
10881   lea(dst, Address(dst, len, Address::times_2));
10882   negptr(len);
10883 
10884   // inflate 1 char per iter
10885   bind(copy_chars_loop);
10886   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10887   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10888   increment(len);
10889   jcc(Assembler::notZero, copy_chars_loop);
10890 
10891   bind(done);
10892 }
10893 
10894 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10895   switch (cond) {
10896     // Note some conditions are synonyms for others
10897     case Assembler::zero:         return Assembler::notZero;
10898     case Assembler::notZero:      return Assembler::zero;
10899     case Assembler::less:         return Assembler::greaterEqual;
10900     case Assembler::lessEqual:    return Assembler::greater;
10901     case Assembler::greater:      return Assembler::lessEqual;
10902     case Assembler::greaterEqual: return Assembler::less;
10903     case Assembler::below:        return Assembler::aboveEqual;
10904     case Assembler::belowEqual:   return Assembler::above;
10905     case Assembler::above:        return Assembler::belowEqual;
10906     case Assembler::aboveEqual:   return Assembler::below;
10907     case Assembler::overflow:     return Assembler::noOverflow;
10908     case Assembler::noOverflow:   return Assembler::overflow;
10909     case Assembler::negative:     return Assembler::positive;
10910     case Assembler::positive:     return Assembler::negative;
10911     case Assembler::parity:       return Assembler::noParity;
10912     case Assembler::noParity:     return Assembler::parity;
10913   }
10914   ShouldNotReachHere(); return Assembler::overflow;
10915 }
10916 
10917 SkipIfEqual::SkipIfEqual(
10918     MacroAssembler* masm, const bool* flag_addr, bool value) {
10919   _masm = masm;
10920   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10921   _masm->jcc(Assembler::equal, _label);
10922 }
10923 
10924 SkipIfEqual::~SkipIfEqual() {
10925   _masm->bind(_label);
10926 }
10927 
10928 // 32-bit Windows has its own fast-path implementation
10929 // of get_thread
10930 #if !defined(WIN32) || defined(_LP64)
10931 
10932 // This is simply a call to Thread::current()
10933 void MacroAssembler::get_thread(Register thread) {
10934   if (thread != rax) {
10935     push(rax);
10936   }
10937   LP64_ONLY(push(rdi);)
10938   LP64_ONLY(push(rsi);)
10939   push(rdx);
10940   push(rcx);
10941 #ifdef _LP64
10942   push(r8);
10943   push(r9);
10944   push(r10);
10945   push(r11);
10946 #endif
10947 
10948   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
10949 
10950 #ifdef _LP64
10951   pop(r11);
10952   pop(r10);
10953   pop(r9);
10954   pop(r8);
10955 #endif
10956   pop(rcx);
10957   pop(rdx);
10958   LP64_ONLY(pop(rsi);)
10959   LP64_ONLY(pop(rdi);)
10960   if (thread != rax) {
10961     mov(thread, rax);
10962     pop(rax);
10963   }
10964 }
10965 
10966 #endif