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 "jvm.h"
  27 #include "asm/assembler.hpp"
  28 #include "asm/assembler.inline.hpp"
  29 #include "compiler/disassembler.hpp"
  30 #include "gc/shared/cardTableModRefBS.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/biasedLocking.hpp"
  38 #include "runtime/interfaceSupport.hpp"
  39 #include "runtime/objectMonitor.hpp"
  40 #include "runtime/os.hpp"
  41 #include "runtime/safepoint.hpp"
  42 #include "runtime/safepointMechanism.hpp"
  43 #include "runtime/sharedRuntime.hpp"
  44 #include "runtime/stubRoutines.hpp"
  45 #include "runtime/thread.hpp"
  46 #include "utilities/macros.hpp"
  47 #if INCLUDE_ALL_GCS
  48 #include "gc/g1/g1CollectedHeap.inline.hpp"
  49 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  50 #include "gc/g1/heapRegion.hpp"
  51 #endif // INCLUDE_ALL_GCS
  52 #include "crc32c.h"
  53 #ifdef COMPILER2
  54 #include "opto/intrinsicnode.hpp"
  55 #endif
  56 
  57 #ifdef PRODUCT
  58 #define BLOCK_COMMENT(str) /* nothing */
  59 #define STOP(error) stop(error)
  60 #else
  61 #define BLOCK_COMMENT(str) block_comment(str)
  62 #define STOP(error) block_comment(error); stop(error)
  63 #endif
  64 
  65 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  66 
  67 #ifdef ASSERT
  68 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  69 #endif
  70 
  71 static Assembler::Condition reverse[] = {
  72     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  73     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  74     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  75     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  76     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  77     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  78     Assembler::above          /* belowEqual    = 0x6 */ ,
  79     Assembler::belowEqual     /* above         = 0x7 */ ,
  80     Assembler::positive       /* negative      = 0x8 */ ,
  81     Assembler::negative       /* positive      = 0x9 */ ,
  82     Assembler::noParity       /* parity        = 0xa */ ,
  83     Assembler::parity         /* noParity      = 0xb */ ,
  84     Assembler::greaterEqual   /* less          = 0xc */ ,
  85     Assembler::less           /* greaterEqual  = 0xd */ ,
  86     Assembler::greater        /* lessEqual     = 0xe */ ,
  87     Assembler::lessEqual      /* greater       = 0xf, */
  88 
  89 };
  90 
  91 
  92 // Implementation of MacroAssembler
  93 
  94 // First all the versions that have distinct versions depending on 32/64 bit
  95 // Unless the difference is trivial (1 line or so).
  96 
  97 #ifndef _LP64
  98 
  99 // 32bit versions
 100 
 101 Address MacroAssembler::as_Address(AddressLiteral adr) {
 102   return Address(adr.target(), adr.rspec());
 103 }
 104 
 105 Address MacroAssembler::as_Address(ArrayAddress adr) {
 106   return Address::make_array(adr);
 107 }
 108 
 109 void MacroAssembler::call_VM_leaf_base(address entry_point,
 110                                        int number_of_arguments) {
 111   call(RuntimeAddress(entry_point));
 112   increment(rsp, number_of_arguments * wordSize);
 113 }
 114 
 115 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 116   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 117 }
 118 
 119 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 120   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 121 }
 122 
 123 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 124   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 125 }
 126 
 127 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 128   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 129 }
 130 
 131 void MacroAssembler::extend_sign(Register hi, Register lo) {
 132   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 133   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 134     cdql();
 135   } else {
 136     movl(hi, lo);
 137     sarl(hi, 31);
 138   }
 139 }
 140 
 141 void MacroAssembler::jC2(Register tmp, Label& L) {
 142   // set parity bit if FPU flag C2 is set (via rax)
 143   save_rax(tmp);
 144   fwait(); fnstsw_ax();
 145   sahf();
 146   restore_rax(tmp);
 147   // branch
 148   jcc(Assembler::parity, L);
 149 }
 150 
 151 void MacroAssembler::jnC2(Register tmp, Label& L) {
 152   // set parity bit if FPU flag C2 is set (via rax)
 153   save_rax(tmp);
 154   fwait(); fnstsw_ax();
 155   sahf();
 156   restore_rax(tmp);
 157   // branch
 158   jcc(Assembler::noParity, L);
 159 }
 160 
 161 // 32bit can do a case table jump in one instruction but we no longer allow the base
 162 // to be installed in the Address class
 163 void MacroAssembler::jump(ArrayAddress entry) {
 164   jmp(as_Address(entry));
 165 }
 166 
 167 // Note: y_lo will be destroyed
 168 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 169   // Long compare for Java (semantics as described in JVM spec.)
 170   Label high, low, done;
 171 
 172   cmpl(x_hi, y_hi);
 173   jcc(Assembler::less, low);
 174   jcc(Assembler::greater, high);
 175   // x_hi is the return register
 176   xorl(x_hi, x_hi);
 177   cmpl(x_lo, y_lo);
 178   jcc(Assembler::below, low);
 179   jcc(Assembler::equal, done);
 180 
 181   bind(high);
 182   xorl(x_hi, x_hi);
 183   increment(x_hi);
 184   jmp(done);
 185 
 186   bind(low);
 187   xorl(x_hi, x_hi);
 188   decrementl(x_hi);
 189 
 190   bind(done);
 191 }
 192 
 193 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 194     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 195 }
 196 
 197 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 198   // leal(dst, as_Address(adr));
 199   // see note in movl as to why we must use a move
 200   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 201 }
 202 
 203 void MacroAssembler::leave() {
 204   mov(rsp, rbp);
 205   pop(rbp);
 206 }
 207 
 208 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 209   // Multiplication of two Java long values stored on the stack
 210   // as illustrated below. Result is in rdx:rax.
 211   //
 212   // rsp ---> [  ??  ] \               \
 213   //            ....    | y_rsp_offset  |
 214   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 215   //          [ y_hi ]                  | (in bytes)
 216   //            ....                    |
 217   //          [ x_lo ]                 /
 218   //          [ x_hi ]
 219   //            ....
 220   //
 221   // Basic idea: lo(result) = lo(x_lo * y_lo)
 222   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 223   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 224   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 225   Label quick;
 226   // load x_hi, y_hi and check if quick
 227   // multiplication is possible
 228   movl(rbx, x_hi);
 229   movl(rcx, y_hi);
 230   movl(rax, rbx);
 231   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 232   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 233   // do full multiplication
 234   // 1st step
 235   mull(y_lo);                                    // x_hi * y_lo
 236   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 237   // 2nd step
 238   movl(rax, x_lo);
 239   mull(rcx);                                     // x_lo * y_hi
 240   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 241   // 3rd step
 242   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 243   movl(rax, x_lo);
 244   mull(y_lo);                                    // x_lo * y_lo
 245   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 246 }
 247 
 248 void MacroAssembler::lneg(Register hi, Register lo) {
 249   negl(lo);
 250   adcl(hi, 0);
 251   negl(hi);
 252 }
 253 
 254 void MacroAssembler::lshl(Register hi, Register lo) {
 255   // Java shift left long support (semantics as described in JVM spec., p.305)
 256   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 257   // shift value is in rcx !
 258   assert(hi != rcx, "must not use rcx");
 259   assert(lo != rcx, "must not use rcx");
 260   const Register s = rcx;                        // shift count
 261   const int      n = BitsPerWord;
 262   Label L;
 263   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 264   cmpl(s, n);                                    // if (s < n)
 265   jcc(Assembler::less, L);                       // else (s >= n)
 266   movl(hi, lo);                                  // x := x << n
 267   xorl(lo, lo);
 268   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 269   bind(L);                                       // s (mod n) < n
 270   shldl(hi, lo);                                 // x := x << s
 271   shll(lo);
 272 }
 273 
 274 
 275 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 276   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 277   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 278   assert(hi != rcx, "must not use rcx");
 279   assert(lo != rcx, "must not use rcx");
 280   const Register s = rcx;                        // shift count
 281   const int      n = BitsPerWord;
 282   Label L;
 283   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 284   cmpl(s, n);                                    // if (s < n)
 285   jcc(Assembler::less, L);                       // else (s >= n)
 286   movl(lo, hi);                                  // x := x >> n
 287   if (sign_extension) sarl(hi, 31);
 288   else                xorl(hi, hi);
 289   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 290   bind(L);                                       // s (mod n) < n
 291   shrdl(lo, hi);                                 // x := x >> s
 292   if (sign_extension) sarl(hi);
 293   else                shrl(hi);
 294 }
 295 
 296 void MacroAssembler::movoop(Register dst, jobject obj) {
 297   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 298 }
 299 
 300 void MacroAssembler::movoop(Address dst, jobject obj) {
 301   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 302 }
 303 
 304 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 305   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 306 }
 307 
 308 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 309   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 310 }
 311 
 312 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 313   // scratch register is not used,
 314   // it is defined to match parameters of 64-bit version of this method.
 315   if (src.is_lval()) {
 316     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 317   } else {
 318     movl(dst, as_Address(src));
 319   }
 320 }
 321 
 322 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 323   movl(as_Address(dst), src);
 324 }
 325 
 326 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 327   movl(dst, as_Address(src));
 328 }
 329 
 330 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 331 void MacroAssembler::movptr(Address dst, intptr_t src) {
 332   movl(dst, src);
 333 }
 334 
 335 
 336 void MacroAssembler::pop_callee_saved_registers() {
 337   pop(rcx);
 338   pop(rdx);
 339   pop(rdi);
 340   pop(rsi);
 341 }
 342 
 343 void MacroAssembler::pop_fTOS() {
 344   fld_d(Address(rsp, 0));
 345   addl(rsp, 2 * wordSize);
 346 }
 347 
 348 void MacroAssembler::push_callee_saved_registers() {
 349   push(rsi);
 350   push(rdi);
 351   push(rdx);
 352   push(rcx);
 353 }
 354 
 355 void MacroAssembler::push_fTOS() {
 356   subl(rsp, 2 * wordSize);
 357   fstp_d(Address(rsp, 0));
 358 }
 359 
 360 
 361 void MacroAssembler::pushoop(jobject obj) {
 362   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 363 }
 364 
 365 void MacroAssembler::pushklass(Metadata* obj) {
 366   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 367 }
 368 
 369 void MacroAssembler::pushptr(AddressLiteral src) {
 370   if (src.is_lval()) {
 371     push_literal32((int32_t)src.target(), src.rspec());
 372   } else {
 373     pushl(as_Address(src));
 374   }
 375 }
 376 
 377 void MacroAssembler::set_word_if_not_zero(Register dst) {
 378   xorl(dst, dst);
 379   set_byte_if_not_zero(dst);
 380 }
 381 
 382 static void pass_arg0(MacroAssembler* masm, Register arg) {
 383   masm->push(arg);
 384 }
 385 
 386 static void pass_arg1(MacroAssembler* masm, Register arg) {
 387   masm->push(arg);
 388 }
 389 
 390 static void pass_arg2(MacroAssembler* masm, Register arg) {
 391   masm->push(arg);
 392 }
 393 
 394 static void pass_arg3(MacroAssembler* masm, Register arg) {
 395   masm->push(arg);
 396 }
 397 
 398 #ifndef PRODUCT
 399 extern "C" void findpc(intptr_t x);
 400 #endif
 401 
 402 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 403   // In order to get locks to work, we need to fake a in_VM state
 404   JavaThread* thread = JavaThread::current();
 405   JavaThreadState saved_state = thread->thread_state();
 406   thread->set_thread_state(_thread_in_vm);
 407   if (ShowMessageBoxOnError) {
 408     JavaThread* thread = JavaThread::current();
 409     JavaThreadState saved_state = thread->thread_state();
 410     thread->set_thread_state(_thread_in_vm);
 411     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 412       ttyLocker ttyl;
 413       BytecodeCounter::print();
 414     }
 415     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 416     // This is the value of eip which points to where verify_oop will return.
 417     if (os::message_box(msg, "Execution stopped, print registers?")) {
 418       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 419       BREAKPOINT;
 420     }
 421   } else {
 422     ttyLocker ttyl;
 423     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 424   }
 425   // Don't assert holding the ttyLock
 426     assert(false, "DEBUG MESSAGE: %s", msg);
 427   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 428 }
 429 
 430 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 431   ttyLocker ttyl;
 432   FlagSetting fs(Debugging, true);
 433   tty->print_cr("eip = 0x%08x", eip);
 434 #ifndef PRODUCT
 435   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 436     tty->cr();
 437     findpc(eip);
 438     tty->cr();
 439   }
 440 #endif
 441 #define PRINT_REG(rax) \
 442   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 443   PRINT_REG(rax);
 444   PRINT_REG(rbx);
 445   PRINT_REG(rcx);
 446   PRINT_REG(rdx);
 447   PRINT_REG(rdi);
 448   PRINT_REG(rsi);
 449   PRINT_REG(rbp);
 450   PRINT_REG(rsp);
 451 #undef PRINT_REG
 452   // Print some words near top of staack.
 453   int* dump_sp = (int*) rsp;
 454   for (int col1 = 0; col1 < 8; col1++) {
 455     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 456     os::print_location(tty, *dump_sp++);
 457   }
 458   for (int row = 0; row < 16; row++) {
 459     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 460     for (int col = 0; col < 8; col++) {
 461       tty->print(" 0x%08x", *dump_sp++);
 462     }
 463     tty->cr();
 464   }
 465   // Print some instructions around pc:
 466   Disassembler::decode((address)eip-64, (address)eip);
 467   tty->print_cr("--------");
 468   Disassembler::decode((address)eip, (address)eip+32);
 469 }
 470 
 471 void MacroAssembler::stop(const char* msg) {
 472   ExternalAddress message((address)msg);
 473   // push address of message
 474   pushptr(message.addr());
 475   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 476   pusha();                                            // push registers
 477   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 478   hlt();
 479 }
 480 
 481 void MacroAssembler::warn(const char* msg) {
 482   push_CPU_state();
 483 
 484   ExternalAddress message((address) msg);
 485   // push address of message
 486   pushptr(message.addr());
 487 
 488   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 489   addl(rsp, wordSize);       // discard argument
 490   pop_CPU_state();
 491 }
 492 
 493 void MacroAssembler::print_state() {
 494   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 495   pusha();                                            // push registers
 496 
 497   push_CPU_state();
 498   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 499   pop_CPU_state();
 500 
 501   popa();
 502   addl(rsp, wordSize);
 503 }
 504 
 505 #else // _LP64
 506 
 507 // 64 bit versions
 508 
 509 Address MacroAssembler::as_Address(AddressLiteral adr) {
 510   // amd64 always does this as a pc-rel
 511   // we can be absolute or disp based on the instruction type
 512   // jmp/call are displacements others are absolute
 513   assert(!adr.is_lval(), "must be rval");
 514   assert(reachable(adr), "must be");
 515   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 516 
 517 }
 518 
 519 Address MacroAssembler::as_Address(ArrayAddress adr) {
 520   AddressLiteral base = adr.base();
 521   lea(rscratch1, base);
 522   Address index = adr.index();
 523   assert(index._disp == 0, "must not have disp"); // maybe it can?
 524   Address array(rscratch1, index._index, index._scale, index._disp);
 525   return array;
 526 }
 527 
 528 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 529   Label L, E;
 530 
 531 #ifdef _WIN64
 532   // Windows always allocates space for it's register args
 533   assert(num_args <= 4, "only register arguments supported");
 534   subq(rsp,  frame::arg_reg_save_area_bytes);
 535 #endif
 536 
 537   // Align stack if necessary
 538   testl(rsp, 15);
 539   jcc(Assembler::zero, L);
 540 
 541   subq(rsp, 8);
 542   {
 543     call(RuntimeAddress(entry_point));
 544   }
 545   addq(rsp, 8);
 546   jmp(E);
 547 
 548   bind(L);
 549   {
 550     call(RuntimeAddress(entry_point));
 551   }
 552 
 553   bind(E);
 554 
 555 #ifdef _WIN64
 556   // restore stack pointer
 557   addq(rsp, frame::arg_reg_save_area_bytes);
 558 #endif
 559 
 560 }
 561 
 562 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 563   assert(!src2.is_lval(), "should use cmpptr");
 564 
 565   if (reachable(src2)) {
 566     cmpq(src1, as_Address(src2));
 567   } else {
 568     lea(rscratch1, src2);
 569     Assembler::cmpq(src1, Address(rscratch1, 0));
 570   }
 571 }
 572 
 573 int MacroAssembler::corrected_idivq(Register reg) {
 574   // Full implementation of Java ldiv and lrem; checks for special
 575   // case as described in JVM spec., p.243 & p.271.  The function
 576   // returns the (pc) offset of the idivl instruction - may be needed
 577   // for implicit exceptions.
 578   //
 579   //         normal case                           special case
 580   //
 581   // input : rax: dividend                         min_long
 582   //         reg: divisor   (may not be eax/edx)   -1
 583   //
 584   // output: rax: quotient  (= rax idiv reg)       min_long
 585   //         rdx: remainder (= rax irem reg)       0
 586   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 587   static const int64_t min_long = 0x8000000000000000;
 588   Label normal_case, special_case;
 589 
 590   // check for special case
 591   cmp64(rax, ExternalAddress((address) &min_long));
 592   jcc(Assembler::notEqual, normal_case);
 593   xorl(rdx, rdx); // prepare rdx for possible special case (where
 594                   // remainder = 0)
 595   cmpq(reg, -1);
 596   jcc(Assembler::equal, special_case);
 597 
 598   // handle normal case
 599   bind(normal_case);
 600   cdqq();
 601   int idivq_offset = offset();
 602   idivq(reg);
 603 
 604   // normal and special case exit
 605   bind(special_case);
 606 
 607   return idivq_offset;
 608 }
 609 
 610 void MacroAssembler::decrementq(Register reg, int value) {
 611   if (value == min_jint) { subq(reg, value); return; }
 612   if (value <  0) { incrementq(reg, -value); return; }
 613   if (value == 0) {                        ; return; }
 614   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 615   /* else */      { subq(reg, value)       ; return; }
 616 }
 617 
 618 void MacroAssembler::decrementq(Address dst, int value) {
 619   if (value == min_jint) { subq(dst, value); return; }
 620   if (value <  0) { incrementq(dst, -value); return; }
 621   if (value == 0) {                        ; return; }
 622   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 623   /* else */      { subq(dst, value)       ; return; }
 624 }
 625 
 626 void MacroAssembler::incrementq(AddressLiteral dst) {
 627   if (reachable(dst)) {
 628     incrementq(as_Address(dst));
 629   } else {
 630     lea(rscratch1, dst);
 631     incrementq(Address(rscratch1, 0));
 632   }
 633 }
 634 
 635 void MacroAssembler::incrementq(Register reg, int value) {
 636   if (value == min_jint) { addq(reg, value); return; }
 637   if (value <  0) { decrementq(reg, -value); return; }
 638   if (value == 0) {                        ; return; }
 639   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 640   /* else */      { addq(reg, value)       ; return; }
 641 }
 642 
 643 void MacroAssembler::incrementq(Address dst, int value) {
 644   if (value == min_jint) { addq(dst, value); return; }
 645   if (value <  0) { decrementq(dst, -value); return; }
 646   if (value == 0) {                        ; return; }
 647   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 648   /* else */      { addq(dst, value)       ; return; }
 649 }
 650 
 651 // 32bit can do a case table jump in one instruction but we no longer allow the base
 652 // to be installed in the Address class
 653 void MacroAssembler::jump(ArrayAddress entry) {
 654   lea(rscratch1, entry.base());
 655   Address dispatch = entry.index();
 656   assert(dispatch._base == noreg, "must be");
 657   dispatch._base = rscratch1;
 658   jmp(dispatch);
 659 }
 660 
 661 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 662   ShouldNotReachHere(); // 64bit doesn't use two regs
 663   cmpq(x_lo, y_lo);
 664 }
 665 
 666 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 667     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 668 }
 669 
 670 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 671   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 672   movptr(dst, rscratch1);
 673 }
 674 
 675 void MacroAssembler::leave() {
 676   // %%% is this really better? Why not on 32bit too?
 677   emit_int8((unsigned char)0xC9); // LEAVE
 678 }
 679 
 680 void MacroAssembler::lneg(Register hi, Register lo) {
 681   ShouldNotReachHere(); // 64bit doesn't use two regs
 682   negq(lo);
 683 }
 684 
 685 void MacroAssembler::movoop(Register dst, jobject obj) {
 686   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 687 }
 688 
 689 void MacroAssembler::movoop(Address dst, jobject obj) {
 690   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 691   movq(dst, rscratch1);
 692 }
 693 
 694 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 695   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 696 }
 697 
 698 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 699   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 700   movq(dst, rscratch1);
 701 }
 702 
 703 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 704   if (src.is_lval()) {
 705     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 706   } else {
 707     if (reachable(src)) {
 708       movq(dst, as_Address(src));
 709     } else {
 710       lea(scratch, src);
 711       movq(dst, Address(scratch, 0));
 712     }
 713   }
 714 }
 715 
 716 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 717   movq(as_Address(dst), src);
 718 }
 719 
 720 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 721   movq(dst, as_Address(src));
 722 }
 723 
 724 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 725 void MacroAssembler::movptr(Address dst, intptr_t src) {
 726   mov64(rscratch1, src);
 727   movq(dst, rscratch1);
 728 }
 729 
 730 // These are mostly for initializing NULL
 731 void MacroAssembler::movptr(Address dst, int32_t src) {
 732   movslq(dst, src);
 733 }
 734 
 735 void MacroAssembler::movptr(Register dst, int32_t src) {
 736   mov64(dst, (intptr_t)src);
 737 }
 738 
 739 void MacroAssembler::pushoop(jobject obj) {
 740   movoop(rscratch1, obj);
 741   push(rscratch1);
 742 }
 743 
 744 void MacroAssembler::pushklass(Metadata* obj) {
 745   mov_metadata(rscratch1, obj);
 746   push(rscratch1);
 747 }
 748 
 749 void MacroAssembler::pushptr(AddressLiteral src) {
 750   lea(rscratch1, src);
 751   if (src.is_lval()) {
 752     push(rscratch1);
 753   } else {
 754     pushq(Address(rscratch1, 0));
 755   }
 756 }
 757 
 758 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 759   // we must set sp to zero to clear frame
 760   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 761   // must clear fp, so that compiled frames are not confused; it is
 762   // possible that we need it only for debugging
 763   if (clear_fp) {
 764     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 765   }
 766 
 767   // Always clear the pc because it could have been set by make_walkable()
 768   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 769   vzeroupper();
 770 }
 771 
 772 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 773                                          Register last_java_fp,
 774                                          address  last_java_pc) {
 775   vzeroupper();
 776   // determine last_java_sp register
 777   if (!last_java_sp->is_valid()) {
 778     last_java_sp = rsp;
 779   }
 780 
 781   // last_java_fp is optional
 782   if (last_java_fp->is_valid()) {
 783     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 784            last_java_fp);
 785   }
 786 
 787   // last_java_pc is optional
 788   if (last_java_pc != NULL) {
 789     Address java_pc(r15_thread,
 790                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 791     lea(rscratch1, InternalAddress(last_java_pc));
 792     movptr(java_pc, rscratch1);
 793   }
 794 
 795   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 796 }
 797 
 798 static void pass_arg0(MacroAssembler* masm, Register arg) {
 799   if (c_rarg0 != arg ) {
 800     masm->mov(c_rarg0, arg);
 801   }
 802 }
 803 
 804 static void pass_arg1(MacroAssembler* masm, Register arg) {
 805   if (c_rarg1 != arg ) {
 806     masm->mov(c_rarg1, arg);
 807   }
 808 }
 809 
 810 static void pass_arg2(MacroAssembler* masm, Register arg) {
 811   if (c_rarg2 != arg ) {
 812     masm->mov(c_rarg2, arg);
 813   }
 814 }
 815 
 816 static void pass_arg3(MacroAssembler* masm, Register arg) {
 817   if (c_rarg3 != arg ) {
 818     masm->mov(c_rarg3, arg);
 819   }
 820 }
 821 
 822 void MacroAssembler::stop(const char* msg) {
 823   address rip = pc();
 824   pusha(); // get regs on stack
 825   lea(c_rarg0, ExternalAddress((address) msg));
 826   lea(c_rarg1, InternalAddress(rip));
 827   movq(c_rarg2, rsp); // pass pointer to regs array
 828   andq(rsp, -16); // align stack as required by ABI
 829   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 830   hlt();
 831 }
 832 
 833 void MacroAssembler::warn(const char* msg) {
 834   push(rbp);
 835   movq(rbp, rsp);
 836   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 837   push_CPU_state();   // keeps alignment at 16 bytes
 838   lea(c_rarg0, ExternalAddress((address) msg));
 839   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 840   pop_CPU_state();
 841   mov(rsp, rbp);
 842   pop(rbp);
 843 }
 844 
 845 void MacroAssembler::print_state() {
 846   address rip = pc();
 847   pusha();            // get regs on stack
 848   push(rbp);
 849   movq(rbp, rsp);
 850   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 851   push_CPU_state();   // keeps alignment at 16 bytes
 852 
 853   lea(c_rarg0, InternalAddress(rip));
 854   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 855   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 856 
 857   pop_CPU_state();
 858   mov(rsp, rbp);
 859   pop(rbp);
 860   popa();
 861 }
 862 
 863 #ifndef PRODUCT
 864 extern "C" void findpc(intptr_t x);
 865 #endif
 866 
 867 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 868   // In order to get locks to work, we need to fake a in_VM state
 869   if (ShowMessageBoxOnError) {
 870     JavaThread* thread = JavaThread::current();
 871     JavaThreadState saved_state = thread->thread_state();
 872     thread->set_thread_state(_thread_in_vm);
 873 #ifndef PRODUCT
 874     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 875       ttyLocker ttyl;
 876       BytecodeCounter::print();
 877     }
 878 #endif
 879     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 880     // XXX correct this offset for amd64
 881     // This is the value of eip which points to where verify_oop will return.
 882     if (os::message_box(msg, "Execution stopped, print registers?")) {
 883       print_state64(pc, regs);
 884       BREAKPOINT;
 885       assert(false, "start up GDB");
 886     }
 887     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 888   } else {
 889     ttyLocker ttyl;
 890     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 891                     msg);
 892     assert(false, "DEBUG MESSAGE: %s", msg);
 893   }
 894 }
 895 
 896 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 897   ttyLocker ttyl;
 898   FlagSetting fs(Debugging, true);
 899   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 900 #ifndef PRODUCT
 901   tty->cr();
 902   findpc(pc);
 903   tty->cr();
 904 #endif
 905 #define PRINT_REG(rax, value) \
 906   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 907   PRINT_REG(rax, regs[15]);
 908   PRINT_REG(rbx, regs[12]);
 909   PRINT_REG(rcx, regs[14]);
 910   PRINT_REG(rdx, regs[13]);
 911   PRINT_REG(rdi, regs[8]);
 912   PRINT_REG(rsi, regs[9]);
 913   PRINT_REG(rbp, regs[10]);
 914   PRINT_REG(rsp, regs[11]);
 915   PRINT_REG(r8 , regs[7]);
 916   PRINT_REG(r9 , regs[6]);
 917   PRINT_REG(r10, regs[5]);
 918   PRINT_REG(r11, regs[4]);
 919   PRINT_REG(r12, regs[3]);
 920   PRINT_REG(r13, regs[2]);
 921   PRINT_REG(r14, regs[1]);
 922   PRINT_REG(r15, regs[0]);
 923 #undef PRINT_REG
 924   // Print some words near top of staack.
 925   int64_t* rsp = (int64_t*) regs[11];
 926   int64_t* dump_sp = rsp;
 927   for (int col1 = 0; col1 < 8; col1++) {
 928     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 929     os::print_location(tty, *dump_sp++);
 930   }
 931   for (int row = 0; row < 25; row++) {
 932     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 933     for (int col = 0; col < 4; col++) {
 934       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 935     }
 936     tty->cr();
 937   }
 938   // Print some instructions around pc:
 939   Disassembler::decode((address)pc-64, (address)pc);
 940   tty->print_cr("--------");
 941   Disassembler::decode((address)pc, (address)pc+32);
 942 }
 943 
 944 #endif // _LP64
 945 
 946 // Now versions that are common to 32/64 bit
 947 
 948 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 949   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 950 }
 951 
 952 void MacroAssembler::addptr(Register dst, Register src) {
 953   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 954 }
 955 
 956 void MacroAssembler::addptr(Address dst, Register src) {
 957   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 958 }
 959 
 960 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 961   if (reachable(src)) {
 962     Assembler::addsd(dst, as_Address(src));
 963   } else {
 964     lea(rscratch1, src);
 965     Assembler::addsd(dst, Address(rscratch1, 0));
 966   }
 967 }
 968 
 969 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 970   if (reachable(src)) {
 971     addss(dst, as_Address(src));
 972   } else {
 973     lea(rscratch1, src);
 974     addss(dst, Address(rscratch1, 0));
 975   }
 976 }
 977 
 978 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 979   if (reachable(src)) {
 980     Assembler::addpd(dst, as_Address(src));
 981   } else {
 982     lea(rscratch1, src);
 983     Assembler::addpd(dst, Address(rscratch1, 0));
 984   }
 985 }
 986 
 987 void MacroAssembler::align(int modulus) {
 988   align(modulus, offset());
 989 }
 990 
 991 void MacroAssembler::align(int modulus, int target) {
 992   if (target % modulus != 0) {
 993     nop(modulus - (target % modulus));
 994   }
 995 }
 996 
 997 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 998   // Used in sign-masking with aligned address.
 999   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1000   if (reachable(src)) {
1001     Assembler::andpd(dst, as_Address(src));
1002   } else {
1003     lea(rscratch1, src);
1004     Assembler::andpd(dst, Address(rscratch1, 0));
1005   }
1006 }
1007 
1008 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1009   // Used in sign-masking with aligned address.
1010   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1011   if (reachable(src)) {
1012     Assembler::andps(dst, as_Address(src));
1013   } else {
1014     lea(rscratch1, src);
1015     Assembler::andps(dst, Address(rscratch1, 0));
1016   }
1017 }
1018 
1019 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1020   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1021 }
1022 
1023 void MacroAssembler::atomic_incl(Address counter_addr) {
1024   if (os::is_MP())
1025     lock();
1026   incrementl(counter_addr);
1027 }
1028 
1029 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1030   if (reachable(counter_addr)) {
1031     atomic_incl(as_Address(counter_addr));
1032   } else {
1033     lea(scr, counter_addr);
1034     atomic_incl(Address(scr, 0));
1035   }
1036 }
1037 
1038 #ifdef _LP64
1039 void MacroAssembler::atomic_incq(Address counter_addr) {
1040   if (os::is_MP())
1041     lock();
1042   incrementq(counter_addr);
1043 }
1044 
1045 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1046   if (reachable(counter_addr)) {
1047     atomic_incq(as_Address(counter_addr));
1048   } else {
1049     lea(scr, counter_addr);
1050     atomic_incq(Address(scr, 0));
1051   }
1052 }
1053 #endif
1054 
1055 // Writes to stack successive pages until offset reached to check for
1056 // stack overflow + shadow pages.  This clobbers tmp.
1057 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1058   movptr(tmp, rsp);
1059   // Bang stack for total size given plus shadow page size.
1060   // Bang one page at a time because large size can bang beyond yellow and
1061   // red zones.
1062   Label loop;
1063   bind(loop);
1064   movl(Address(tmp, (-os::vm_page_size())), size );
1065   subptr(tmp, os::vm_page_size());
1066   subl(size, os::vm_page_size());
1067   jcc(Assembler::greater, loop);
1068 
1069   // Bang down shadow pages too.
1070   // At this point, (tmp-0) is the last address touched, so don't
1071   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1072   // was post-decremented.)  Skip this address by starting at i=1, and
1073   // touch a few more pages below.  N.B.  It is important to touch all
1074   // the way down including all pages in the shadow zone.
1075   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1076     // this could be any sized move but this is can be a debugging crumb
1077     // so the bigger the better.
1078     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1079   }
1080 }
1081 
1082 void MacroAssembler::reserved_stack_check() {
1083     // testing if reserved zone needs to be enabled
1084     Label no_reserved_zone_enabling;
1085     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1086     NOT_LP64(get_thread(rsi);)
1087 
1088     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1089     jcc(Assembler::below, no_reserved_zone_enabling);
1090 
1091     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1092     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1093     should_not_reach_here();
1094 
1095     bind(no_reserved_zone_enabling);
1096 }
1097 
1098 int MacroAssembler::biased_locking_enter(Register lock_reg,
1099                                          Register obj_reg,
1100                                          Register swap_reg,
1101                                          Register tmp_reg,
1102                                          bool swap_reg_contains_mark,
1103                                          Label& done,
1104                                          Label* slow_case,
1105                                          BiasedLockingCounters* counters) {
1106   assert(UseBiasedLocking, "why call this otherwise?");
1107   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1108   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1109   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1110   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1111   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1112   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1113 
1114   if (PrintBiasedLockingStatistics && counters == NULL) {
1115     counters = BiasedLocking::counters();
1116   }
1117   // Biased locking
1118   // See whether the lock is currently biased toward our thread and
1119   // whether the epoch is still valid
1120   // Note that the runtime guarantees sufficient alignment of JavaThread
1121   // pointers to allow age to be placed into low bits
1122   // First check to see whether biasing is even enabled for this object
1123   Label cas_label;
1124   int null_check_offset = -1;
1125   if (!swap_reg_contains_mark) {
1126     null_check_offset = offset();
1127     movptr(swap_reg, mark_addr);
1128   }
1129   movptr(tmp_reg, swap_reg);
1130   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1131   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1132   jcc(Assembler::notEqual, cas_label);
1133   // The bias pattern is present in the object's header. Need to check
1134   // whether the bias owner and the epoch are both still current.
1135 #ifndef _LP64
1136   // Note that because there is no current thread register on x86_32 we
1137   // need to store off the mark word we read out of the object to
1138   // avoid reloading it and needing to recheck invariants below. This
1139   // store is unfortunate but it makes the overall code shorter and
1140   // simpler.
1141   movptr(saved_mark_addr, swap_reg);
1142 #endif
1143   if (swap_reg_contains_mark) {
1144     null_check_offset = offset();
1145   }
1146   load_prototype_header(tmp_reg, obj_reg);
1147 #ifdef _LP64
1148   orptr(tmp_reg, r15_thread);
1149   xorptr(tmp_reg, swap_reg);
1150   Register header_reg = tmp_reg;
1151 #else
1152   xorptr(tmp_reg, swap_reg);
1153   get_thread(swap_reg);
1154   xorptr(swap_reg, tmp_reg);
1155   Register header_reg = swap_reg;
1156 #endif
1157   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1158   if (counters != NULL) {
1159     cond_inc32(Assembler::zero,
1160                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1161   }
1162   jcc(Assembler::equal, done);
1163 
1164   Label try_revoke_bias;
1165   Label try_rebias;
1166 
1167   // At this point we know that the header has the bias pattern and
1168   // that we are not the bias owner in the current epoch. We need to
1169   // figure out more details about the state of the header in order to
1170   // know what operations can be legally performed on the object's
1171   // header.
1172 
1173   // If the low three bits in the xor result aren't clear, that means
1174   // the prototype header is no longer biased and we have to revoke
1175   // the bias on this object.
1176   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1177   jccb(Assembler::notZero, try_revoke_bias);
1178 
1179   // Biasing is still enabled for this data type. See whether the
1180   // epoch of the current bias is still valid, meaning that the epoch
1181   // bits of the mark word are equal to the epoch bits of the
1182   // prototype header. (Note that the prototype header's epoch bits
1183   // only change at a safepoint.) If not, attempt to rebias the object
1184   // toward the current thread. Note that we must be absolutely sure
1185   // that the current epoch is invalid in order to do this because
1186   // otherwise the manipulations it performs on the mark word are
1187   // illegal.
1188   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1189   jccb(Assembler::notZero, try_rebias);
1190 
1191   // The epoch of the current bias is still valid but we know nothing
1192   // about the owner; it might be set or it might be clear. Try to
1193   // acquire the bias of the object using an atomic operation. If this
1194   // fails we will go in to the runtime to revoke the object's bias.
1195   // Note that we first construct the presumed unbiased header so we
1196   // don't accidentally blow away another thread's valid bias.
1197   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1198   andptr(swap_reg,
1199          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1200 #ifdef _LP64
1201   movptr(tmp_reg, swap_reg);
1202   orptr(tmp_reg, r15_thread);
1203 #else
1204   get_thread(tmp_reg);
1205   orptr(tmp_reg, swap_reg);
1206 #endif
1207   if (os::is_MP()) {
1208     lock();
1209   }
1210   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1211   // If the biasing toward our thread failed, this means that
1212   // another thread succeeded in biasing it toward itself and we
1213   // need to revoke that bias. The revocation will occur in the
1214   // interpreter runtime in the slow case.
1215   if (counters != NULL) {
1216     cond_inc32(Assembler::zero,
1217                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1218   }
1219   if (slow_case != NULL) {
1220     jcc(Assembler::notZero, *slow_case);
1221   }
1222   jmp(done);
1223 
1224   bind(try_rebias);
1225   // At this point we know the epoch has expired, meaning that the
1226   // current "bias owner", if any, is actually invalid. Under these
1227   // circumstances _only_, we are allowed to use the current header's
1228   // value as the comparison value when doing the cas to acquire the
1229   // bias in the current epoch. In other words, we allow transfer of
1230   // the bias from one thread to another directly in this situation.
1231   //
1232   // FIXME: due to a lack of registers we currently blow away the age
1233   // bits in this situation. Should attempt to preserve them.
1234   load_prototype_header(tmp_reg, obj_reg);
1235 #ifdef _LP64
1236   orptr(tmp_reg, r15_thread);
1237 #else
1238   get_thread(swap_reg);
1239   orptr(tmp_reg, swap_reg);
1240   movptr(swap_reg, saved_mark_addr);
1241 #endif
1242   if (os::is_MP()) {
1243     lock();
1244   }
1245   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1246   // If the biasing toward our thread failed, then another thread
1247   // succeeded in biasing it toward itself and we need to revoke that
1248   // bias. The revocation will occur in the runtime in the slow case.
1249   if (counters != NULL) {
1250     cond_inc32(Assembler::zero,
1251                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1252   }
1253   if (slow_case != NULL) {
1254     jcc(Assembler::notZero, *slow_case);
1255   }
1256   jmp(done);
1257 
1258   bind(try_revoke_bias);
1259   // The prototype mark in the klass doesn't have the bias bit set any
1260   // more, indicating that objects of this data type are not supposed
1261   // to be biased any more. We are going to try to reset the mark of
1262   // this object to the prototype value and fall through to the
1263   // CAS-based locking scheme. Note that if our CAS fails, it means
1264   // that another thread raced us for the privilege of revoking the
1265   // bias of this particular object, so it's okay to continue in the
1266   // normal locking code.
1267   //
1268   // FIXME: due to a lack of registers we currently blow away the age
1269   // bits in this situation. Should attempt to preserve them.
1270   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1271   load_prototype_header(tmp_reg, obj_reg);
1272   if (os::is_MP()) {
1273     lock();
1274   }
1275   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1276   // Fall through to the normal CAS-based lock, because no matter what
1277   // the result of the above CAS, some thread must have succeeded in
1278   // removing the bias bit from the object's header.
1279   if (counters != NULL) {
1280     cond_inc32(Assembler::zero,
1281                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1282   }
1283 
1284   bind(cas_label);
1285 
1286   return null_check_offset;
1287 }
1288 
1289 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1290   assert(UseBiasedLocking, "why call this otherwise?");
1291 
1292   // Check for biased locking unlock case, which is a no-op
1293   // Note: we do not have to check the thread ID for two reasons.
1294   // First, the interpreter checks for IllegalMonitorStateException at
1295   // a higher level. Second, if the bias was revoked while we held the
1296   // lock, the object could not be rebiased toward another thread, so
1297   // the bias bit would be clear.
1298   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1299   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1300   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1301   jcc(Assembler::equal, done);
1302 }
1303 
1304 #ifdef COMPILER2
1305 
1306 #if INCLUDE_RTM_OPT
1307 
1308 // Update rtm_counters based on abort status
1309 // input: abort_status
1310 //        rtm_counters (RTMLockingCounters*)
1311 // flags are killed
1312 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1313 
1314   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1315   if (PrintPreciseRTMLockingStatistics) {
1316     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1317       Label check_abort;
1318       testl(abort_status, (1<<i));
1319       jccb(Assembler::equal, check_abort);
1320       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1321       bind(check_abort);
1322     }
1323   }
1324 }
1325 
1326 // Branch if (random & (count-1) != 0), count is 2^n
1327 // tmp, scr and flags are killed
1328 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1329   assert(tmp == rax, "");
1330   assert(scr == rdx, "");
1331   rdtsc(); // modifies EDX:EAX
1332   andptr(tmp, count-1);
1333   jccb(Assembler::notZero, brLabel);
1334 }
1335 
1336 // Perform abort ratio calculation, set no_rtm bit if high ratio
1337 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1338 // tmpReg, rtm_counters_Reg and flags are killed
1339 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1340                                                  Register rtm_counters_Reg,
1341                                                  RTMLockingCounters* rtm_counters,
1342                                                  Metadata* method_data) {
1343   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1344 
1345   if (RTMLockingCalculationDelay > 0) {
1346     // Delay calculation
1347     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1348     testptr(tmpReg, tmpReg);
1349     jccb(Assembler::equal, L_done);
1350   }
1351   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1352   //   Aborted transactions = abort_count * 100
1353   //   All transactions = total_count *  RTMTotalCountIncrRate
1354   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1355 
1356   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1357   cmpptr(tmpReg, RTMAbortThreshold);
1358   jccb(Assembler::below, L_check_always_rtm2);
1359   imulptr(tmpReg, tmpReg, 100);
1360 
1361   Register scrReg = rtm_counters_Reg;
1362   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1363   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1364   imulptr(scrReg, scrReg, RTMAbortRatio);
1365   cmpptr(tmpReg, scrReg);
1366   jccb(Assembler::below, L_check_always_rtm1);
1367   if (method_data != NULL) {
1368     // set rtm_state to "no rtm" in MDO
1369     mov_metadata(tmpReg, method_data);
1370     if (os::is_MP()) {
1371       lock();
1372     }
1373     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1374   }
1375   jmpb(L_done);
1376   bind(L_check_always_rtm1);
1377   // Reload RTMLockingCounters* address
1378   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1379   bind(L_check_always_rtm2);
1380   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1381   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1382   jccb(Assembler::below, L_done);
1383   if (method_data != NULL) {
1384     // set rtm_state to "always rtm" in MDO
1385     mov_metadata(tmpReg, method_data);
1386     if (os::is_MP()) {
1387       lock();
1388     }
1389     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1390   }
1391   bind(L_done);
1392 }
1393 
1394 // Update counters and perform abort ratio calculation
1395 // input:  abort_status_Reg
1396 // rtm_counters_Reg, flags are killed
1397 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1398                                    Register rtm_counters_Reg,
1399                                    RTMLockingCounters* rtm_counters,
1400                                    Metadata* method_data,
1401                                    bool profile_rtm) {
1402 
1403   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1404   // update rtm counters based on rax value at abort
1405   // reads abort_status_Reg, updates flags
1406   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1407   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1408   if (profile_rtm) {
1409     // Save abort status because abort_status_Reg is used by following code.
1410     if (RTMRetryCount > 0) {
1411       push(abort_status_Reg);
1412     }
1413     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1414     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1415     // restore abort status
1416     if (RTMRetryCount > 0) {
1417       pop(abort_status_Reg);
1418     }
1419   }
1420 }
1421 
1422 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1423 // inputs: retry_count_Reg
1424 //       : abort_status_Reg
1425 // output: retry_count_Reg decremented by 1
1426 // flags are killed
1427 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1428   Label doneRetry;
1429   assert(abort_status_Reg == rax, "");
1430   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1431   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1432   // if reason is in 0x6 and retry count != 0 then retry
1433   andptr(abort_status_Reg, 0x6);
1434   jccb(Assembler::zero, doneRetry);
1435   testl(retry_count_Reg, retry_count_Reg);
1436   jccb(Assembler::zero, doneRetry);
1437   pause();
1438   decrementl(retry_count_Reg);
1439   jmp(retryLabel);
1440   bind(doneRetry);
1441 }
1442 
1443 // Spin and retry if lock is busy,
1444 // inputs: box_Reg (monitor address)
1445 //       : retry_count_Reg
1446 // output: retry_count_Reg decremented by 1
1447 //       : clear z flag if retry count exceeded
1448 // tmp_Reg, scr_Reg, flags are killed
1449 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1450                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1451   Label SpinLoop, SpinExit, doneRetry;
1452   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1453 
1454   testl(retry_count_Reg, retry_count_Reg);
1455   jccb(Assembler::zero, doneRetry);
1456   decrementl(retry_count_Reg);
1457   movptr(scr_Reg, RTMSpinLoopCount);
1458 
1459   bind(SpinLoop);
1460   pause();
1461   decrementl(scr_Reg);
1462   jccb(Assembler::lessEqual, SpinExit);
1463   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1464   testptr(tmp_Reg, tmp_Reg);
1465   jccb(Assembler::notZero, SpinLoop);
1466 
1467   bind(SpinExit);
1468   jmp(retryLabel);
1469   bind(doneRetry);
1470   incrementl(retry_count_Reg); // clear z flag
1471 }
1472 
1473 // Use RTM for normal stack locks
1474 // Input: objReg (object to lock)
1475 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1476                                        Register retry_on_abort_count_Reg,
1477                                        RTMLockingCounters* stack_rtm_counters,
1478                                        Metadata* method_data, bool profile_rtm,
1479                                        Label& DONE_LABEL, Label& IsInflated) {
1480   assert(UseRTMForStackLocks, "why call this otherwise?");
1481   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1482   assert(tmpReg == rax, "");
1483   assert(scrReg == rdx, "");
1484   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1485 
1486   if (RTMRetryCount > 0) {
1487     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1488     bind(L_rtm_retry);
1489   }
1490   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1491   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1492   jcc(Assembler::notZero, IsInflated);
1493 
1494   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1495     Label L_noincrement;
1496     if (RTMTotalCountIncrRate > 1) {
1497       // tmpReg, scrReg and flags are killed
1498       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1499     }
1500     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1501     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1502     bind(L_noincrement);
1503   }
1504   xbegin(L_on_abort);
1505   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1506   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1507   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1508   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1509 
1510   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1511   if (UseRTMXendForLockBusy) {
1512     xend();
1513     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1514     jmp(L_decrement_retry);
1515   }
1516   else {
1517     xabort(0);
1518   }
1519   bind(L_on_abort);
1520   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1521     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1522   }
1523   bind(L_decrement_retry);
1524   if (RTMRetryCount > 0) {
1525     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1526     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1527   }
1528 }
1529 
1530 // Use RTM for inflating locks
1531 // inputs: objReg (object to lock)
1532 //         boxReg (on-stack box address (displaced header location) - KILLED)
1533 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1534 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1535                                           Register scrReg, Register retry_on_busy_count_Reg,
1536                                           Register retry_on_abort_count_Reg,
1537                                           RTMLockingCounters* rtm_counters,
1538                                           Metadata* method_data, bool profile_rtm,
1539                                           Label& DONE_LABEL) {
1540   assert(UseRTMLocking, "why call this otherwise?");
1541   assert(tmpReg == rax, "");
1542   assert(scrReg == rdx, "");
1543   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1544   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1545 
1546   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1547   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1548   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1549 
1550   if (RTMRetryCount > 0) {
1551     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1552     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1553     bind(L_rtm_retry);
1554   }
1555   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1556     Label L_noincrement;
1557     if (RTMTotalCountIncrRate > 1) {
1558       // tmpReg, scrReg and flags are killed
1559       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1560     }
1561     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1562     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1563     bind(L_noincrement);
1564   }
1565   xbegin(L_on_abort);
1566   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1567   movptr(tmpReg, Address(tmpReg, owner_offset));
1568   testptr(tmpReg, tmpReg);
1569   jcc(Assembler::zero, DONE_LABEL);
1570   if (UseRTMXendForLockBusy) {
1571     xend();
1572     jmp(L_decrement_retry);
1573   }
1574   else {
1575     xabort(0);
1576   }
1577   bind(L_on_abort);
1578   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1579   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1580     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1581   }
1582   if (RTMRetryCount > 0) {
1583     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1584     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1585   }
1586 
1587   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1588   testptr(tmpReg, tmpReg) ;
1589   jccb(Assembler::notZero, L_decrement_retry) ;
1590 
1591   // Appears unlocked - try to swing _owner from null to non-null.
1592   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1593 #ifdef _LP64
1594   Register threadReg = r15_thread;
1595 #else
1596   get_thread(scrReg);
1597   Register threadReg = scrReg;
1598 #endif
1599   if (os::is_MP()) {
1600     lock();
1601   }
1602   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1603 
1604   if (RTMRetryCount > 0) {
1605     // success done else retry
1606     jccb(Assembler::equal, DONE_LABEL) ;
1607     bind(L_decrement_retry);
1608     // Spin and retry if lock is busy.
1609     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1610   }
1611   else {
1612     bind(L_decrement_retry);
1613   }
1614 }
1615 
1616 #endif //  INCLUDE_RTM_OPT
1617 
1618 // Fast_Lock and Fast_Unlock used by C2
1619 
1620 // Because the transitions from emitted code to the runtime
1621 // monitorenter/exit helper stubs are so slow it's critical that
1622 // we inline both the stack-locking fast-path and the inflated fast path.
1623 //
1624 // See also: cmpFastLock and cmpFastUnlock.
1625 //
1626 // What follows is a specialized inline transliteration of the code
1627 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1628 // another option would be to emit TrySlowEnter and TrySlowExit methods
1629 // at startup-time.  These methods would accept arguments as
1630 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1631 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1632 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1633 // In practice, however, the # of lock sites is bounded and is usually small.
1634 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1635 // if the processor uses simple bimodal branch predictors keyed by EIP
1636 // Since the helper routines would be called from multiple synchronization
1637 // sites.
1638 //
1639 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1640 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1641 // to those specialized methods.  That'd give us a mostly platform-independent
1642 // implementation that the JITs could optimize and inline at their pleasure.
1643 // Done correctly, the only time we'd need to cross to native could would be
1644 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1645 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1646 // (b) explicit barriers or fence operations.
1647 //
1648 // TODO:
1649 //
1650 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1651 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1652 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1653 //    the lock operators would typically be faster than reifying Self.
1654 //
1655 // *  Ideally I'd define the primitives as:
1656 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1657 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1658 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1659 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1660 //    Furthermore the register assignments are overconstrained, possibly resulting in
1661 //    sub-optimal code near the synchronization site.
1662 //
1663 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1664 //    Alternately, use a better sp-proximity test.
1665 //
1666 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1667 //    Either one is sufficient to uniquely identify a thread.
1668 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1669 //
1670 // *  Intrinsify notify() and notifyAll() for the common cases where the
1671 //    object is locked by the calling thread but the waitlist is empty.
1672 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1673 //
1674 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1675 //    But beware of excessive branch density on AMD Opterons.
1676 //
1677 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1678 //    or failure of the fast-path.  If the fast-path fails then we pass
1679 //    control to the slow-path, typically in C.  In Fast_Lock and
1680 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1681 //    will emit a conditional branch immediately after the node.
1682 //    So we have branches to branches and lots of ICC.ZF games.
1683 //    Instead, it might be better to have C2 pass a "FailureLabel"
1684 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1685 //    will drop through the node.  ICC.ZF is undefined at exit.
1686 //    In the case of failure, the node will branch directly to the
1687 //    FailureLabel
1688 
1689 
1690 // obj: object to lock
1691 // box: on-stack box address (displaced header location) - KILLED
1692 // rax,: tmp -- KILLED
1693 // scr: tmp -- KILLED
1694 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1695                                Register scrReg, Register cx1Reg, Register cx2Reg,
1696                                BiasedLockingCounters* counters,
1697                                RTMLockingCounters* rtm_counters,
1698                                RTMLockingCounters* stack_rtm_counters,
1699                                Metadata* method_data,
1700                                bool use_rtm, bool profile_rtm) {
1701   // Ensure the register assignments are disjoint
1702   assert(tmpReg == rax, "");
1703 
1704   if (use_rtm) {
1705     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1706   } else {
1707     assert(cx1Reg == noreg, "");
1708     assert(cx2Reg == noreg, "");
1709     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1710   }
1711 
1712   if (counters != NULL) {
1713     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1714   }
1715   if (EmitSync & 1) {
1716       // set box->dhw = markOopDesc::unused_mark()
1717       // Force all sync thru slow-path: slow_enter() and slow_exit()
1718       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1719       cmpptr (rsp, (int32_t)NULL_WORD);
1720   } else {
1721     // Possible cases that we'll encounter in fast_lock
1722     // ------------------------------------------------
1723     // * Inflated
1724     //    -- unlocked
1725     //    -- Locked
1726     //       = by self
1727     //       = by other
1728     // * biased
1729     //    -- by Self
1730     //    -- by other
1731     // * neutral
1732     // * stack-locked
1733     //    -- by self
1734     //       = sp-proximity test hits
1735     //       = sp-proximity test generates false-negative
1736     //    -- by other
1737     //
1738 
1739     Label IsInflated, DONE_LABEL;
1740 
1741     // it's stack-locked, biased or neutral
1742     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1743     // order to reduce the number of conditional branches in the most common cases.
1744     // Beware -- there's a subtle invariant that fetch of the markword
1745     // at [FETCH], below, will never observe a biased encoding (*101b).
1746     // If this invariant is not held we risk exclusion (safety) failure.
1747     if (UseBiasedLocking && !UseOptoBiasInlining) {
1748       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1749     }
1750 
1751 #if INCLUDE_RTM_OPT
1752     if (UseRTMForStackLocks && use_rtm) {
1753       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1754                         stack_rtm_counters, method_data, profile_rtm,
1755                         DONE_LABEL, IsInflated);
1756     }
1757 #endif // INCLUDE_RTM_OPT
1758 
1759     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1760     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1761     jccb(Assembler::notZero, IsInflated);
1762 
1763     // Attempt stack-locking ...
1764     orptr (tmpReg, markOopDesc::unlocked_value);
1765     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1766     if (os::is_MP()) {
1767       lock();
1768     }
1769     cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1770     if (counters != NULL) {
1771       cond_inc32(Assembler::equal,
1772                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1773     }
1774     jcc(Assembler::equal, DONE_LABEL);           // Success
1775 
1776     // Recursive locking.
1777     // The object is stack-locked: markword contains stack pointer to BasicLock.
1778     // Locked by current thread if difference with current SP is less than one page.
1779     subptr(tmpReg, rsp);
1780     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1781     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1782     movptr(Address(boxReg, 0), tmpReg);
1783     if (counters != NULL) {
1784       cond_inc32(Assembler::equal,
1785                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1786     }
1787     jmp(DONE_LABEL);
1788 
1789     bind(IsInflated);
1790     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1791 
1792 #if INCLUDE_RTM_OPT
1793     // Use the same RTM locking code in 32- and 64-bit VM.
1794     if (use_rtm) {
1795       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1796                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1797     } else {
1798 #endif // INCLUDE_RTM_OPT
1799 
1800 #ifndef _LP64
1801     // The object is inflated.
1802 
1803     // boxReg refers to the on-stack BasicLock in the current frame.
1804     // We'd like to write:
1805     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1806     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1807     // additional latency as we have another ST in the store buffer that must drain.
1808 
1809     if (EmitSync & 8192) {
1810        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1811        get_thread (scrReg);
1812        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1813        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1814        if (os::is_MP()) {
1815          lock();
1816        }
1817        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1818     } else
1819     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1820        // register juggle because we need tmpReg for cmpxchgptr below
1821        movptr(scrReg, boxReg);
1822        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1823 
1824        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1825        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1826           // prefetchw [eax + Offset(_owner)-2]
1827           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1828        }
1829 
1830        if ((EmitSync & 64) == 0) {
1831          // Optimistic form: consider XORL tmpReg,tmpReg
1832          movptr(tmpReg, NULL_WORD);
1833        } else {
1834          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1835          // Test-And-CAS instead of CAS
1836          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1837          testptr(tmpReg, tmpReg);                   // Locked ?
1838          jccb  (Assembler::notZero, DONE_LABEL);
1839        }
1840 
1841        // Appears unlocked - try to swing _owner from null to non-null.
1842        // Ideally, I'd manifest "Self" with get_thread and then attempt
1843        // to CAS the register containing Self into m->Owner.
1844        // But we don't have enough registers, so instead we can either try to CAS
1845        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1846        // we later store "Self" into m->Owner.  Transiently storing a stack address
1847        // (rsp or the address of the box) into  m->owner is harmless.
1848        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1849        if (os::is_MP()) {
1850          lock();
1851        }
1852        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1853        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1854        // If we weren't able to swing _owner from NULL to the BasicLock
1855        // then take the slow path.
1856        jccb  (Assembler::notZero, DONE_LABEL);
1857        // update _owner from BasicLock to thread
1858        get_thread (scrReg);                    // beware: clobbers ICCs
1859        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1860        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1861 
1862        // If the CAS fails we can either retry or pass control to the slow-path.
1863        // We use the latter tactic.
1864        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1865        // If the CAS was successful ...
1866        //   Self has acquired the lock
1867        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1868        // Intentional fall-through into DONE_LABEL ...
1869     } else {
1870        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1871        movptr(boxReg, tmpReg);
1872 
1873        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1874        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1875           // prefetchw [eax + Offset(_owner)-2]
1876           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1877        }
1878 
1879        if ((EmitSync & 64) == 0) {
1880          // Optimistic form
1881          xorptr  (tmpReg, tmpReg);
1882        } else {
1883          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1884          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1885          testptr(tmpReg, tmpReg);                   // Locked ?
1886          jccb  (Assembler::notZero, DONE_LABEL);
1887        }
1888 
1889        // Appears unlocked - try to swing _owner from null to non-null.
1890        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1891        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1892        get_thread (scrReg);
1893        if (os::is_MP()) {
1894          lock();
1895        }
1896        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1897 
1898        // If the CAS fails we can either retry or pass control to the slow-path.
1899        // We use the latter tactic.
1900        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1901        // If the CAS was successful ...
1902        //   Self has acquired the lock
1903        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1904        // Intentional fall-through into DONE_LABEL ...
1905     }
1906 #else // _LP64
1907     // It's inflated
1908     movq(scrReg, tmpReg);
1909     xorq(tmpReg, tmpReg);
1910 
1911     if (os::is_MP()) {
1912       lock();
1913     }
1914     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1915     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1916     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1917     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1918     // Intentional fall-through into DONE_LABEL ...
1919     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1920 #endif // _LP64
1921 #if INCLUDE_RTM_OPT
1922     } // use_rtm()
1923 #endif
1924     // DONE_LABEL is a hot target - we'd really like to place it at the
1925     // start of cache line by padding with NOPs.
1926     // See the AMD and Intel software optimization manuals for the
1927     // most efficient "long" NOP encodings.
1928     // Unfortunately none of our alignment mechanisms suffice.
1929     bind(DONE_LABEL);
1930 
1931     // At DONE_LABEL the icc ZFlag is set as follows ...
1932     // Fast_Unlock uses the same protocol.
1933     // ZFlag == 1 -> Success
1934     // ZFlag == 0 -> Failure - force control through the slow-path
1935   }
1936 }
1937 
1938 // obj: object to unlock
1939 // box: box address (displaced header location), killed.  Must be EAX.
1940 // tmp: killed, cannot be obj nor box.
1941 //
1942 // Some commentary on balanced locking:
1943 //
1944 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1945 // Methods that don't have provably balanced locking are forced to run in the
1946 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1947 // The interpreter provides two properties:
1948 // I1:  At return-time the interpreter automatically and quietly unlocks any
1949 //      objects acquired the current activation (frame).  Recall that the
1950 //      interpreter maintains an on-stack list of locks currently held by
1951 //      a frame.
1952 // I2:  If a method attempts to unlock an object that is not held by the
1953 //      the frame the interpreter throws IMSX.
1954 //
1955 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1956 // B() doesn't have provably balanced locking so it runs in the interpreter.
1957 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1958 // is still locked by A().
1959 //
1960 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1961 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1962 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1963 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1964 // Arguably given that the spec legislates the JNI case as undefined our implementation
1965 // could reasonably *avoid* checking owner in Fast_Unlock().
1966 // In the interest of performance we elide m->Owner==Self check in unlock.
1967 // A perfectly viable alternative is to elide the owner check except when
1968 // Xcheck:jni is enabled.
1969 
1970 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1971   assert(boxReg == rax, "");
1972   assert_different_registers(objReg, boxReg, tmpReg);
1973 
1974   if (EmitSync & 4) {
1975     // Disable - inhibit all inlining.  Force control through the slow-path
1976     cmpptr (rsp, 0);
1977   } else {
1978     Label DONE_LABEL, Stacked, CheckSucc;
1979 
1980     // Critically, the biased locking test must have precedence over
1981     // and appear before the (box->dhw == 0) recursive stack-lock test.
1982     if (UseBiasedLocking && !UseOptoBiasInlining) {
1983        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1984     }
1985 
1986 #if INCLUDE_RTM_OPT
1987     if (UseRTMForStackLocks && use_rtm) {
1988       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1989       Label L_regular_unlock;
1990       movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
1991       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1992       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1993       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1994       xend();                                       // otherwise end...
1995       jmp(DONE_LABEL);                              // ... and we're done
1996       bind(L_regular_unlock);
1997     }
1998 #endif
1999 
2000     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
2001     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2002     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
2003     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2004     jccb  (Assembler::zero, Stacked);
2005 
2006     // It's inflated.
2007 #if INCLUDE_RTM_OPT
2008     if (use_rtm) {
2009       Label L_regular_inflated_unlock;
2010       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2011       movptr(boxReg, Address(tmpReg, owner_offset));
2012       testptr(boxReg, boxReg);
2013       jccb(Assembler::notZero, L_regular_inflated_unlock);
2014       xend();
2015       jmpb(DONE_LABEL);
2016       bind(L_regular_inflated_unlock);
2017     }
2018 #endif
2019 
2020     // Despite our balanced locking property we still check that m->_owner == Self
2021     // as java routines or native JNI code called by this thread might
2022     // have released the lock.
2023     // Refer to the comments in synchronizer.cpp for how we might encode extra
2024     // state in _succ so we can avoid fetching EntryList|cxq.
2025     //
2026     // I'd like to add more cases in fast_lock() and fast_unlock() --
2027     // such as recursive enter and exit -- but we have to be wary of
2028     // I$ bloat, T$ effects and BP$ effects.
2029     //
2030     // If there's no contention try a 1-0 exit.  That is, exit without
2031     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2032     // we detect and recover from the race that the 1-0 exit admits.
2033     //
2034     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2035     // before it STs null into _owner, releasing the lock.  Updates
2036     // to data protected by the critical section must be visible before
2037     // we drop the lock (and thus before any other thread could acquire
2038     // the lock and observe the fields protected by the lock).
2039     // IA32's memory-model is SPO, so STs are ordered with respect to
2040     // each other and there's no need for an explicit barrier (fence).
2041     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2042 #ifndef _LP64
2043     get_thread (boxReg);
2044     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2045       // prefetchw [ebx + Offset(_owner)-2]
2046       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2047     }
2048 
2049     // Note that we could employ various encoding schemes to reduce
2050     // the number of loads below (currently 4) to just 2 or 3.
2051     // Refer to the comments in synchronizer.cpp.
2052     // In practice the chain of fetches doesn't seem to impact performance, however.
2053     xorptr(boxReg, boxReg);
2054     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2055        // Attempt to reduce branch density - AMD's branch predictor.
2056        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2057        orptr(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, DONE_LABEL);
2060        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2061        jmpb  (DONE_LABEL);
2062     } else {
2063        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2064        jccb  (Assembler::notZero, DONE_LABEL);
2065        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2066        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2067        jccb  (Assembler::notZero, CheckSucc);
2068        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2069        jmpb  (DONE_LABEL);
2070     }
2071 
2072     // The Following code fragment (EmitSync & 65536) improves the performance of
2073     // contended applications and contended synchronization microbenchmarks.
2074     // Unfortunately the emission of the code - even though not executed - causes regressions
2075     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2076     // with an equal number of never-executed NOPs results in the same regression.
2077     // We leave it off by default.
2078 
2079     if ((EmitSync & 65536) != 0) {
2080        Label LSuccess, LGoSlowPath ;
2081 
2082        bind  (CheckSucc);
2083 
2084        // Optional pre-test ... it's safe to elide this
2085        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2086        jccb(Assembler::zero, LGoSlowPath);
2087 
2088        // We have a classic Dekker-style idiom:
2089        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2090        // There are a number of ways to implement the barrier:
2091        // (1) lock:andl &m->_owner, 0
2092        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2093        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2094        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2095        // (2) If supported, an explicit MFENCE is appealing.
2096        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2097        //     particularly if the write-buffer is full as might be the case if
2098        //     if stores closely precede the fence or fence-equivalent instruction.
2099        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2100        //     as the situation has changed with Nehalem and Shanghai.
2101        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2102        //     The $lines underlying the top-of-stack should be in M-state.
2103        //     The locked add instruction is serializing, of course.
2104        // (4) Use xchg, which is serializing
2105        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2106        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2107        //     The integer condition codes will tell us if succ was 0.
2108        //     Since _succ and _owner should reside in the same $line and
2109        //     we just stored into _owner, it's likely that the $line
2110        //     remains in M-state for the lock:orl.
2111        //
2112        // We currently use (3), although it's likely that switching to (2)
2113        // is correct for the future.
2114 
2115        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2116        if (os::is_MP()) {
2117          lock(); addptr(Address(rsp, 0), 0);
2118        }
2119        // Ratify _succ remains non-null
2120        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2121        jccb  (Assembler::notZero, LSuccess);
2122 
2123        xorptr(boxReg, boxReg);                  // box is really EAX
2124        if (os::is_MP()) { lock(); }
2125        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2126        // There's no successor so we tried to regrab the lock with the
2127        // placeholder value. If that didn't work, then another thread
2128        // grabbed the lock so we're done (and exit was a success).
2129        jccb  (Assembler::notEqual, LSuccess);
2130        // Since we're low on registers we installed rsp as a placeholding in _owner.
2131        // Now install Self over rsp.  This is safe as we're transitioning from
2132        // non-null to non=null
2133        get_thread (boxReg);
2134        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2135        // Intentional fall-through into LGoSlowPath ...
2136 
2137        bind  (LGoSlowPath);
2138        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2139        jmpb  (DONE_LABEL);
2140 
2141        bind  (LSuccess);
2142        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2143        jmpb  (DONE_LABEL);
2144     }
2145 
2146     bind (Stacked);
2147     // It's not inflated and it's not recursively stack-locked and it's not biased.
2148     // It must be stack-locked.
2149     // Try to reset the header to displaced header.
2150     // The "box" value on the stack is stable, so we can reload
2151     // and be assured we observe the same value as above.
2152     movptr(tmpReg, Address(boxReg, 0));
2153     if (os::is_MP()) {
2154       lock();
2155     }
2156     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2157     // Intention fall-thru into DONE_LABEL
2158 
2159     // DONE_LABEL is a hot target - we'd really like to place it at the
2160     // start of cache line by padding with NOPs.
2161     // See the AMD and Intel software optimization manuals for the
2162     // most efficient "long" NOP encodings.
2163     // Unfortunately none of our alignment mechanisms suffice.
2164     if ((EmitSync & 65536) == 0) {
2165        bind (CheckSucc);
2166     }
2167 #else // _LP64
2168     // It's inflated
2169     if (EmitSync & 1024) {
2170       // Emit code to check that _owner == Self
2171       // We could fold the _owner test into subsequent code more efficiently
2172       // than using a stand-alone check, but since _owner checking is off by
2173       // default we don't bother. We also might consider predicating the
2174       // _owner==Self check on Xcheck:jni or running on a debug build.
2175       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2176       xorptr(boxReg, r15_thread);
2177     } else {
2178       xorptr(boxReg, boxReg);
2179     }
2180     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2181     jccb  (Assembler::notZero, DONE_LABEL);
2182     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2183     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2184     jccb  (Assembler::notZero, CheckSucc);
2185     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2186     jmpb  (DONE_LABEL);
2187 
2188     if ((EmitSync & 65536) == 0) {
2189       // Try to avoid passing control into the slow_path ...
2190       Label LSuccess, LGoSlowPath ;
2191       bind  (CheckSucc);
2192 
2193       // The following optional optimization can be elided if necessary
2194       // Effectively: if (succ == null) goto SlowPath
2195       // The code reduces the window for a race, however,
2196       // and thus benefits performance.
2197       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2198       jccb  (Assembler::zero, LGoSlowPath);
2199 
2200       xorptr(boxReg, boxReg);
2201       if ((EmitSync & 16) && os::is_MP()) {
2202         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2203       } else {
2204         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2205         if (os::is_MP()) {
2206           // Memory barrier/fence
2207           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2208           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2209           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2210           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2211           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2212           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2213           lock(); addl(Address(rsp, 0), 0);
2214         }
2215       }
2216       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2217       jccb  (Assembler::notZero, LSuccess);
2218 
2219       // Rare inopportune interleaving - race.
2220       // The successor vanished in the small window above.
2221       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2222       // We need to ensure progress and succession.
2223       // Try to reacquire the lock.
2224       // If that fails then the new owner is responsible for succession and this
2225       // thread needs to take no further action and can exit via the fast path (success).
2226       // If the re-acquire succeeds then pass control into the slow path.
2227       // As implemented, this latter mode is horrible because we generated more
2228       // coherence traffic on the lock *and* artifically extended the critical section
2229       // length while by virtue of passing control into the slow path.
2230 
2231       // box is really RAX -- the following CMPXCHG depends on that binding
2232       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2233       if (os::is_MP()) { lock(); }
2234       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2235       // There's no successor so we tried to regrab the lock.
2236       // If that didn't work, then another thread grabbed the
2237       // lock so we're done (and exit was a success).
2238       jccb  (Assembler::notEqual, LSuccess);
2239       // Intentional fall-through into slow-path
2240 
2241       bind  (LGoSlowPath);
2242       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2243       jmpb  (DONE_LABEL);
2244 
2245       bind  (LSuccess);
2246       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2247       jmpb  (DONE_LABEL);
2248     }
2249 
2250     bind  (Stacked);
2251     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2252     if (os::is_MP()) { lock(); }
2253     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2254 
2255     if (EmitSync & 65536) {
2256        bind (CheckSucc);
2257     }
2258 #endif
2259     bind(DONE_LABEL);
2260   }
2261 }
2262 #endif // COMPILER2
2263 
2264 void MacroAssembler::c2bool(Register x) {
2265   // implements x == 0 ? 0 : 1
2266   // note: must only look at least-significant byte of x
2267   //       since C-style booleans are stored in one byte
2268   //       only! (was bug)
2269   andl(x, 0xFF);
2270   setb(Assembler::notZero, x);
2271 }
2272 
2273 // Wouldn't need if AddressLiteral version had new name
2274 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2275   Assembler::call(L, rtype);
2276 }
2277 
2278 void MacroAssembler::call(Register entry) {
2279   Assembler::call(entry);
2280 }
2281 
2282 void MacroAssembler::call(AddressLiteral entry) {
2283   if (reachable(entry)) {
2284     Assembler::call_literal(entry.target(), entry.rspec());
2285   } else {
2286     lea(rscratch1, entry);
2287     Assembler::call(rscratch1);
2288   }
2289 }
2290 
2291 void MacroAssembler::ic_call(address entry, jint method_index) {
2292   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2293   movptr(rax, (intptr_t)Universe::non_oop_word());
2294   call(AddressLiteral(entry, rh));
2295 }
2296 
2297 // Implementation of call_VM versions
2298 
2299 void MacroAssembler::call_VM(Register oop_result,
2300                              address entry_point,
2301                              bool check_exceptions) {
2302   Label C, E;
2303   call(C, relocInfo::none);
2304   jmp(E);
2305 
2306   bind(C);
2307   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2308   ret(0);
2309 
2310   bind(E);
2311 }
2312 
2313 void MacroAssembler::call_VM(Register oop_result,
2314                              address entry_point,
2315                              Register arg_1,
2316                              bool check_exceptions) {
2317   Label C, E;
2318   call(C, relocInfo::none);
2319   jmp(E);
2320 
2321   bind(C);
2322   pass_arg1(this, arg_1);
2323   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2324   ret(0);
2325 
2326   bind(E);
2327 }
2328 
2329 void MacroAssembler::call_VM(Register oop_result,
2330                              address entry_point,
2331                              Register arg_1,
2332                              Register arg_2,
2333                              bool check_exceptions) {
2334   Label C, E;
2335   call(C, relocInfo::none);
2336   jmp(E);
2337 
2338   bind(C);
2339 
2340   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2341 
2342   pass_arg2(this, arg_2);
2343   pass_arg1(this, arg_1);
2344   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2345   ret(0);
2346 
2347   bind(E);
2348 }
2349 
2350 void MacroAssembler::call_VM(Register oop_result,
2351                              address entry_point,
2352                              Register arg_1,
2353                              Register arg_2,
2354                              Register arg_3,
2355                              bool check_exceptions) {
2356   Label C, E;
2357   call(C, relocInfo::none);
2358   jmp(E);
2359 
2360   bind(C);
2361 
2362   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2363   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2364   pass_arg3(this, arg_3);
2365 
2366   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2367   pass_arg2(this, arg_2);
2368 
2369   pass_arg1(this, arg_1);
2370   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2371   ret(0);
2372 
2373   bind(E);
2374 }
2375 
2376 void MacroAssembler::call_VM(Register oop_result,
2377                              Register last_java_sp,
2378                              address entry_point,
2379                              int number_of_arguments,
2380                              bool check_exceptions) {
2381   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2382   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2383 }
2384 
2385 void MacroAssembler::call_VM(Register oop_result,
2386                              Register last_java_sp,
2387                              address entry_point,
2388                              Register arg_1,
2389                              bool check_exceptions) {
2390   pass_arg1(this, arg_1);
2391   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2392 }
2393 
2394 void MacroAssembler::call_VM(Register oop_result,
2395                              Register last_java_sp,
2396                              address entry_point,
2397                              Register arg_1,
2398                              Register arg_2,
2399                              bool check_exceptions) {
2400 
2401   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2402   pass_arg2(this, arg_2);
2403   pass_arg1(this, arg_1);
2404   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2405 }
2406 
2407 void MacroAssembler::call_VM(Register oop_result,
2408                              Register last_java_sp,
2409                              address entry_point,
2410                              Register arg_1,
2411                              Register arg_2,
2412                              Register arg_3,
2413                              bool check_exceptions) {
2414   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2415   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2416   pass_arg3(this, arg_3);
2417   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2418   pass_arg2(this, arg_2);
2419   pass_arg1(this, arg_1);
2420   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2421 }
2422 
2423 void MacroAssembler::super_call_VM(Register oop_result,
2424                                    Register last_java_sp,
2425                                    address entry_point,
2426                                    int number_of_arguments,
2427                                    bool check_exceptions) {
2428   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2429   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2430 }
2431 
2432 void MacroAssembler::super_call_VM(Register oop_result,
2433                                    Register last_java_sp,
2434                                    address entry_point,
2435                                    Register arg_1,
2436                                    bool check_exceptions) {
2437   pass_arg1(this, arg_1);
2438   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2439 }
2440 
2441 void MacroAssembler::super_call_VM(Register oop_result,
2442                                    Register last_java_sp,
2443                                    address entry_point,
2444                                    Register arg_1,
2445                                    Register arg_2,
2446                                    bool check_exceptions) {
2447 
2448   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2449   pass_arg2(this, arg_2);
2450   pass_arg1(this, arg_1);
2451   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2452 }
2453 
2454 void MacroAssembler::super_call_VM(Register oop_result,
2455                                    Register last_java_sp,
2456                                    address entry_point,
2457                                    Register arg_1,
2458                                    Register arg_2,
2459                                    Register arg_3,
2460                                    bool check_exceptions) {
2461   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2462   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2463   pass_arg3(this, arg_3);
2464   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2465   pass_arg2(this, arg_2);
2466   pass_arg1(this, arg_1);
2467   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2468 }
2469 
2470 void MacroAssembler::call_VM_base(Register oop_result,
2471                                   Register java_thread,
2472                                   Register last_java_sp,
2473                                   address  entry_point,
2474                                   int      number_of_arguments,
2475                                   bool     check_exceptions) {
2476   // determine java_thread register
2477   if (!java_thread->is_valid()) {
2478 #ifdef _LP64
2479     java_thread = r15_thread;
2480 #else
2481     java_thread = rdi;
2482     get_thread(java_thread);
2483 #endif // LP64
2484   }
2485   // determine last_java_sp register
2486   if (!last_java_sp->is_valid()) {
2487     last_java_sp = rsp;
2488   }
2489   // debugging support
2490   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2491   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2492 #ifdef ASSERT
2493   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2494   // r12 is the heapbase.
2495   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2496 #endif // ASSERT
2497 
2498   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2499   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2500 
2501   // push java thread (becomes first argument of C function)
2502 
2503   NOT_LP64(push(java_thread); number_of_arguments++);
2504   LP64_ONLY(mov(c_rarg0, r15_thread));
2505 
2506   // set last Java frame before call
2507   assert(last_java_sp != rbp, "can't use ebp/rbp");
2508 
2509   // Only interpreter should have to set fp
2510   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2511 
2512   // do the call, remove parameters
2513   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2514 
2515   // restore the thread (cannot use the pushed argument since arguments
2516   // may be overwritten by C code generated by an optimizing compiler);
2517   // however can use the register value directly if it is callee saved.
2518   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2519     // rdi & rsi (also r15) are callee saved -> nothing to do
2520 #ifdef ASSERT
2521     guarantee(java_thread != rax, "change this code");
2522     push(rax);
2523     { Label L;
2524       get_thread(rax);
2525       cmpptr(java_thread, rax);
2526       jcc(Assembler::equal, L);
2527       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2528       bind(L);
2529     }
2530     pop(rax);
2531 #endif
2532   } else {
2533     get_thread(java_thread);
2534   }
2535   // reset last Java frame
2536   // Only interpreter should have to clear fp
2537   reset_last_Java_frame(java_thread, true);
2538 
2539    // C++ interp handles this in the interpreter
2540   check_and_handle_popframe(java_thread);
2541   check_and_handle_earlyret(java_thread);
2542 
2543   if (check_exceptions) {
2544     // check for pending exceptions (java_thread is set upon return)
2545     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2546 #ifndef _LP64
2547     jump_cc(Assembler::notEqual,
2548             RuntimeAddress(StubRoutines::forward_exception_entry()));
2549 #else
2550     // This used to conditionally jump to forward_exception however it is
2551     // possible if we relocate that the branch will not reach. So we must jump
2552     // around so we can always reach
2553 
2554     Label ok;
2555     jcc(Assembler::equal, ok);
2556     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2557     bind(ok);
2558 #endif // LP64
2559   }
2560 
2561   // get oop result if there is one and reset the value in the thread
2562   if (oop_result->is_valid()) {
2563     get_vm_result(oop_result, java_thread);
2564   }
2565 }
2566 
2567 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2568 
2569   // Calculate the value for last_Java_sp
2570   // somewhat subtle. call_VM does an intermediate call
2571   // which places a return address on the stack just under the
2572   // stack pointer as the user finsihed with it. This allows
2573   // use to retrieve last_Java_pc from last_Java_sp[-1].
2574   // On 32bit we then have to push additional args on the stack to accomplish
2575   // the actual requested call. On 64bit call_VM only can use register args
2576   // so the only extra space is the return address that call_VM created.
2577   // This hopefully explains the calculations here.
2578 
2579 #ifdef _LP64
2580   // We've pushed one address, correct last_Java_sp
2581   lea(rax, Address(rsp, wordSize));
2582 #else
2583   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2584 #endif // LP64
2585 
2586   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2587 
2588 }
2589 
2590 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2591 void MacroAssembler::call_VM_leaf0(address entry_point) {
2592   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2593 }
2594 
2595 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2596   call_VM_leaf_base(entry_point, number_of_arguments);
2597 }
2598 
2599 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2600   pass_arg0(this, arg_0);
2601   call_VM_leaf(entry_point, 1);
2602 }
2603 
2604 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2605 
2606   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2607   pass_arg1(this, arg_1);
2608   pass_arg0(this, arg_0);
2609   call_VM_leaf(entry_point, 2);
2610 }
2611 
2612 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2613   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2614   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2615   pass_arg2(this, arg_2);
2616   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2617   pass_arg1(this, arg_1);
2618   pass_arg0(this, arg_0);
2619   call_VM_leaf(entry_point, 3);
2620 }
2621 
2622 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2623   pass_arg0(this, arg_0);
2624   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2625 }
2626 
2627 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2628 
2629   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2630   pass_arg1(this, arg_1);
2631   pass_arg0(this, arg_0);
2632   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2633 }
2634 
2635 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2636   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2637   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2638   pass_arg2(this, arg_2);
2639   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2640   pass_arg1(this, arg_1);
2641   pass_arg0(this, arg_0);
2642   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2643 }
2644 
2645 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2646   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2647   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2648   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2649   pass_arg3(this, arg_3);
2650   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2651   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2652   pass_arg2(this, arg_2);
2653   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2654   pass_arg1(this, arg_1);
2655   pass_arg0(this, arg_0);
2656   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2657 }
2658 
2659 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2660   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2661   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2662   verify_oop(oop_result, "broken oop in call_VM_base");
2663 }
2664 
2665 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2666   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2667   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2668 }
2669 
2670 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2671 }
2672 
2673 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2674 }
2675 
2676 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2677   if (reachable(src1)) {
2678     cmpl(as_Address(src1), imm);
2679   } else {
2680     lea(rscratch1, src1);
2681     cmpl(Address(rscratch1, 0), imm);
2682   }
2683 }
2684 
2685 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2686   assert(!src2.is_lval(), "use cmpptr");
2687   if (reachable(src2)) {
2688     cmpl(src1, as_Address(src2));
2689   } else {
2690     lea(rscratch1, src2);
2691     cmpl(src1, Address(rscratch1, 0));
2692   }
2693 }
2694 
2695 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2696   Assembler::cmpl(src1, imm);
2697 }
2698 
2699 void MacroAssembler::cmp32(Register src1, Address src2) {
2700   Assembler::cmpl(src1, src2);
2701 }
2702 
2703 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2704   ucomisd(opr1, opr2);
2705 
2706   Label L;
2707   if (unordered_is_less) {
2708     movl(dst, -1);
2709     jcc(Assembler::parity, L);
2710     jcc(Assembler::below , L);
2711     movl(dst, 0);
2712     jcc(Assembler::equal , L);
2713     increment(dst);
2714   } else { // unordered is greater
2715     movl(dst, 1);
2716     jcc(Assembler::parity, L);
2717     jcc(Assembler::above , L);
2718     movl(dst, 0);
2719     jcc(Assembler::equal , L);
2720     decrementl(dst);
2721   }
2722   bind(L);
2723 }
2724 
2725 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2726   ucomiss(opr1, opr2);
2727 
2728   Label L;
2729   if (unordered_is_less) {
2730     movl(dst, -1);
2731     jcc(Assembler::parity, L);
2732     jcc(Assembler::below , L);
2733     movl(dst, 0);
2734     jcc(Assembler::equal , L);
2735     increment(dst);
2736   } else { // unordered is greater
2737     movl(dst, 1);
2738     jcc(Assembler::parity, L);
2739     jcc(Assembler::above , L);
2740     movl(dst, 0);
2741     jcc(Assembler::equal , L);
2742     decrementl(dst);
2743   }
2744   bind(L);
2745 }
2746 
2747 
2748 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2749   if (reachable(src1)) {
2750     cmpb(as_Address(src1), imm);
2751   } else {
2752     lea(rscratch1, src1);
2753     cmpb(Address(rscratch1, 0), imm);
2754   }
2755 }
2756 
2757 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2758 #ifdef _LP64
2759   if (src2.is_lval()) {
2760     movptr(rscratch1, src2);
2761     Assembler::cmpq(src1, rscratch1);
2762   } else if (reachable(src2)) {
2763     cmpq(src1, as_Address(src2));
2764   } else {
2765     lea(rscratch1, src2);
2766     Assembler::cmpq(src1, Address(rscratch1, 0));
2767   }
2768 #else
2769   if (src2.is_lval()) {
2770     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2771   } else {
2772     cmpl(src1, as_Address(src2));
2773   }
2774 #endif // _LP64
2775 }
2776 
2777 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2778   assert(src2.is_lval(), "not a mem-mem compare");
2779 #ifdef _LP64
2780   // moves src2's literal address
2781   movptr(rscratch1, src2);
2782   Assembler::cmpq(src1, rscratch1);
2783 #else
2784   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2785 #endif // _LP64
2786 }
2787 
2788 void MacroAssembler::cmpoop(Register src1, Register src2) {
2789   cmpptr(src1, src2);
2790 }
2791 
2792 void MacroAssembler::cmpoop(Register src1, Address src2) {
2793   cmpptr(src1, src2);
2794 }
2795 
2796 #ifdef _LP64
2797 void MacroAssembler::cmpoop(Register src1, jobject src2) {
2798   movoop(rscratch1, src2);
2799   cmpptr(src1, rscratch1);
2800 }
2801 #endif
2802 
2803 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2804   if (reachable(adr)) {
2805     if (os::is_MP())
2806       lock();
2807     cmpxchgptr(reg, as_Address(adr));
2808   } else {
2809     lea(rscratch1, adr);
2810     if (os::is_MP())
2811       lock();
2812     cmpxchgptr(reg, Address(rscratch1, 0));
2813   }
2814 }
2815 
2816 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2817   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2818 }
2819 
2820 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2821   if (reachable(src)) {
2822     Assembler::comisd(dst, as_Address(src));
2823   } else {
2824     lea(rscratch1, src);
2825     Assembler::comisd(dst, Address(rscratch1, 0));
2826   }
2827 }
2828 
2829 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2830   if (reachable(src)) {
2831     Assembler::comiss(dst, as_Address(src));
2832   } else {
2833     lea(rscratch1, src);
2834     Assembler::comiss(dst, Address(rscratch1, 0));
2835   }
2836 }
2837 
2838 
2839 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2840   Condition negated_cond = negate_condition(cond);
2841   Label L;
2842   jcc(negated_cond, L);
2843   pushf(); // Preserve flags
2844   atomic_incl(counter_addr);
2845   popf();
2846   bind(L);
2847 }
2848 
2849 int MacroAssembler::corrected_idivl(Register reg) {
2850   // Full implementation of Java idiv and irem; checks for
2851   // special case as described in JVM spec., p.243 & p.271.
2852   // The function returns the (pc) offset of the idivl
2853   // instruction - may be needed for implicit exceptions.
2854   //
2855   //         normal case                           special case
2856   //
2857   // input : rax,: dividend                         min_int
2858   //         reg: divisor   (may not be rax,/rdx)   -1
2859   //
2860   // output: rax,: quotient  (= rax, idiv reg)       min_int
2861   //         rdx: remainder (= rax, irem reg)       0
2862   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2863   const int min_int = 0x80000000;
2864   Label normal_case, special_case;
2865 
2866   // check for special case
2867   cmpl(rax, min_int);
2868   jcc(Assembler::notEqual, normal_case);
2869   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2870   cmpl(reg, -1);
2871   jcc(Assembler::equal, special_case);
2872 
2873   // handle normal case
2874   bind(normal_case);
2875   cdql();
2876   int idivl_offset = offset();
2877   idivl(reg);
2878 
2879   // normal and special case exit
2880   bind(special_case);
2881 
2882   return idivl_offset;
2883 }
2884 
2885 
2886 
2887 void MacroAssembler::decrementl(Register reg, int value) {
2888   if (value == min_jint) {subl(reg, value) ; return; }
2889   if (value <  0) { incrementl(reg, -value); return; }
2890   if (value == 0) {                        ; return; }
2891   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2892   /* else */      { subl(reg, value)       ; return; }
2893 }
2894 
2895 void MacroAssembler::decrementl(Address dst, int value) {
2896   if (value == min_jint) {subl(dst, value) ; return; }
2897   if (value <  0) { incrementl(dst, -value); return; }
2898   if (value == 0) {                        ; return; }
2899   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2900   /* else */      { subl(dst, value)       ; return; }
2901 }
2902 
2903 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2904   assert (shift_value > 0, "illegal shift value");
2905   Label _is_positive;
2906   testl (reg, reg);
2907   jcc (Assembler::positive, _is_positive);
2908   int offset = (1 << shift_value) - 1 ;
2909 
2910   if (offset == 1) {
2911     incrementl(reg);
2912   } else {
2913     addl(reg, offset);
2914   }
2915 
2916   bind (_is_positive);
2917   sarl(reg, shift_value);
2918 }
2919 
2920 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2921   if (reachable(src)) {
2922     Assembler::divsd(dst, as_Address(src));
2923   } else {
2924     lea(rscratch1, src);
2925     Assembler::divsd(dst, Address(rscratch1, 0));
2926   }
2927 }
2928 
2929 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2930   if (reachable(src)) {
2931     Assembler::divss(dst, as_Address(src));
2932   } else {
2933     lea(rscratch1, src);
2934     Assembler::divss(dst, Address(rscratch1, 0));
2935   }
2936 }
2937 
2938 // !defined(COMPILER2) is because of stupid core builds
2939 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2940 void MacroAssembler::empty_FPU_stack() {
2941   if (VM_Version::supports_mmx()) {
2942     emms();
2943   } else {
2944     for (int i = 8; i-- > 0; ) ffree(i);
2945   }
2946 }
2947 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2948 
2949 
2950 // Defines obj, preserves var_size_in_bytes
2951 void MacroAssembler::eden_allocate(Register obj,
2952                                    Register var_size_in_bytes,
2953                                    int con_size_in_bytes,
2954                                    Register t1,
2955                                    Label& slow_case) {
2956   assert(obj == rax, "obj must be in rax, for cmpxchg");
2957   assert_different_registers(obj, var_size_in_bytes, t1);
2958   if (!Universe::heap()->supports_inline_contig_alloc()) {
2959     jmp(slow_case);
2960   } else {
2961     Register end = t1;
2962     Label retry;
2963     bind(retry);
2964     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2965     movptr(obj, heap_top);
2966     if (var_size_in_bytes == noreg) {
2967       lea(end, Address(obj, con_size_in_bytes));
2968     } else {
2969       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2970     }
2971     // if end < obj then we wrapped around => object too long => slow case
2972     cmpptr(end, obj);
2973     jcc(Assembler::below, slow_case);
2974     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2975     jcc(Assembler::above, slow_case);
2976     // Compare obj with the top addr, and if still equal, store the new top addr in
2977     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2978     // it otherwise. Use lock prefix for atomicity on MPs.
2979     locked_cmpxchgptr(end, heap_top);
2980     jcc(Assembler::notEqual, retry);
2981   }
2982 }
2983 
2984 void MacroAssembler::enter() {
2985   push(rbp);
2986   mov(rbp, rsp);
2987 }
2988 
2989 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2990 void MacroAssembler::fat_nop() {
2991   if (UseAddressNop) {
2992     addr_nop_5();
2993   } else {
2994     emit_int8(0x26); // es:
2995     emit_int8(0x2e); // cs:
2996     emit_int8(0x64); // fs:
2997     emit_int8(0x65); // gs:
2998     emit_int8((unsigned char)0x90);
2999   }
3000 }
3001 
3002 void MacroAssembler::fcmp(Register tmp) {
3003   fcmp(tmp, 1, true, true);
3004 }
3005 
3006 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
3007   assert(!pop_right || pop_left, "usage error");
3008   if (VM_Version::supports_cmov()) {
3009     assert(tmp == noreg, "unneeded temp");
3010     if (pop_left) {
3011       fucomip(index);
3012     } else {
3013       fucomi(index);
3014     }
3015     if (pop_right) {
3016       fpop();
3017     }
3018   } else {
3019     assert(tmp != noreg, "need temp");
3020     if (pop_left) {
3021       if (pop_right) {
3022         fcompp();
3023       } else {
3024         fcomp(index);
3025       }
3026     } else {
3027       fcom(index);
3028     }
3029     // convert FPU condition into eflags condition via rax,
3030     save_rax(tmp);
3031     fwait(); fnstsw_ax();
3032     sahf();
3033     restore_rax(tmp);
3034   }
3035   // condition codes set as follows:
3036   //
3037   // CF (corresponds to C0) if x < y
3038   // PF (corresponds to C2) if unordered
3039   // ZF (corresponds to C3) if x = y
3040 }
3041 
3042 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3043   fcmp2int(dst, unordered_is_less, 1, true, true);
3044 }
3045 
3046 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3047   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3048   Label L;
3049   if (unordered_is_less) {
3050     movl(dst, -1);
3051     jcc(Assembler::parity, L);
3052     jcc(Assembler::below , L);
3053     movl(dst, 0);
3054     jcc(Assembler::equal , L);
3055     increment(dst);
3056   } else { // unordered is greater
3057     movl(dst, 1);
3058     jcc(Assembler::parity, L);
3059     jcc(Assembler::above , L);
3060     movl(dst, 0);
3061     jcc(Assembler::equal , L);
3062     decrementl(dst);
3063   }
3064   bind(L);
3065 }
3066 
3067 void MacroAssembler::fld_d(AddressLiteral src) {
3068   fld_d(as_Address(src));
3069 }
3070 
3071 void MacroAssembler::fld_s(AddressLiteral src) {
3072   fld_s(as_Address(src));
3073 }
3074 
3075 void MacroAssembler::fld_x(AddressLiteral src) {
3076   Assembler::fld_x(as_Address(src));
3077 }
3078 
3079 void MacroAssembler::fldcw(AddressLiteral src) {
3080   Assembler::fldcw(as_Address(src));
3081 }
3082 
3083 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3084   if (reachable(src)) {
3085     Assembler::mulpd(dst, as_Address(src));
3086   } else {
3087     lea(rscratch1, src);
3088     Assembler::mulpd(dst, Address(rscratch1, 0));
3089   }
3090 }
3091 
3092 void MacroAssembler::increase_precision() {
3093   subptr(rsp, BytesPerWord);
3094   fnstcw(Address(rsp, 0));
3095   movl(rax, Address(rsp, 0));
3096   orl(rax, 0x300);
3097   push(rax);
3098   fldcw(Address(rsp, 0));
3099   pop(rax);
3100 }
3101 
3102 void MacroAssembler::restore_precision() {
3103   fldcw(Address(rsp, 0));
3104   addptr(rsp, BytesPerWord);
3105 }
3106 
3107 void MacroAssembler::fpop() {
3108   ffree();
3109   fincstp();
3110 }
3111 
3112 void MacroAssembler::load_float(Address src) {
3113   if (UseSSE >= 1) {
3114     movflt(xmm0, src);
3115   } else {
3116     LP64_ONLY(ShouldNotReachHere());
3117     NOT_LP64(fld_s(src));
3118   }
3119 }
3120 
3121 void MacroAssembler::store_float(Address dst) {
3122   if (UseSSE >= 1) {
3123     movflt(dst, xmm0);
3124   } else {
3125     LP64_ONLY(ShouldNotReachHere());
3126     NOT_LP64(fstp_s(dst));
3127   }
3128 }
3129 
3130 void MacroAssembler::load_double(Address src) {
3131   if (UseSSE >= 2) {
3132     movdbl(xmm0, src);
3133   } else {
3134     LP64_ONLY(ShouldNotReachHere());
3135     NOT_LP64(fld_d(src));
3136   }
3137 }
3138 
3139 void MacroAssembler::store_double(Address dst) {
3140   if (UseSSE >= 2) {
3141     movdbl(dst, xmm0);
3142   } else {
3143     LP64_ONLY(ShouldNotReachHere());
3144     NOT_LP64(fstp_d(dst));
3145   }
3146 }
3147 
3148 void MacroAssembler::fremr(Register tmp) {
3149   save_rax(tmp);
3150   { Label L;
3151     bind(L);
3152     fprem();
3153     fwait(); fnstsw_ax();
3154 #ifdef _LP64
3155     testl(rax, 0x400);
3156     jcc(Assembler::notEqual, L);
3157 #else
3158     sahf();
3159     jcc(Assembler::parity, L);
3160 #endif // _LP64
3161   }
3162   restore_rax(tmp);
3163   // Result is in ST0.
3164   // Note: fxch & fpop to get rid of ST1
3165   // (otherwise FPU stack could overflow eventually)
3166   fxch(1);
3167   fpop();
3168 }
3169 
3170 // dst = c = a * b + c
3171 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3172   Assembler::vfmadd231sd(c, a, b);
3173   if (dst != c) {
3174     movdbl(dst, c);
3175   }
3176 }
3177 
3178 // dst = c = a * b + c
3179 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3180   Assembler::vfmadd231ss(c, a, b);
3181   if (dst != c) {
3182     movflt(dst, c);
3183   }
3184 }
3185 
3186 // dst = c = a * b + c
3187 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3188   Assembler::vfmadd231pd(c, a, b, vector_len);
3189   if (dst != c) {
3190     vmovdqu(dst, c);
3191   }
3192 }
3193 
3194 // dst = c = a * b + c
3195 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3196   Assembler::vfmadd231ps(c, a, b, vector_len);
3197   if (dst != c) {
3198     vmovdqu(dst, c);
3199   }
3200 }
3201 
3202 // dst = c = a * b + c
3203 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3204   Assembler::vfmadd231pd(c, a, b, vector_len);
3205   if (dst != c) {
3206     vmovdqu(dst, c);
3207   }
3208 }
3209 
3210 // dst = c = a * b + c
3211 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3212   Assembler::vfmadd231ps(c, a, b, vector_len);
3213   if (dst != c) {
3214     vmovdqu(dst, c);
3215   }
3216 }
3217 
3218 void MacroAssembler::incrementl(AddressLiteral dst) {
3219   if (reachable(dst)) {
3220     incrementl(as_Address(dst));
3221   } else {
3222     lea(rscratch1, dst);
3223     incrementl(Address(rscratch1, 0));
3224   }
3225 }
3226 
3227 void MacroAssembler::incrementl(ArrayAddress dst) {
3228   incrementl(as_Address(dst));
3229 }
3230 
3231 void MacroAssembler::incrementl(Register reg, int value) {
3232   if (value == min_jint) {addl(reg, value) ; return; }
3233   if (value <  0) { decrementl(reg, -value); return; }
3234   if (value == 0) {                        ; return; }
3235   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3236   /* else */      { addl(reg, value)       ; return; }
3237 }
3238 
3239 void MacroAssembler::incrementl(Address dst, int value) {
3240   if (value == min_jint) {addl(dst, value) ; return; }
3241   if (value <  0) { decrementl(dst, -value); return; }
3242   if (value == 0) {                        ; return; }
3243   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3244   /* else */      { addl(dst, value)       ; return; }
3245 }
3246 
3247 void MacroAssembler::jump(AddressLiteral dst) {
3248   if (reachable(dst)) {
3249     jmp_literal(dst.target(), dst.rspec());
3250   } else {
3251     lea(rscratch1, dst);
3252     jmp(rscratch1);
3253   }
3254 }
3255 
3256 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3257   if (reachable(dst)) {
3258     InstructionMark im(this);
3259     relocate(dst.reloc());
3260     const int short_size = 2;
3261     const int long_size = 6;
3262     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3263     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3264       // 0111 tttn #8-bit disp
3265       emit_int8(0x70 | cc);
3266       emit_int8((offs - short_size) & 0xFF);
3267     } else {
3268       // 0000 1111 1000 tttn #32-bit disp
3269       emit_int8(0x0F);
3270       emit_int8((unsigned char)(0x80 | cc));
3271       emit_int32(offs - long_size);
3272     }
3273   } else {
3274 #ifdef ASSERT
3275     warning("reversing conditional branch");
3276 #endif /* ASSERT */
3277     Label skip;
3278     jccb(reverse[cc], skip);
3279     lea(rscratch1, dst);
3280     Assembler::jmp(rscratch1);
3281     bind(skip);
3282   }
3283 }
3284 
3285 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3286   if (reachable(src)) {
3287     Assembler::ldmxcsr(as_Address(src));
3288   } else {
3289     lea(rscratch1, src);
3290     Assembler::ldmxcsr(Address(rscratch1, 0));
3291   }
3292 }
3293 
3294 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3295   int off;
3296   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3297     off = offset();
3298     movsbl(dst, src); // movsxb
3299   } else {
3300     off = load_unsigned_byte(dst, src);
3301     shll(dst, 24);
3302     sarl(dst, 24);
3303   }
3304   return off;
3305 }
3306 
3307 // Note: load_signed_short used to be called load_signed_word.
3308 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3309 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3310 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3311 int MacroAssembler::load_signed_short(Register dst, Address src) {
3312   int off;
3313   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3314     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3315     // version but this is what 64bit has always done. This seems to imply
3316     // that users are only using 32bits worth.
3317     off = offset();
3318     movswl(dst, src); // movsxw
3319   } else {
3320     off = load_unsigned_short(dst, src);
3321     shll(dst, 16);
3322     sarl(dst, 16);
3323   }
3324   return off;
3325 }
3326 
3327 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3328   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3329   // and "3.9 Partial Register Penalties", p. 22).
3330   int off;
3331   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3332     off = offset();
3333     movzbl(dst, src); // movzxb
3334   } else {
3335     xorl(dst, dst);
3336     off = offset();
3337     movb(dst, src);
3338   }
3339   return off;
3340 }
3341 
3342 // Note: load_unsigned_short used to be called load_unsigned_word.
3343 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3344   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3345   // and "3.9 Partial Register Penalties", p. 22).
3346   int off;
3347   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3348     off = offset();
3349     movzwl(dst, src); // movzxw
3350   } else {
3351     xorl(dst, dst);
3352     off = offset();
3353     movw(dst, src);
3354   }
3355   return off;
3356 }
3357 
3358 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3359   switch (size_in_bytes) {
3360 #ifndef _LP64
3361   case  8:
3362     assert(dst2 != noreg, "second dest register required");
3363     movl(dst,  src);
3364     movl(dst2, src.plus_disp(BytesPerInt));
3365     break;
3366 #else
3367   case  8:  movq(dst, src); break;
3368 #endif
3369   case  4:  movl(dst, src); break;
3370   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3371   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3372   default:  ShouldNotReachHere();
3373   }
3374 }
3375 
3376 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3377   switch (size_in_bytes) {
3378 #ifndef _LP64
3379   case  8:
3380     assert(src2 != noreg, "second source register required");
3381     movl(dst,                        src);
3382     movl(dst.plus_disp(BytesPerInt), src2);
3383     break;
3384 #else
3385   case  8:  movq(dst, src); break;
3386 #endif
3387   case  4:  movl(dst, src); break;
3388   case  2:  movw(dst, src); break;
3389   case  1:  movb(dst, src); break;
3390   default:  ShouldNotReachHere();
3391   }
3392 }
3393 
3394 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3395   if (reachable(dst)) {
3396     movl(as_Address(dst), src);
3397   } else {
3398     lea(rscratch1, dst);
3399     movl(Address(rscratch1, 0), src);
3400   }
3401 }
3402 
3403 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3404   if (reachable(src)) {
3405     movl(dst, as_Address(src));
3406   } else {
3407     lea(rscratch1, src);
3408     movl(dst, Address(rscratch1, 0));
3409   }
3410 }
3411 
3412 // C++ bool manipulation
3413 
3414 void MacroAssembler::movbool(Register dst, Address src) {
3415   if(sizeof(bool) == 1)
3416     movb(dst, src);
3417   else if(sizeof(bool) == 2)
3418     movw(dst, src);
3419   else if(sizeof(bool) == 4)
3420     movl(dst, src);
3421   else
3422     // unsupported
3423     ShouldNotReachHere();
3424 }
3425 
3426 void MacroAssembler::movbool(Address dst, bool boolconst) {
3427   if(sizeof(bool) == 1)
3428     movb(dst, (int) boolconst);
3429   else if(sizeof(bool) == 2)
3430     movw(dst, (int) boolconst);
3431   else if(sizeof(bool) == 4)
3432     movl(dst, (int) boolconst);
3433   else
3434     // unsupported
3435     ShouldNotReachHere();
3436 }
3437 
3438 void MacroAssembler::movbool(Address dst, Register src) {
3439   if(sizeof(bool) == 1)
3440     movb(dst, src);
3441   else if(sizeof(bool) == 2)
3442     movw(dst, src);
3443   else if(sizeof(bool) == 4)
3444     movl(dst, src);
3445   else
3446     // unsupported
3447     ShouldNotReachHere();
3448 }
3449 
3450 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3451   movb(as_Address(dst), src);
3452 }
3453 
3454 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3455   if (reachable(src)) {
3456     movdl(dst, as_Address(src));
3457   } else {
3458     lea(rscratch1, src);
3459     movdl(dst, Address(rscratch1, 0));
3460   }
3461 }
3462 
3463 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3464   if (reachable(src)) {
3465     movq(dst, as_Address(src));
3466   } else {
3467     lea(rscratch1, src);
3468     movq(dst, Address(rscratch1, 0));
3469   }
3470 }
3471 
3472 void MacroAssembler::setvectmask(Register dst, Register src) {
3473   Assembler::movl(dst, 1);
3474   Assembler::shlxl(dst, dst, src);
3475   Assembler::decl(dst);
3476   Assembler::kmovdl(k1, dst);
3477   Assembler::movl(dst, src);
3478 }
3479 
3480 void MacroAssembler::restorevectmask() {
3481   Assembler::knotwl(k1, k0);
3482 }
3483 
3484 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3485   if (reachable(src)) {
3486     if (UseXmmLoadAndClearUpper) {
3487       movsd (dst, as_Address(src));
3488     } else {
3489       movlpd(dst, as_Address(src));
3490     }
3491   } else {
3492     lea(rscratch1, src);
3493     if (UseXmmLoadAndClearUpper) {
3494       movsd (dst, Address(rscratch1, 0));
3495     } else {
3496       movlpd(dst, Address(rscratch1, 0));
3497     }
3498   }
3499 }
3500 
3501 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3502   if (reachable(src)) {
3503     movss(dst, as_Address(src));
3504   } else {
3505     lea(rscratch1, src);
3506     movss(dst, Address(rscratch1, 0));
3507   }
3508 }
3509 
3510 void MacroAssembler::movptr(Register dst, Register src) {
3511   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3512 }
3513 
3514 void MacroAssembler::movptr(Register dst, Address src) {
3515   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3516 }
3517 
3518 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3519 void MacroAssembler::movptr(Register dst, intptr_t src) {
3520   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3521 }
3522 
3523 void MacroAssembler::movptr(Address dst, Register src) {
3524   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3525 }
3526 
3527 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3528   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3529     Assembler::vextractf32x4(dst, src, 0);
3530   } else {
3531     Assembler::movdqu(dst, src);
3532   }
3533 }
3534 
3535 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3536   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3537     Assembler::vinsertf32x4(dst, dst, src, 0);
3538   } else {
3539     Assembler::movdqu(dst, src);
3540   }
3541 }
3542 
3543 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3544   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3545     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3546   } else {
3547     Assembler::movdqu(dst, src);
3548   }
3549 }
3550 
3551 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3552   if (reachable(src)) {
3553     movdqu(dst, as_Address(src));
3554   } else {
3555     lea(scratchReg, src);
3556     movdqu(dst, Address(scratchReg, 0));
3557   }
3558 }
3559 
3560 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3561   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3562     vextractf64x4_low(dst, src);
3563   } else {
3564     Assembler::vmovdqu(dst, src);
3565   }
3566 }
3567 
3568 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3569   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3570     vinsertf64x4_low(dst, src);
3571   } else {
3572     Assembler::vmovdqu(dst, src);
3573   }
3574 }
3575 
3576 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3577   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3578     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3579   }
3580   else {
3581     Assembler::vmovdqu(dst, src);
3582   }
3583 }
3584 
3585 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3586   if (reachable(src)) {
3587     vmovdqu(dst, as_Address(src));
3588   }
3589   else {
3590     lea(rscratch1, src);
3591     vmovdqu(dst, Address(rscratch1, 0));
3592   }
3593 }
3594 
3595 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3596   if (reachable(src)) {
3597     Assembler::movdqa(dst, as_Address(src));
3598   } else {
3599     lea(rscratch1, src);
3600     Assembler::movdqa(dst, Address(rscratch1, 0));
3601   }
3602 }
3603 
3604 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3605   if (reachable(src)) {
3606     Assembler::movsd(dst, as_Address(src));
3607   } else {
3608     lea(rscratch1, src);
3609     Assembler::movsd(dst, Address(rscratch1, 0));
3610   }
3611 }
3612 
3613 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3614   if (reachable(src)) {
3615     Assembler::movss(dst, as_Address(src));
3616   } else {
3617     lea(rscratch1, src);
3618     Assembler::movss(dst, Address(rscratch1, 0));
3619   }
3620 }
3621 
3622 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3623   if (reachable(src)) {
3624     Assembler::mulsd(dst, as_Address(src));
3625   } else {
3626     lea(rscratch1, src);
3627     Assembler::mulsd(dst, Address(rscratch1, 0));
3628   }
3629 }
3630 
3631 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3632   if (reachable(src)) {
3633     Assembler::mulss(dst, as_Address(src));
3634   } else {
3635     lea(rscratch1, src);
3636     Assembler::mulss(dst, Address(rscratch1, 0));
3637   }
3638 }
3639 
3640 void MacroAssembler::null_check(Register reg, int offset) {
3641   if (needs_explicit_null_check(offset)) {
3642     // provoke OS NULL exception if reg = NULL by
3643     // accessing M[reg] w/o changing any (non-CC) registers
3644     // NOTE: cmpl is plenty here to provoke a segv
3645     cmpptr(rax, Address(reg, 0));
3646     // Note: should probably use testl(rax, Address(reg, 0));
3647     //       may be shorter code (however, this version of
3648     //       testl needs to be implemented first)
3649   } else {
3650     // nothing to do, (later) access of M[reg + offset]
3651     // will provoke OS NULL exception if reg = NULL
3652   }
3653 }
3654 
3655 void MacroAssembler::os_breakpoint() {
3656   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3657   // (e.g., MSVC can't call ps() otherwise)
3658   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3659 }
3660 
3661 void MacroAssembler::unimplemented(const char* what) {
3662   char* b = new char[1024];
3663   jio_snprintf(b, 1024, "unimplemented: %s", what);
3664   stop(b);
3665 }
3666 
3667 #ifdef _LP64
3668 #define XSTATE_BV 0x200
3669 #endif
3670 
3671 void MacroAssembler::pop_CPU_state() {
3672   pop_FPU_state();
3673   pop_IU_state();
3674 }
3675 
3676 void MacroAssembler::pop_FPU_state() {
3677 #ifndef _LP64
3678   frstor(Address(rsp, 0));
3679 #else
3680   fxrstor(Address(rsp, 0));
3681 #endif
3682   addptr(rsp, FPUStateSizeInWords * wordSize);
3683 }
3684 
3685 void MacroAssembler::pop_IU_state() {
3686   popa();
3687   LP64_ONLY(addq(rsp, 8));
3688   popf();
3689 }
3690 
3691 // Save Integer and Float state
3692 // Warning: Stack must be 16 byte aligned (64bit)
3693 void MacroAssembler::push_CPU_state() {
3694   push_IU_state();
3695   push_FPU_state();
3696 }
3697 
3698 void MacroAssembler::push_FPU_state() {
3699   subptr(rsp, FPUStateSizeInWords * wordSize);
3700 #ifndef _LP64
3701   fnsave(Address(rsp, 0));
3702   fwait();
3703 #else
3704   fxsave(Address(rsp, 0));
3705 #endif // LP64
3706 }
3707 
3708 void MacroAssembler::push_IU_state() {
3709   // Push flags first because pusha kills them
3710   pushf();
3711   // Make sure rsp stays 16-byte aligned
3712   LP64_ONLY(subq(rsp, 8));
3713   pusha();
3714 }
3715 
3716 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3717   if (!java_thread->is_valid()) {
3718     java_thread = rdi;
3719     get_thread(java_thread);
3720   }
3721   // we must set sp to zero to clear frame
3722   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3723   if (clear_fp) {
3724     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3725   }
3726 
3727   // Always clear the pc because it could have been set by make_walkable()
3728   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3729 
3730   vzeroupper();
3731 }
3732 
3733 void MacroAssembler::restore_rax(Register tmp) {
3734   if (tmp == noreg) pop(rax);
3735   else if (tmp != rax) mov(rax, tmp);
3736 }
3737 
3738 void MacroAssembler::round_to(Register reg, int modulus) {
3739   addptr(reg, modulus - 1);
3740   andptr(reg, -modulus);
3741 }
3742 
3743 void MacroAssembler::save_rax(Register tmp) {
3744   if (tmp == noreg) push(rax);
3745   else if (tmp != rax) mov(tmp, rax);
3746 }
3747 
3748 // Write serialization page so VM thread can do a pseudo remote membar.
3749 // We use the current thread pointer to calculate a thread specific
3750 // offset to write to within the page. This minimizes bus traffic
3751 // due to cache line collision.
3752 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3753   movl(tmp, thread);
3754   shrl(tmp, os::get_serialize_page_shift_count());
3755   andl(tmp, (os::vm_page_size() - sizeof(int)));
3756 
3757   Address index(noreg, tmp, Address::times_1);
3758   ExternalAddress page(os::get_memory_serialize_page());
3759 
3760   // Size of store must match masking code above
3761   movl(as_Address(ArrayAddress(page, index)), tmp);
3762 }
3763 
3764 #ifdef _LP64
3765 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, Register temp_reg) {
3766   if (SafepointMechanism::uses_thread_local_poll()) {
3767     testb(Address(r15_thread, Thread::polling_page_offset()), SafepointMechanism::poll_bit());
3768     jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
3769   } else {
3770     cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3771         SafepointSynchronize::_not_synchronized);
3772     jcc(Assembler::notEqual, slow_path);
3773   }
3774 }
3775 #else
3776 void MacroAssembler::safepoint_poll(Label& slow_path) {
3777   cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3778       SafepointSynchronize::_not_synchronized);
3779   jcc(Assembler::notEqual, slow_path);
3780 }
3781 #endif
3782 
3783 // Calls to C land
3784 //
3785 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3786 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3787 // has to be reset to 0. This is required to allow proper stack traversal.
3788 void MacroAssembler::set_last_Java_frame(Register java_thread,
3789                                          Register last_java_sp,
3790                                          Register last_java_fp,
3791                                          address  last_java_pc) {
3792   vzeroupper();
3793   // determine java_thread register
3794   if (!java_thread->is_valid()) {
3795     java_thread = rdi;
3796     get_thread(java_thread);
3797   }
3798   // determine last_java_sp register
3799   if (!last_java_sp->is_valid()) {
3800     last_java_sp = rsp;
3801   }
3802 
3803   // last_java_fp is optional
3804 
3805   if (last_java_fp->is_valid()) {
3806     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3807   }
3808 
3809   // last_java_pc is optional
3810 
3811   if (last_java_pc != NULL) {
3812     lea(Address(java_thread,
3813                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3814         InternalAddress(last_java_pc));
3815 
3816   }
3817   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3818 }
3819 
3820 void MacroAssembler::shlptr(Register dst, int imm8) {
3821   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3822 }
3823 
3824 void MacroAssembler::shrptr(Register dst, int imm8) {
3825   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3826 }
3827 
3828 void MacroAssembler::sign_extend_byte(Register reg) {
3829   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3830     movsbl(reg, reg); // movsxb
3831   } else {
3832     shll(reg, 24);
3833     sarl(reg, 24);
3834   }
3835 }
3836 
3837 void MacroAssembler::sign_extend_short(Register reg) {
3838   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3839     movswl(reg, reg); // movsxw
3840   } else {
3841     shll(reg, 16);
3842     sarl(reg, 16);
3843   }
3844 }
3845 
3846 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3847   assert(reachable(src), "Address should be reachable");
3848   testl(dst, as_Address(src));
3849 }
3850 
3851 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3852   int dst_enc = dst->encoding();
3853   int src_enc = src->encoding();
3854   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3855     Assembler::pcmpeqb(dst, src);
3856   } else if ((dst_enc < 16) && (src_enc < 16)) {
3857     Assembler::pcmpeqb(dst, src);
3858   } else if (src_enc < 16) {
3859     subptr(rsp, 64);
3860     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3861     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3862     Assembler::pcmpeqb(xmm0, src);
3863     movdqu(dst, xmm0);
3864     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3865     addptr(rsp, 64);
3866   } else if (dst_enc < 16) {
3867     subptr(rsp, 64);
3868     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3869     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3870     Assembler::pcmpeqb(dst, xmm0);
3871     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3872     addptr(rsp, 64);
3873   } else {
3874     subptr(rsp, 64);
3875     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3876     subptr(rsp, 64);
3877     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3878     movdqu(xmm0, src);
3879     movdqu(xmm1, dst);
3880     Assembler::pcmpeqb(xmm1, xmm0);
3881     movdqu(dst, xmm1);
3882     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3883     addptr(rsp, 64);
3884     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3885     addptr(rsp, 64);
3886   }
3887 }
3888 
3889 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3890   int dst_enc = dst->encoding();
3891   int src_enc = src->encoding();
3892   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3893     Assembler::pcmpeqw(dst, src);
3894   } else if ((dst_enc < 16) && (src_enc < 16)) {
3895     Assembler::pcmpeqw(dst, src);
3896   } else if (src_enc < 16) {
3897     subptr(rsp, 64);
3898     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3899     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3900     Assembler::pcmpeqw(xmm0, src);
3901     movdqu(dst, xmm0);
3902     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3903     addptr(rsp, 64);
3904   } else if (dst_enc < 16) {
3905     subptr(rsp, 64);
3906     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3907     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3908     Assembler::pcmpeqw(dst, xmm0);
3909     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3910     addptr(rsp, 64);
3911   } else {
3912     subptr(rsp, 64);
3913     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3914     subptr(rsp, 64);
3915     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3916     movdqu(xmm0, src);
3917     movdqu(xmm1, dst);
3918     Assembler::pcmpeqw(xmm1, xmm0);
3919     movdqu(dst, xmm1);
3920     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3921     addptr(rsp, 64);
3922     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3923     addptr(rsp, 64);
3924   }
3925 }
3926 
3927 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3928   int dst_enc = dst->encoding();
3929   if (dst_enc < 16) {
3930     Assembler::pcmpestri(dst, src, imm8);
3931   } else {
3932     subptr(rsp, 64);
3933     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3934     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3935     Assembler::pcmpestri(xmm0, src, imm8);
3936     movdqu(dst, xmm0);
3937     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3938     addptr(rsp, 64);
3939   }
3940 }
3941 
3942 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3943   int dst_enc = dst->encoding();
3944   int src_enc = src->encoding();
3945   if ((dst_enc < 16) && (src_enc < 16)) {
3946     Assembler::pcmpestri(dst, src, imm8);
3947   } else if (src_enc < 16) {
3948     subptr(rsp, 64);
3949     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3950     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3951     Assembler::pcmpestri(xmm0, src, imm8);
3952     movdqu(dst, xmm0);
3953     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3954     addptr(rsp, 64);
3955   } else if (dst_enc < 16) {
3956     subptr(rsp, 64);
3957     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3958     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3959     Assembler::pcmpestri(dst, xmm0, imm8);
3960     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3961     addptr(rsp, 64);
3962   } else {
3963     subptr(rsp, 64);
3964     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3965     subptr(rsp, 64);
3966     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3967     movdqu(xmm0, src);
3968     movdqu(xmm1, dst);
3969     Assembler::pcmpestri(xmm1, xmm0, imm8);
3970     movdqu(dst, xmm1);
3971     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3972     addptr(rsp, 64);
3973     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3974     addptr(rsp, 64);
3975   }
3976 }
3977 
3978 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3979   int dst_enc = dst->encoding();
3980   int src_enc = src->encoding();
3981   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3982     Assembler::pmovzxbw(dst, src);
3983   } else if ((dst_enc < 16) && (src_enc < 16)) {
3984     Assembler::pmovzxbw(dst, src);
3985   } else if (src_enc < 16) {
3986     subptr(rsp, 64);
3987     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3988     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3989     Assembler::pmovzxbw(xmm0, src);
3990     movdqu(dst, xmm0);
3991     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3992     addptr(rsp, 64);
3993   } else if (dst_enc < 16) {
3994     subptr(rsp, 64);
3995     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3996     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3997     Assembler::pmovzxbw(dst, xmm0);
3998     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3999     addptr(rsp, 64);
4000   } else {
4001     subptr(rsp, 64);
4002     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4003     subptr(rsp, 64);
4004     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4005     movdqu(xmm0, src);
4006     movdqu(xmm1, dst);
4007     Assembler::pmovzxbw(xmm1, xmm0);
4008     movdqu(dst, xmm1);
4009     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4010     addptr(rsp, 64);
4011     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4012     addptr(rsp, 64);
4013   }
4014 }
4015 
4016 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4017   int dst_enc = dst->encoding();
4018   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4019     Assembler::pmovzxbw(dst, src);
4020   } else if (dst_enc < 16) {
4021     Assembler::pmovzxbw(dst, src);
4022   } else {
4023     subptr(rsp, 64);
4024     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4025     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4026     Assembler::pmovzxbw(xmm0, src);
4027     movdqu(dst, xmm0);
4028     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4029     addptr(rsp, 64);
4030   }
4031 }
4032 
4033 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4034   int src_enc = src->encoding();
4035   if (src_enc < 16) {
4036     Assembler::pmovmskb(dst, src);
4037   } else {
4038     subptr(rsp, 64);
4039     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4040     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4041     Assembler::pmovmskb(dst, xmm0);
4042     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4043     addptr(rsp, 64);
4044   }
4045 }
4046 
4047 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4048   int dst_enc = dst->encoding();
4049   int src_enc = src->encoding();
4050   if ((dst_enc < 16) && (src_enc < 16)) {
4051     Assembler::ptest(dst, src);
4052   } else if (src_enc < 16) {
4053     subptr(rsp, 64);
4054     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4055     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4056     Assembler::ptest(xmm0, src);
4057     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4058     addptr(rsp, 64);
4059   } else if (dst_enc < 16) {
4060     subptr(rsp, 64);
4061     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4062     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4063     Assembler::ptest(dst, xmm0);
4064     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4065     addptr(rsp, 64);
4066   } else {
4067     subptr(rsp, 64);
4068     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4069     subptr(rsp, 64);
4070     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4071     movdqu(xmm0, src);
4072     movdqu(xmm1, dst);
4073     Assembler::ptest(xmm1, xmm0);
4074     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4075     addptr(rsp, 64);
4076     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4077     addptr(rsp, 64);
4078   }
4079 }
4080 
4081 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4082   if (reachable(src)) {
4083     Assembler::sqrtsd(dst, as_Address(src));
4084   } else {
4085     lea(rscratch1, src);
4086     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4087   }
4088 }
4089 
4090 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4091   if (reachable(src)) {
4092     Assembler::sqrtss(dst, as_Address(src));
4093   } else {
4094     lea(rscratch1, src);
4095     Assembler::sqrtss(dst, Address(rscratch1, 0));
4096   }
4097 }
4098 
4099 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4100   if (reachable(src)) {
4101     Assembler::subsd(dst, as_Address(src));
4102   } else {
4103     lea(rscratch1, src);
4104     Assembler::subsd(dst, Address(rscratch1, 0));
4105   }
4106 }
4107 
4108 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4109   if (reachable(src)) {
4110     Assembler::subss(dst, as_Address(src));
4111   } else {
4112     lea(rscratch1, src);
4113     Assembler::subss(dst, Address(rscratch1, 0));
4114   }
4115 }
4116 
4117 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4118   if (reachable(src)) {
4119     Assembler::ucomisd(dst, as_Address(src));
4120   } else {
4121     lea(rscratch1, src);
4122     Assembler::ucomisd(dst, Address(rscratch1, 0));
4123   }
4124 }
4125 
4126 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4127   if (reachable(src)) {
4128     Assembler::ucomiss(dst, as_Address(src));
4129   } else {
4130     lea(rscratch1, src);
4131     Assembler::ucomiss(dst, Address(rscratch1, 0));
4132   }
4133 }
4134 
4135 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4136   // Used in sign-bit flipping with aligned address.
4137   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4138   if (reachable(src)) {
4139     Assembler::xorpd(dst, as_Address(src));
4140   } else {
4141     lea(rscratch1, src);
4142     Assembler::xorpd(dst, Address(rscratch1, 0));
4143   }
4144 }
4145 
4146 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4147   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4148     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4149   }
4150   else {
4151     Assembler::xorpd(dst, src);
4152   }
4153 }
4154 
4155 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4156   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4157     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4158   } else {
4159     Assembler::xorps(dst, src);
4160   }
4161 }
4162 
4163 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4164   // Used in sign-bit flipping with aligned address.
4165   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4166   if (reachable(src)) {
4167     Assembler::xorps(dst, as_Address(src));
4168   } else {
4169     lea(rscratch1, src);
4170     Assembler::xorps(dst, Address(rscratch1, 0));
4171   }
4172 }
4173 
4174 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4175   // Used in sign-bit flipping with aligned address.
4176   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4177   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4178   if (reachable(src)) {
4179     Assembler::pshufb(dst, as_Address(src));
4180   } else {
4181     lea(rscratch1, src);
4182     Assembler::pshufb(dst, Address(rscratch1, 0));
4183   }
4184 }
4185 
4186 // AVX 3-operands instructions
4187 
4188 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4189   if (reachable(src)) {
4190     vaddsd(dst, nds, as_Address(src));
4191   } else {
4192     lea(rscratch1, src);
4193     vaddsd(dst, nds, Address(rscratch1, 0));
4194   }
4195 }
4196 
4197 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4198   if (reachable(src)) {
4199     vaddss(dst, nds, as_Address(src));
4200   } else {
4201     lea(rscratch1, src);
4202     vaddss(dst, nds, Address(rscratch1, 0));
4203   }
4204 }
4205 
4206 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4207   int dst_enc = dst->encoding();
4208   int nds_enc = nds->encoding();
4209   int src_enc = src->encoding();
4210   if ((dst_enc < 16) && (nds_enc < 16)) {
4211     vandps(dst, nds, negate_field, vector_len);
4212   } else if ((src_enc < 16) && (dst_enc < 16)) {
4213     evmovdqul(src, nds, Assembler::AVX_512bit);
4214     vandps(dst, src, negate_field, vector_len);
4215   } else if (src_enc < 16) {
4216     evmovdqul(src, nds, Assembler::AVX_512bit);
4217     vandps(src, src, negate_field, vector_len);
4218     evmovdqul(dst, src, Assembler::AVX_512bit);
4219   } else if (dst_enc < 16) {
4220     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4221     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4222     vandps(dst, xmm0, negate_field, vector_len);
4223     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4224   } else {
4225     if (src_enc != dst_enc) {
4226       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4227       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4228       vandps(xmm0, xmm0, negate_field, vector_len);
4229       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4230       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4231     } else {
4232       subptr(rsp, 64);
4233       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4234       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4235       vandps(xmm0, xmm0, negate_field, vector_len);
4236       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4237       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4238       addptr(rsp, 64);
4239     }
4240   }
4241 }
4242 
4243 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4244   int dst_enc = dst->encoding();
4245   int nds_enc = nds->encoding();
4246   int src_enc = src->encoding();
4247   if ((dst_enc < 16) && (nds_enc < 16)) {
4248     vandpd(dst, nds, negate_field, vector_len);
4249   } else if ((src_enc < 16) && (dst_enc < 16)) {
4250     evmovdqul(src, nds, Assembler::AVX_512bit);
4251     vandpd(dst, src, negate_field, vector_len);
4252   } else if (src_enc < 16) {
4253     evmovdqul(src, nds, Assembler::AVX_512bit);
4254     vandpd(src, src, negate_field, vector_len);
4255     evmovdqul(dst, src, Assembler::AVX_512bit);
4256   } else if (dst_enc < 16) {
4257     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4258     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4259     vandpd(dst, xmm0, negate_field, vector_len);
4260     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4261   } else {
4262     if (src_enc != dst_enc) {
4263       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4264       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4265       vandpd(xmm0, xmm0, negate_field, vector_len);
4266       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4267       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4268     } else {
4269       subptr(rsp, 64);
4270       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4271       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4272       vandpd(xmm0, xmm0, negate_field, vector_len);
4273       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4274       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4275       addptr(rsp, 64);
4276     }
4277   }
4278 }
4279 
4280 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4281   int dst_enc = dst->encoding();
4282   int nds_enc = nds->encoding();
4283   int src_enc = src->encoding();
4284   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4285     Assembler::vpaddb(dst, nds, src, vector_len);
4286   } else if ((dst_enc < 16) && (src_enc < 16)) {
4287     Assembler::vpaddb(dst, dst, src, vector_len);
4288   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4289     // use nds as scratch for src
4290     evmovdqul(nds, src, Assembler::AVX_512bit);
4291     Assembler::vpaddb(dst, dst, nds, vector_len);
4292   } else if ((src_enc < 16) && (nds_enc < 16)) {
4293     // use nds as scratch for dst
4294     evmovdqul(nds, dst, Assembler::AVX_512bit);
4295     Assembler::vpaddb(nds, nds, src, vector_len);
4296     evmovdqul(dst, nds, Assembler::AVX_512bit);
4297   } else if (dst_enc < 16) {
4298     // use nds as scatch for xmm0 to hold src
4299     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4300     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4301     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4302     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4303   } else {
4304     // worse case scenario, all regs are in the upper bank
4305     subptr(rsp, 64);
4306     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4307     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4308     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4309     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4310     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4311     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4312     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4313     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4314     addptr(rsp, 64);
4315   }
4316 }
4317 
4318 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4319   int dst_enc = dst->encoding();
4320   int nds_enc = nds->encoding();
4321   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4322     Assembler::vpaddb(dst, nds, src, vector_len);
4323   } else if (dst_enc < 16) {
4324     Assembler::vpaddb(dst, dst, src, vector_len);
4325   } else if (nds_enc < 16) {
4326     // implies dst_enc in upper bank with src as scratch
4327     evmovdqul(nds, dst, Assembler::AVX_512bit);
4328     Assembler::vpaddb(nds, nds, src, vector_len);
4329     evmovdqul(dst, nds, Assembler::AVX_512bit);
4330   } else {
4331     // worse case scenario, all regs in upper bank
4332     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4333     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4334     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4335     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4336   }
4337 }
4338 
4339 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4340   int dst_enc = dst->encoding();
4341   int nds_enc = nds->encoding();
4342   int src_enc = src->encoding();
4343   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4344     Assembler::vpaddw(dst, nds, src, vector_len);
4345   } else if ((dst_enc < 16) && (src_enc < 16)) {
4346     Assembler::vpaddw(dst, dst, src, vector_len);
4347   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4348     // use nds as scratch for src
4349     evmovdqul(nds, src, Assembler::AVX_512bit);
4350     Assembler::vpaddw(dst, dst, nds, vector_len);
4351   } else if ((src_enc < 16) && (nds_enc < 16)) {
4352     // use nds as scratch for dst
4353     evmovdqul(nds, dst, Assembler::AVX_512bit);
4354     Assembler::vpaddw(nds, nds, src, vector_len);
4355     evmovdqul(dst, nds, Assembler::AVX_512bit);
4356   } else if (dst_enc < 16) {
4357     // use nds as scatch for xmm0 to hold src
4358     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4359     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4360     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4361     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4362   } else {
4363     // worse case scenario, all regs are in the upper bank
4364     subptr(rsp, 64);
4365     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4366     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4367     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4368     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4369     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4370     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4371     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4372     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4373     addptr(rsp, 64);
4374   }
4375 }
4376 
4377 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4378   int dst_enc = dst->encoding();
4379   int nds_enc = nds->encoding();
4380   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4381     Assembler::vpaddw(dst, nds, src, vector_len);
4382   } else if (dst_enc < 16) {
4383     Assembler::vpaddw(dst, dst, src, vector_len);
4384   } else if (nds_enc < 16) {
4385     // implies dst_enc in upper bank with src as scratch
4386     evmovdqul(nds, dst, Assembler::AVX_512bit);
4387     Assembler::vpaddw(nds, nds, src, vector_len);
4388     evmovdqul(dst, nds, Assembler::AVX_512bit);
4389   } else {
4390     // worse case scenario, all regs in upper bank
4391     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4392     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4393     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4394     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4395   }
4396 }
4397 
4398 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4399   if (reachable(src)) {
4400     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4401   } else {
4402     lea(rscratch1, src);
4403     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4404   }
4405 }
4406 
4407 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4408   int dst_enc = dst->encoding();
4409   int src_enc = src->encoding();
4410   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4411     Assembler::vpbroadcastw(dst, src);
4412   } else if ((dst_enc < 16) && (src_enc < 16)) {
4413     Assembler::vpbroadcastw(dst, src);
4414   } else if (src_enc < 16) {
4415     subptr(rsp, 64);
4416     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4417     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4418     Assembler::vpbroadcastw(xmm0, src);
4419     movdqu(dst, xmm0);
4420     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4421     addptr(rsp, 64);
4422   } else if (dst_enc < 16) {
4423     subptr(rsp, 64);
4424     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4425     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4426     Assembler::vpbroadcastw(dst, xmm0);
4427     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4428     addptr(rsp, 64);
4429   } else {
4430     subptr(rsp, 64);
4431     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4432     subptr(rsp, 64);
4433     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4434     movdqu(xmm0, src);
4435     movdqu(xmm1, dst);
4436     Assembler::vpbroadcastw(xmm1, xmm0);
4437     movdqu(dst, xmm1);
4438     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4439     addptr(rsp, 64);
4440     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4441     addptr(rsp, 64);
4442   }
4443 }
4444 
4445 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4446   int dst_enc = dst->encoding();
4447   int nds_enc = nds->encoding();
4448   int src_enc = src->encoding();
4449   assert(dst_enc == nds_enc, "");
4450   if ((dst_enc < 16) && (src_enc < 16)) {
4451     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4452   } else if (src_enc < 16) {
4453     subptr(rsp, 64);
4454     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4455     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4456     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4457     movdqu(dst, xmm0);
4458     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4459     addptr(rsp, 64);
4460   } else if (dst_enc < 16) {
4461     subptr(rsp, 64);
4462     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4463     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4464     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4465     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4466     addptr(rsp, 64);
4467   } else {
4468     subptr(rsp, 64);
4469     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4470     subptr(rsp, 64);
4471     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4472     movdqu(xmm0, src);
4473     movdqu(xmm1, dst);
4474     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4475     movdqu(dst, xmm1);
4476     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4477     addptr(rsp, 64);
4478     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4479     addptr(rsp, 64);
4480   }
4481 }
4482 
4483 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4484   int dst_enc = dst->encoding();
4485   int nds_enc = nds->encoding();
4486   int src_enc = src->encoding();
4487   assert(dst_enc == nds_enc, "");
4488   if ((dst_enc < 16) && (src_enc < 16)) {
4489     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4490   } else if (src_enc < 16) {
4491     subptr(rsp, 64);
4492     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4493     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4494     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4495     movdqu(dst, xmm0);
4496     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4497     addptr(rsp, 64);
4498   } else if (dst_enc < 16) {
4499     subptr(rsp, 64);
4500     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4501     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4502     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4503     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4504     addptr(rsp, 64);
4505   } else {
4506     subptr(rsp, 64);
4507     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4508     subptr(rsp, 64);
4509     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4510     movdqu(xmm0, src);
4511     movdqu(xmm1, dst);
4512     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4513     movdqu(dst, xmm1);
4514     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4515     addptr(rsp, 64);
4516     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4517     addptr(rsp, 64);
4518   }
4519 }
4520 
4521 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4522   int dst_enc = dst->encoding();
4523   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4524     Assembler::vpmovzxbw(dst, src, vector_len);
4525   } else if (dst_enc < 16) {
4526     Assembler::vpmovzxbw(dst, src, vector_len);
4527   } else {
4528     subptr(rsp, 64);
4529     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4530     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4531     Assembler::vpmovzxbw(xmm0, src, vector_len);
4532     movdqu(dst, xmm0);
4533     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4534     addptr(rsp, 64);
4535   }
4536 }
4537 
4538 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4539   int src_enc = src->encoding();
4540   if (src_enc < 16) {
4541     Assembler::vpmovmskb(dst, src);
4542   } else {
4543     subptr(rsp, 64);
4544     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4545     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4546     Assembler::vpmovmskb(dst, xmm0);
4547     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4548     addptr(rsp, 64);
4549   }
4550 }
4551 
4552 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4553   int dst_enc = dst->encoding();
4554   int nds_enc = nds->encoding();
4555   int src_enc = src->encoding();
4556   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4557     Assembler::vpmullw(dst, nds, src, vector_len);
4558   } else if ((dst_enc < 16) && (src_enc < 16)) {
4559     Assembler::vpmullw(dst, dst, src, vector_len);
4560   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4561     // use nds as scratch for src
4562     evmovdqul(nds, src, Assembler::AVX_512bit);
4563     Assembler::vpmullw(dst, dst, nds, vector_len);
4564   } else if ((src_enc < 16) && (nds_enc < 16)) {
4565     // use nds as scratch for dst
4566     evmovdqul(nds, dst, Assembler::AVX_512bit);
4567     Assembler::vpmullw(nds, nds, src, vector_len);
4568     evmovdqul(dst, nds, Assembler::AVX_512bit);
4569   } else if (dst_enc < 16) {
4570     // use nds as scatch for xmm0 to hold src
4571     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4572     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4573     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4574     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4575   } else {
4576     // worse case scenario, all regs are in the upper bank
4577     subptr(rsp, 64);
4578     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4579     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4580     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4581     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4582     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4583     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4584     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4585     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4586     addptr(rsp, 64);
4587   }
4588 }
4589 
4590 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4591   int dst_enc = dst->encoding();
4592   int nds_enc = nds->encoding();
4593   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4594     Assembler::vpmullw(dst, nds, src, vector_len);
4595   } else if (dst_enc < 16) {
4596     Assembler::vpmullw(dst, dst, src, vector_len);
4597   } else if (nds_enc < 16) {
4598     // implies dst_enc in upper bank with src as scratch
4599     evmovdqul(nds, dst, Assembler::AVX_512bit);
4600     Assembler::vpmullw(nds, nds, src, vector_len);
4601     evmovdqul(dst, nds, Assembler::AVX_512bit);
4602   } else {
4603     // worse case scenario, all regs in upper bank
4604     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4605     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4606     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4607     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4608   }
4609 }
4610 
4611 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4612   int dst_enc = dst->encoding();
4613   int nds_enc = nds->encoding();
4614   int src_enc = src->encoding();
4615   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4616     Assembler::vpsubb(dst, nds, src, vector_len);
4617   } else if ((dst_enc < 16) && (src_enc < 16)) {
4618     Assembler::vpsubb(dst, dst, src, vector_len);
4619   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4620     // use nds as scratch for src
4621     evmovdqul(nds, src, Assembler::AVX_512bit);
4622     Assembler::vpsubb(dst, dst, nds, vector_len);
4623   } else if ((src_enc < 16) && (nds_enc < 16)) {
4624     // use nds as scratch for dst
4625     evmovdqul(nds, dst, Assembler::AVX_512bit);
4626     Assembler::vpsubb(nds, nds, src, vector_len);
4627     evmovdqul(dst, nds, Assembler::AVX_512bit);
4628   } else if (dst_enc < 16) {
4629     // use nds as scatch for xmm0 to hold src
4630     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4631     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4632     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4633     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4634   } else {
4635     // worse case scenario, all regs are in the upper bank
4636     subptr(rsp, 64);
4637     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4638     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4639     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4640     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4641     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4642     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4643     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4644     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4645     addptr(rsp, 64);
4646   }
4647 }
4648 
4649 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4650   int dst_enc = dst->encoding();
4651   int nds_enc = nds->encoding();
4652   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4653     Assembler::vpsubb(dst, nds, src, vector_len);
4654   } else if (dst_enc < 16) {
4655     Assembler::vpsubb(dst, dst, src, vector_len);
4656   } else if (nds_enc < 16) {
4657     // implies dst_enc in upper bank with src as scratch
4658     evmovdqul(nds, dst, Assembler::AVX_512bit);
4659     Assembler::vpsubb(nds, nds, src, vector_len);
4660     evmovdqul(dst, nds, Assembler::AVX_512bit);
4661   } else {
4662     // worse case scenario, all regs in upper bank
4663     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4664     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4665     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4666     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4667   }
4668 }
4669 
4670 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4671   int dst_enc = dst->encoding();
4672   int nds_enc = nds->encoding();
4673   int src_enc = src->encoding();
4674   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4675     Assembler::vpsubw(dst, nds, src, vector_len);
4676   } else if ((dst_enc < 16) && (src_enc < 16)) {
4677     Assembler::vpsubw(dst, dst, src, vector_len);
4678   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4679     // use nds as scratch for src
4680     evmovdqul(nds, src, Assembler::AVX_512bit);
4681     Assembler::vpsubw(dst, dst, nds, vector_len);
4682   } else if ((src_enc < 16) && (nds_enc < 16)) {
4683     // use nds as scratch for dst
4684     evmovdqul(nds, dst, Assembler::AVX_512bit);
4685     Assembler::vpsubw(nds, nds, src, vector_len);
4686     evmovdqul(dst, nds, Assembler::AVX_512bit);
4687   } else if (dst_enc < 16) {
4688     // use nds as scatch for xmm0 to hold src
4689     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4690     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4691     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4692     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4693   } else {
4694     // worse case scenario, all regs are in the upper bank
4695     subptr(rsp, 64);
4696     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4697     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4698     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4699     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4700     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4701     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4702     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4703     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4704     addptr(rsp, 64);
4705   }
4706 }
4707 
4708 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4709   int dst_enc = dst->encoding();
4710   int nds_enc = nds->encoding();
4711   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4712     Assembler::vpsubw(dst, nds, src, vector_len);
4713   } else if (dst_enc < 16) {
4714     Assembler::vpsubw(dst, dst, src, vector_len);
4715   } else if (nds_enc < 16) {
4716     // implies dst_enc in upper bank with src as scratch
4717     evmovdqul(nds, dst, Assembler::AVX_512bit);
4718     Assembler::vpsubw(nds, nds, src, vector_len);
4719     evmovdqul(dst, nds, Assembler::AVX_512bit);
4720   } else {
4721     // worse case scenario, all regs in upper bank
4722     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4723     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4724     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4725     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4726   }
4727 }
4728 
4729 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4730   int dst_enc = dst->encoding();
4731   int nds_enc = nds->encoding();
4732   int shift_enc = shift->encoding();
4733   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4734     Assembler::vpsraw(dst, nds, shift, vector_len);
4735   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4736     Assembler::vpsraw(dst, dst, shift, vector_len);
4737   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4738     // use nds_enc as scratch with shift
4739     evmovdqul(nds, shift, Assembler::AVX_512bit);
4740     Assembler::vpsraw(dst, dst, nds, vector_len);
4741   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4742     // use nds as scratch with dst
4743     evmovdqul(nds, dst, Assembler::AVX_512bit);
4744     Assembler::vpsraw(nds, nds, shift, vector_len);
4745     evmovdqul(dst, nds, Assembler::AVX_512bit);
4746   } else if (dst_enc < 16) {
4747     // use nds to save a copy of xmm0 and hold shift
4748     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4749     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4750     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4751     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4752   } else if (nds_enc < 16) {
4753     // use nds as dest as temps
4754     evmovdqul(nds, dst, Assembler::AVX_512bit);
4755     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4756     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4757     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4758     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4759     evmovdqul(dst, nds, Assembler::AVX_512bit);
4760   } else {
4761     // worse case scenario, all regs are in the upper bank
4762     subptr(rsp, 64);
4763     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4764     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4765     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4766     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4767     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4768     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4769     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4770     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4771     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4772     addptr(rsp, 64);
4773   }
4774 }
4775 
4776 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4777   int dst_enc = dst->encoding();
4778   int nds_enc = nds->encoding();
4779   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4780     Assembler::vpsraw(dst, nds, shift, vector_len);
4781   } else if (dst_enc < 16) {
4782     Assembler::vpsraw(dst, dst, shift, vector_len);
4783   } else if (nds_enc < 16) {
4784     // use nds as scratch
4785     evmovdqul(nds, dst, Assembler::AVX_512bit);
4786     Assembler::vpsraw(nds, nds, shift, vector_len);
4787     evmovdqul(dst, nds, Assembler::AVX_512bit);
4788   } else {
4789     // use nds as scratch for xmm0
4790     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4791     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4792     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4793     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4794   }
4795 }
4796 
4797 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4798   int dst_enc = dst->encoding();
4799   int nds_enc = nds->encoding();
4800   int shift_enc = shift->encoding();
4801   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4802     Assembler::vpsrlw(dst, nds, shift, vector_len);
4803   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4804     Assembler::vpsrlw(dst, dst, shift, vector_len);
4805   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4806     // use nds_enc as scratch with shift
4807     evmovdqul(nds, shift, Assembler::AVX_512bit);
4808     Assembler::vpsrlw(dst, dst, nds, vector_len);
4809   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4810     // use nds as scratch with dst
4811     evmovdqul(nds, dst, Assembler::AVX_512bit);
4812     Assembler::vpsrlw(nds, nds, shift, vector_len);
4813     evmovdqul(dst, nds, Assembler::AVX_512bit);
4814   } else if (dst_enc < 16) {
4815     // use nds to save a copy of xmm0 and hold shift
4816     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4817     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4818     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4819     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4820   } else if (nds_enc < 16) {
4821     // use nds as dest as temps
4822     evmovdqul(nds, dst, Assembler::AVX_512bit);
4823     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4824     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4825     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4826     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4827     evmovdqul(dst, nds, Assembler::AVX_512bit);
4828   } else {
4829     // worse case scenario, all regs are in the upper bank
4830     subptr(rsp, 64);
4831     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4832     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4833     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4834     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4835     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4836     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4837     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4838     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4839     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4840     addptr(rsp, 64);
4841   }
4842 }
4843 
4844 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4845   int dst_enc = dst->encoding();
4846   int nds_enc = nds->encoding();
4847   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4848     Assembler::vpsrlw(dst, nds, shift, vector_len);
4849   } else if (dst_enc < 16) {
4850     Assembler::vpsrlw(dst, dst, shift, vector_len);
4851   } else if (nds_enc < 16) {
4852     // use nds as scratch
4853     evmovdqul(nds, dst, Assembler::AVX_512bit);
4854     Assembler::vpsrlw(nds, nds, shift, vector_len);
4855     evmovdqul(dst, nds, Assembler::AVX_512bit);
4856   } else {
4857     // use nds as scratch for xmm0
4858     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4859     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4860     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4861     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4862   }
4863 }
4864 
4865 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4866   int dst_enc = dst->encoding();
4867   int nds_enc = nds->encoding();
4868   int shift_enc = shift->encoding();
4869   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4870     Assembler::vpsllw(dst, nds, shift, vector_len);
4871   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4872     Assembler::vpsllw(dst, dst, shift, vector_len);
4873   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4874     // use nds_enc as scratch with shift
4875     evmovdqul(nds, shift, Assembler::AVX_512bit);
4876     Assembler::vpsllw(dst, dst, nds, vector_len);
4877   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4878     // use nds as scratch with dst
4879     evmovdqul(nds, dst, Assembler::AVX_512bit);
4880     Assembler::vpsllw(nds, nds, shift, vector_len);
4881     evmovdqul(dst, nds, Assembler::AVX_512bit);
4882   } else if (dst_enc < 16) {
4883     // use nds to save a copy of xmm0 and hold shift
4884     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4885     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4886     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4887     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4888   } else if (nds_enc < 16) {
4889     // use nds as dest as temps
4890     evmovdqul(nds, dst, Assembler::AVX_512bit);
4891     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4892     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4893     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4894     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4895     evmovdqul(dst, nds, Assembler::AVX_512bit);
4896   } else {
4897     // worse case scenario, all regs are in the upper bank
4898     subptr(rsp, 64);
4899     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4900     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4901     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4902     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4903     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4904     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4905     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4906     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4907     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4908     addptr(rsp, 64);
4909   }
4910 }
4911 
4912 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4913   int dst_enc = dst->encoding();
4914   int nds_enc = nds->encoding();
4915   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4916     Assembler::vpsllw(dst, nds, shift, vector_len);
4917   } else if (dst_enc < 16) {
4918     Assembler::vpsllw(dst, dst, shift, vector_len);
4919   } else if (nds_enc < 16) {
4920     // use nds as scratch
4921     evmovdqul(nds, dst, Assembler::AVX_512bit);
4922     Assembler::vpsllw(nds, nds, shift, vector_len);
4923     evmovdqul(dst, nds, Assembler::AVX_512bit);
4924   } else {
4925     // use nds as scratch for xmm0
4926     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4927     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4928     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4929     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4930   }
4931 }
4932 
4933 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4934   int dst_enc = dst->encoding();
4935   int src_enc = src->encoding();
4936   if ((dst_enc < 16) && (src_enc < 16)) {
4937     Assembler::vptest(dst, src);
4938   } else if (src_enc < 16) {
4939     subptr(rsp, 64);
4940     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4941     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4942     Assembler::vptest(xmm0, src);
4943     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4944     addptr(rsp, 64);
4945   } else if (dst_enc < 16) {
4946     subptr(rsp, 64);
4947     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4948     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4949     Assembler::vptest(dst, xmm0);
4950     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4951     addptr(rsp, 64);
4952   } else {
4953     subptr(rsp, 64);
4954     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4955     subptr(rsp, 64);
4956     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4957     movdqu(xmm0, src);
4958     movdqu(xmm1, dst);
4959     Assembler::vptest(xmm1, xmm0);
4960     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4961     addptr(rsp, 64);
4962     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4963     addptr(rsp, 64);
4964   }
4965 }
4966 
4967 // This instruction exists within macros, ergo we cannot control its input
4968 // when emitted through those patterns.
4969 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4970   if (VM_Version::supports_avx512nobw()) {
4971     int dst_enc = dst->encoding();
4972     int src_enc = src->encoding();
4973     if (dst_enc == src_enc) {
4974       if (dst_enc < 16) {
4975         Assembler::punpcklbw(dst, src);
4976       } else {
4977         subptr(rsp, 64);
4978         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4979         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4980         Assembler::punpcklbw(xmm0, xmm0);
4981         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4982         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4983         addptr(rsp, 64);
4984       }
4985     } else {
4986       if ((src_enc < 16) && (dst_enc < 16)) {
4987         Assembler::punpcklbw(dst, src);
4988       } else if (src_enc < 16) {
4989         subptr(rsp, 64);
4990         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4991         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4992         Assembler::punpcklbw(xmm0, src);
4993         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4994         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4995         addptr(rsp, 64);
4996       } else if (dst_enc < 16) {
4997         subptr(rsp, 64);
4998         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4999         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5000         Assembler::punpcklbw(dst, xmm0);
5001         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5002         addptr(rsp, 64);
5003       } else {
5004         subptr(rsp, 64);
5005         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5006         subptr(rsp, 64);
5007         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5008         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5009         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5010         Assembler::punpcklbw(xmm0, xmm1);
5011         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5012         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5013         addptr(rsp, 64);
5014         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5015         addptr(rsp, 64);
5016       }
5017     }
5018   } else {
5019     Assembler::punpcklbw(dst, src);
5020   }
5021 }
5022 
5023 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
5024   if (VM_Version::supports_avx512vl()) {
5025     Assembler::pshufd(dst, src, mode);
5026   } else {
5027     int dst_enc = dst->encoding();
5028     if (dst_enc < 16) {
5029       Assembler::pshufd(dst, src, mode);
5030     } else {
5031       subptr(rsp, 64);
5032       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5033       Assembler::pshufd(xmm0, src, mode);
5034       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5035       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5036       addptr(rsp, 64);
5037     }
5038   }
5039 }
5040 
5041 // This instruction exists within macros, ergo we cannot control its input
5042 // when emitted through those patterns.
5043 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5044   if (VM_Version::supports_avx512nobw()) {
5045     int dst_enc = dst->encoding();
5046     int src_enc = src->encoding();
5047     if (dst_enc == src_enc) {
5048       if (dst_enc < 16) {
5049         Assembler::pshuflw(dst, src, mode);
5050       } else {
5051         subptr(rsp, 64);
5052         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5053         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5054         Assembler::pshuflw(xmm0, xmm0, mode);
5055         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5056         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5057         addptr(rsp, 64);
5058       }
5059     } else {
5060       if ((src_enc < 16) && (dst_enc < 16)) {
5061         Assembler::pshuflw(dst, src, mode);
5062       } else if (src_enc < 16) {
5063         subptr(rsp, 64);
5064         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5065         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5066         Assembler::pshuflw(xmm0, src, mode);
5067         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5068         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5069         addptr(rsp, 64);
5070       } else if (dst_enc < 16) {
5071         subptr(rsp, 64);
5072         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5073         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5074         Assembler::pshuflw(dst, xmm0, mode);
5075         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5076         addptr(rsp, 64);
5077       } else {
5078         subptr(rsp, 64);
5079         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5080         subptr(rsp, 64);
5081         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5082         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5083         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5084         Assembler::pshuflw(xmm0, xmm1, mode);
5085         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5086         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5087         addptr(rsp, 64);
5088         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5089         addptr(rsp, 64);
5090       }
5091     }
5092   } else {
5093     Assembler::pshuflw(dst, src, mode);
5094   }
5095 }
5096 
5097 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5098   if (reachable(src)) {
5099     vandpd(dst, nds, as_Address(src), vector_len);
5100   } else {
5101     lea(rscratch1, src);
5102     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5103   }
5104 }
5105 
5106 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5107   if (reachable(src)) {
5108     vandps(dst, nds, as_Address(src), vector_len);
5109   } else {
5110     lea(rscratch1, src);
5111     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5112   }
5113 }
5114 
5115 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5116   if (reachable(src)) {
5117     vdivsd(dst, nds, as_Address(src));
5118   } else {
5119     lea(rscratch1, src);
5120     vdivsd(dst, nds, Address(rscratch1, 0));
5121   }
5122 }
5123 
5124 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5125   if (reachable(src)) {
5126     vdivss(dst, nds, as_Address(src));
5127   } else {
5128     lea(rscratch1, src);
5129     vdivss(dst, nds, Address(rscratch1, 0));
5130   }
5131 }
5132 
5133 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5134   if (reachable(src)) {
5135     vmulsd(dst, nds, as_Address(src));
5136   } else {
5137     lea(rscratch1, src);
5138     vmulsd(dst, nds, Address(rscratch1, 0));
5139   }
5140 }
5141 
5142 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5143   if (reachable(src)) {
5144     vmulss(dst, nds, as_Address(src));
5145   } else {
5146     lea(rscratch1, src);
5147     vmulss(dst, nds, Address(rscratch1, 0));
5148   }
5149 }
5150 
5151 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5152   if (reachable(src)) {
5153     vsubsd(dst, nds, as_Address(src));
5154   } else {
5155     lea(rscratch1, src);
5156     vsubsd(dst, nds, Address(rscratch1, 0));
5157   }
5158 }
5159 
5160 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5161   if (reachable(src)) {
5162     vsubss(dst, nds, as_Address(src));
5163   } else {
5164     lea(rscratch1, src);
5165     vsubss(dst, nds, Address(rscratch1, 0));
5166   }
5167 }
5168 
5169 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5170   int nds_enc = nds->encoding();
5171   int dst_enc = dst->encoding();
5172   bool dst_upper_bank = (dst_enc > 15);
5173   bool nds_upper_bank = (nds_enc > 15);
5174   if (VM_Version::supports_avx512novl() &&
5175       (nds_upper_bank || dst_upper_bank)) {
5176     if (dst_upper_bank) {
5177       subptr(rsp, 64);
5178       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5179       movflt(xmm0, nds);
5180       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5181       movflt(dst, xmm0);
5182       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5183       addptr(rsp, 64);
5184     } else {
5185       movflt(dst, nds);
5186       vxorps(dst, dst, src, Assembler::AVX_128bit);
5187     }
5188   } else {
5189     vxorps(dst, nds, src, Assembler::AVX_128bit);
5190   }
5191 }
5192 
5193 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5194   int nds_enc = nds->encoding();
5195   int dst_enc = dst->encoding();
5196   bool dst_upper_bank = (dst_enc > 15);
5197   bool nds_upper_bank = (nds_enc > 15);
5198   if (VM_Version::supports_avx512novl() &&
5199       (nds_upper_bank || dst_upper_bank)) {
5200     if (dst_upper_bank) {
5201       subptr(rsp, 64);
5202       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5203       movdbl(xmm0, nds);
5204       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5205       movdbl(dst, xmm0);
5206       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5207       addptr(rsp, 64);
5208     } else {
5209       movdbl(dst, nds);
5210       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5211     }
5212   } else {
5213     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5214   }
5215 }
5216 
5217 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5218   if (reachable(src)) {
5219     vxorpd(dst, nds, as_Address(src), vector_len);
5220   } else {
5221     lea(rscratch1, src);
5222     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5223   }
5224 }
5225 
5226 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5227   if (reachable(src)) {
5228     vxorps(dst, nds, as_Address(src), vector_len);
5229   } else {
5230     lea(rscratch1, src);
5231     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5232   }
5233 }
5234 
5235 
5236 void MacroAssembler::resolve_jobject(Register value,
5237                                      Register thread,
5238                                      Register tmp) {
5239   assert_different_registers(value, thread, tmp);
5240   Label done, not_weak;
5241   testptr(value, value);
5242   jcc(Assembler::zero, done);                // Use NULL as-is.
5243   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5244   jcc(Assembler::zero, not_weak);
5245   // Resolve jweak.
5246   movptr(value, Address(value, -JNIHandles::weak_tag_value));
5247   verify_oop(value);
5248 #if INCLUDE_ALL_GCS
5249   if (UseG1GC) {
5250     g1_write_barrier_pre(noreg /* obj */,
5251                          value /* pre_val */,
5252                          thread /* thread */,
5253                          tmp /* tmp */,
5254                          true /* tosca_live */,
5255                          true /* expand_call */);
5256   }
5257 #endif // INCLUDE_ALL_GCS
5258   jmp(done);
5259   bind(not_weak);
5260   // Resolve (untagged) jobject.
5261   movptr(value, Address(value, 0));
5262   verify_oop(value);
5263   bind(done);
5264 }
5265 
5266 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5267   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5268   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5269   // The inverted mask is sign-extended
5270   andptr(possibly_jweak, inverted_jweak_mask);
5271 }
5272 
5273 //////////////////////////////////////////////////////////////////////////////////
5274 #if INCLUDE_ALL_GCS
5275 
5276 void MacroAssembler::g1_write_barrier_pre(Register obj,
5277                                           Register pre_val,
5278                                           Register thread,
5279                                           Register tmp,
5280                                           bool tosca_live,
5281                                           bool expand_call) {
5282 
5283   // If expand_call is true then we expand the call_VM_leaf macro
5284   // directly to skip generating the check by
5285   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5286 
5287 #ifdef _LP64
5288   assert(thread == r15_thread, "must be");
5289 #endif // _LP64
5290 
5291   Label done;
5292   Label runtime;
5293 
5294   assert(pre_val != noreg, "check this code");
5295 
5296   if (obj != noreg) {
5297     assert_different_registers(obj, pre_val, tmp);
5298     assert(pre_val != rax, "check this code");
5299   }
5300 
5301   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5302                                        SATBMarkQueue::byte_offset_of_active()));
5303   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5304                                        SATBMarkQueue::byte_offset_of_index()));
5305   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5306                                        SATBMarkQueue::byte_offset_of_buf()));
5307 
5308 
5309   // Is marking active?
5310   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5311     cmpl(in_progress, 0);
5312   } else {
5313     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5314     cmpb(in_progress, 0);
5315   }
5316   jcc(Assembler::equal, done);
5317 
5318   // Do we need to load the previous value?
5319   if (obj != noreg) {
5320     load_heap_oop(pre_val, Address(obj, 0));
5321   }
5322 
5323   // Is the previous value null?
5324   cmpptr(pre_val, (int32_t) NULL_WORD);
5325   jcc(Assembler::equal, done);
5326 
5327   // Can we store original value in the thread's buffer?
5328   // Is index == 0?
5329   // (The index field is typed as size_t.)
5330 
5331   movptr(tmp, index);                   // tmp := *index_adr
5332   cmpptr(tmp, 0);                       // tmp == 0?
5333   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5334 
5335   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5336   movptr(index, tmp);                   // *index_adr := tmp
5337   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5338 
5339   // Record the previous value
5340   movptr(Address(tmp, 0), pre_val);
5341   jmp(done);
5342 
5343   bind(runtime);
5344   // save the live input values
5345   if(tosca_live) push(rax);
5346 
5347   if (obj != noreg && obj != rax)
5348     push(obj);
5349 
5350   if (pre_val != rax)
5351     push(pre_val);
5352 
5353   // Calling the runtime using the regular call_VM_leaf mechanism generates
5354   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5355   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5356   //
5357   // If we care generating the pre-barrier without a frame (e.g. in the
5358   // intrinsified Reference.get() routine) then ebp might be pointing to
5359   // the caller frame and so this check will most likely fail at runtime.
5360   //
5361   // Expanding the call directly bypasses the generation of the check.
5362   // So when we do not have have a full interpreter frame on the stack
5363   // expand_call should be passed true.
5364 
5365   NOT_LP64( push(thread); )
5366 
5367   if (expand_call) {
5368     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5369     pass_arg1(this, thread);
5370     pass_arg0(this, pre_val);
5371     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5372   } else {
5373     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5374   }
5375 
5376   NOT_LP64( pop(thread); )
5377 
5378   // save the live input values
5379   if (pre_val != rax)
5380     pop(pre_val);
5381 
5382   if (obj != noreg && obj != rax)
5383     pop(obj);
5384 
5385   if(tosca_live) pop(rax);
5386 
5387   bind(done);
5388 }
5389 
5390 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5391                                            Register new_val,
5392                                            Register thread,
5393                                            Register tmp,
5394                                            Register tmp2) {
5395 #ifdef _LP64
5396   assert(thread == r15_thread, "must be");
5397 #endif // _LP64
5398 
5399   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5400                                        DirtyCardQueue::byte_offset_of_index()));
5401   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5402                                        DirtyCardQueue::byte_offset_of_buf()));
5403 
5404   CardTableModRefBS* ct =
5405     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5406   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5407 
5408   Label done;
5409   Label runtime;
5410 
5411   // Does store cross heap regions?
5412 
5413   movptr(tmp, store_addr);
5414   xorptr(tmp, new_val);
5415   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5416   jcc(Assembler::equal, done);
5417 
5418   // crosses regions, storing NULL?
5419 
5420   cmpptr(new_val, (int32_t) NULL_WORD);
5421   jcc(Assembler::equal, done);
5422 
5423   // storing region crossing non-NULL, is card already dirty?
5424 
5425   const Register card_addr = tmp;
5426   const Register cardtable = tmp2;
5427 
5428   movptr(card_addr, store_addr);
5429   shrptr(card_addr, CardTableModRefBS::card_shift);
5430   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5431   // a valid address and therefore is not properly handled by the relocation code.
5432   movptr(cardtable, (intptr_t)ct->byte_map_base);
5433   addptr(card_addr, cardtable);
5434 
5435   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5436   jcc(Assembler::equal, done);
5437 
5438   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5439   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5440   jcc(Assembler::equal, done);
5441 
5442 
5443   // storing a region crossing, non-NULL oop, card is clean.
5444   // dirty card and log.
5445 
5446   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5447 
5448   cmpl(queue_index, 0);
5449   jcc(Assembler::equal, runtime);
5450   subl(queue_index, wordSize);
5451   movptr(tmp2, buffer);
5452 #ifdef _LP64
5453   movslq(rscratch1, queue_index);
5454   addq(tmp2, rscratch1);
5455   movq(Address(tmp2, 0), card_addr);
5456 #else
5457   addl(tmp2, queue_index);
5458   movl(Address(tmp2, 0), card_addr);
5459 #endif
5460   jmp(done);
5461 
5462   bind(runtime);
5463   // save the live input values
5464   push(store_addr);
5465   push(new_val);
5466 #ifdef _LP64
5467   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5468 #else
5469   push(thread);
5470   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5471   pop(thread);
5472 #endif
5473   pop(new_val);
5474   pop(store_addr);
5475 
5476   bind(done);
5477 }
5478 
5479 #endif // INCLUDE_ALL_GCS
5480 //////////////////////////////////////////////////////////////////////////////////
5481 
5482 
5483 void MacroAssembler::store_check(Register obj, Address dst) {
5484   store_check(obj);
5485 }
5486 
5487 void MacroAssembler::store_check(Register obj) {
5488   // Does a store check for the oop in register obj. The content of
5489   // register obj is destroyed afterwards.
5490   BarrierSet* bs = Universe::heap()->barrier_set();
5491   assert(bs->kind() == BarrierSet::CardTableForRS ||
5492          bs->kind() == BarrierSet::CardTableExtension,
5493          "Wrong barrier set kind");
5494 
5495   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5496   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5497 
5498   shrptr(obj, CardTableModRefBS::card_shift);
5499 
5500   Address card_addr;
5501 
5502   // The calculation for byte_map_base is as follows:
5503   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5504   // So this essentially converts an address to a displacement and it will
5505   // never need to be relocated. On 64bit however the value may be too
5506   // large for a 32bit displacement.
5507   intptr_t disp = (intptr_t) ct->byte_map_base;
5508   if (is_simm32(disp)) {
5509     card_addr = Address(noreg, obj, Address::times_1, disp);
5510   } else {
5511     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5512     // displacement and done in a single instruction given favorable mapping and a
5513     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5514     // entry and that entry is not properly handled by the relocation code.
5515     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5516     Address index(noreg, obj, Address::times_1);
5517     card_addr = as_Address(ArrayAddress(cardtable, index));
5518   }
5519 
5520   int dirty = CardTableModRefBS::dirty_card_val();
5521   if (UseCondCardMark) {
5522     Label L_already_dirty;
5523     if (UseConcMarkSweepGC) {
5524       membar(Assembler::StoreLoad);
5525     }
5526     cmpb(card_addr, dirty);
5527     jcc(Assembler::equal, L_already_dirty);
5528     movb(card_addr, dirty);
5529     bind(L_already_dirty);
5530   } else {
5531     movb(card_addr, dirty);
5532   }
5533 }
5534 
5535 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5536   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5537 }
5538 
5539 // Force generation of a 4 byte immediate value even if it fits into 8bit
5540 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5541   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5542 }
5543 
5544 void MacroAssembler::subptr(Register dst, Register src) {
5545   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5546 }
5547 
5548 // C++ bool manipulation
5549 void MacroAssembler::testbool(Register dst) {
5550   if(sizeof(bool) == 1)
5551     testb(dst, 0xff);
5552   else if(sizeof(bool) == 2) {
5553     // testw implementation needed for two byte bools
5554     ShouldNotReachHere();
5555   } else if(sizeof(bool) == 4)
5556     testl(dst, dst);
5557   else
5558     // unsupported
5559     ShouldNotReachHere();
5560 }
5561 
5562 void MacroAssembler::testptr(Register dst, Register src) {
5563   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5564 }
5565 
5566 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5567 void MacroAssembler::tlab_allocate(Register obj,
5568                                    Register var_size_in_bytes,
5569                                    int con_size_in_bytes,
5570                                    Register t1,
5571                                    Register t2,
5572                                    Label& slow_case) {
5573   assert_different_registers(obj, t1, t2);
5574   assert_different_registers(obj, var_size_in_bytes, t1);
5575   Register end = t2;
5576   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5577 
5578   verify_tlab();
5579 
5580   NOT_LP64(get_thread(thread));
5581 
5582   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5583   if (var_size_in_bytes == noreg) {
5584     lea(end, Address(obj, con_size_in_bytes));
5585   } else {
5586     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5587   }
5588   cmpptr(end, Address(thread, JavaThread::tlab_current_end_offset()));
5589   jcc(Assembler::above, slow_case);
5590 
5591   // update the tlab top pointer
5592   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5593 
5594   // recover var_size_in_bytes if necessary
5595   if (var_size_in_bytes == end) {
5596     subptr(var_size_in_bytes, obj);
5597   }
5598   verify_tlab();
5599 }
5600 
5601 // Preserves rbx, and rdx.
5602 Register MacroAssembler::tlab_refill(Label& retry,
5603                                      Label& try_eden,
5604                                      Label& slow_case) {
5605   Register top = rax;
5606   Register t1  = rcx; // object size
5607   Register t2  = rsi;
5608   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5609   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5610   Label do_refill, discard_tlab;
5611 
5612   if (!Universe::heap()->supports_inline_contig_alloc()) {
5613     // No allocation in the shared eden.
5614     jmp(slow_case);
5615   }
5616 
5617   NOT_LP64(get_thread(thread_reg));
5618 
5619   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5620   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_current_end_offset())));
5621 
5622   // calculate amount of free space
5623   subptr(t1, top);
5624   shrptr(t1, LogHeapWordSize);
5625 
5626   // Retain tlab and allocate object in shared space if
5627   // the amount free in the tlab is too large to discard.
5628   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5629   jcc(Assembler::lessEqual, discard_tlab);
5630 
5631   // Retain
5632   // %%% yuck as movptr...
5633   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5634   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5635   if (TLABStats) {
5636     // increment number of slow_allocations
5637     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5638   }
5639   jmp(try_eden);
5640 
5641   bind(discard_tlab);
5642   if (TLABStats) {
5643     // increment number of refills
5644     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5645     // accumulate wastage -- t1 is amount free in tlab
5646     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5647   }
5648 
5649   // if tlab is currently allocated (top or end != null) then
5650   // fill [top, end + alignment_reserve) with array object
5651   testptr(top, top);
5652   jcc(Assembler::zero, do_refill);
5653 
5654   // set up the mark word
5655   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5656   // set the length to the remaining space
5657   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5658   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5659   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5660   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5661   // set klass to intArrayKlass
5662   // dubious reloc why not an oop reloc?
5663   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5664   // store klass last.  concurrent gcs assumes klass length is valid if
5665   // klass field is not null.
5666   store_klass(top, t1);
5667 
5668   movptr(t1, top);
5669   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5670   incr_allocated_bytes(thread_reg, t1, 0);
5671 
5672   // refill the tlab with an eden allocation
5673   bind(do_refill);
5674   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5675   shlptr(t1, LogHeapWordSize);
5676   // allocate new tlab, address returned in top
5677   eden_allocate(top, t1, 0, t2, slow_case);
5678 
5679   // Check that t1 was preserved in eden_allocate.
5680 #ifdef ASSERT
5681   if (UseTLAB) {
5682     Label ok;
5683     Register tsize = rsi;
5684     assert_different_registers(tsize, thread_reg, t1);
5685     push(tsize);
5686     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5687     shlptr(tsize, LogHeapWordSize);
5688     cmpptr(t1, tsize);
5689     jcc(Assembler::equal, ok);
5690     STOP("assert(t1 != tlab size)");
5691     should_not_reach_here();
5692 
5693     bind(ok);
5694     pop(tsize);
5695   }
5696 #endif
5697   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5698   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5699   addptr(top, t1);
5700   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5701   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_current_end_offset())), top);
5702 
5703   if (ZeroTLAB) {
5704     // This is a fast TLAB refill, therefore the GC is not notified of it.
5705     // So compiled code must fill the new TLAB with zeroes.
5706     movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5707     zero_memory(top, t1, 0, t2);
5708   }
5709 
5710   verify_tlab();
5711   jmp(retry);
5712 
5713   return thread_reg; // for use by caller
5714 }
5715 
5716 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5717 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5718   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5719   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5720   Label done;
5721 
5722   testptr(length_in_bytes, length_in_bytes);
5723   jcc(Assembler::zero, done);
5724 
5725   // initialize topmost word, divide index by 2, check if odd and test if zero
5726   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5727 #ifdef ASSERT
5728   {
5729     Label L;
5730     testptr(length_in_bytes, BytesPerWord - 1);
5731     jcc(Assembler::zero, L);
5732     stop("length must be a multiple of BytesPerWord");
5733     bind(L);
5734   }
5735 #endif
5736   Register index = length_in_bytes;
5737   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5738   if (UseIncDec) {
5739     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5740   } else {
5741     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5742     shrptr(index, 1);
5743   }
5744 #ifndef _LP64
5745   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5746   {
5747     Label even;
5748     // note: if index was a multiple of 8, then it cannot
5749     //       be 0 now otherwise it must have been 0 before
5750     //       => if it is even, we don't need to check for 0 again
5751     jcc(Assembler::carryClear, even);
5752     // clear topmost word (no jump would be needed if conditional assignment worked here)
5753     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5754     // index could be 0 now, must check again
5755     jcc(Assembler::zero, done);
5756     bind(even);
5757   }
5758 #endif // !_LP64
5759   // initialize remaining object fields: index is a multiple of 2 now
5760   {
5761     Label loop;
5762     bind(loop);
5763     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5764     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5765     decrement(index);
5766     jcc(Assembler::notZero, loop);
5767   }
5768 
5769   bind(done);
5770 }
5771 
5772 void MacroAssembler::incr_allocated_bytes(Register thread,
5773                                           Register var_size_in_bytes,
5774                                           int con_size_in_bytes,
5775                                           Register t1) {
5776   if (!thread->is_valid()) {
5777 #ifdef _LP64
5778     thread = r15_thread;
5779 #else
5780     assert(t1->is_valid(), "need temp reg");
5781     thread = t1;
5782     get_thread(thread);
5783 #endif
5784   }
5785 
5786 #ifdef _LP64
5787   if (var_size_in_bytes->is_valid()) {
5788     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5789   } else {
5790     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5791   }
5792 #else
5793   if (var_size_in_bytes->is_valid()) {
5794     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5795   } else {
5796     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5797   }
5798   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5799 #endif
5800 }
5801 
5802 // Look up the method for a megamorphic invokeinterface call.
5803 // The target method is determined by <intf_klass, itable_index>.
5804 // The receiver klass is in recv_klass.
5805 // On success, the result will be in method_result, and execution falls through.
5806 // On failure, execution transfers to the given label.
5807 void MacroAssembler::lookup_interface_method(Register recv_klass,
5808                                              Register intf_klass,
5809                                              RegisterOrConstant itable_index,
5810                                              Register method_result,
5811                                              Register scan_temp,
5812                                              Label& L_no_such_interface) {
5813   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5814   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5815          "caller must use same register for non-constant itable index as for method");
5816 
5817   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5818   int vtable_base = in_bytes(Klass::vtable_start_offset());
5819   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5820   int scan_step   = itableOffsetEntry::size() * wordSize;
5821   int vte_size    = vtableEntry::size_in_bytes();
5822   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5823   assert(vte_size == wordSize, "else adjust times_vte_scale");
5824 
5825   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5826 
5827   // %%% Could store the aligned, prescaled offset in the klassoop.
5828   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5829 
5830   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5831   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5832   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5833 
5834   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5835   //   if (scan->interface() == intf) {
5836   //     result = (klass + scan->offset() + itable_index);
5837   //   }
5838   // }
5839   Label search, found_method;
5840 
5841   for (int peel = 1; peel >= 0; peel--) {
5842     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5843     cmpptr(intf_klass, method_result);
5844 
5845     if (peel) {
5846       jccb(Assembler::equal, found_method);
5847     } else {
5848       jccb(Assembler::notEqual, search);
5849       // (invert the test to fall through to found_method...)
5850     }
5851 
5852     if (!peel)  break;
5853 
5854     bind(search);
5855 
5856     // Check that the previous entry is non-null.  A null entry means that
5857     // the receiver class doesn't implement the interface, and wasn't the
5858     // same as when the caller was compiled.
5859     testptr(method_result, method_result);
5860     jcc(Assembler::zero, L_no_such_interface);
5861     addptr(scan_temp, scan_step);
5862   }
5863 
5864   bind(found_method);
5865 
5866   // Got a hit.
5867   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5868   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5869 }
5870 
5871 
5872 // virtual method calling
5873 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5874                                            RegisterOrConstant vtable_index,
5875                                            Register method_result) {
5876   const int base = in_bytes(Klass::vtable_start_offset());
5877   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5878   Address vtable_entry_addr(recv_klass,
5879                             vtable_index, Address::times_ptr,
5880                             base + vtableEntry::method_offset_in_bytes());
5881   movptr(method_result, vtable_entry_addr);
5882 }
5883 
5884 
5885 void MacroAssembler::check_klass_subtype(Register sub_klass,
5886                            Register super_klass,
5887                            Register temp_reg,
5888                            Label& L_success) {
5889   Label L_failure;
5890   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5891   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5892   bind(L_failure);
5893 }
5894 
5895 
5896 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5897                                                    Register super_klass,
5898                                                    Register temp_reg,
5899                                                    Label* L_success,
5900                                                    Label* L_failure,
5901                                                    Label* L_slow_path,
5902                                         RegisterOrConstant super_check_offset) {
5903   assert_different_registers(sub_klass, super_klass, temp_reg);
5904   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5905   if (super_check_offset.is_register()) {
5906     assert_different_registers(sub_klass, super_klass,
5907                                super_check_offset.as_register());
5908   } else if (must_load_sco) {
5909     assert(temp_reg != noreg, "supply either a temp or a register offset");
5910   }
5911 
5912   Label L_fallthrough;
5913   int label_nulls = 0;
5914   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5915   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5916   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5917   assert(label_nulls <= 1, "at most one NULL in the batch");
5918 
5919   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5920   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5921   Address super_check_offset_addr(super_klass, sco_offset);
5922 
5923   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5924   // range of a jccb.  If this routine grows larger, reconsider at
5925   // least some of these.
5926 #define local_jcc(assembler_cond, label)                                \
5927   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5928   else                             jcc( assembler_cond, label) /*omit semi*/
5929 
5930   // Hacked jmp, which may only be used just before L_fallthrough.
5931 #define final_jmp(label)                                                \
5932   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5933   else                            jmp(label)                /*omit semi*/
5934 
5935   // If the pointers are equal, we are done (e.g., String[] elements).
5936   // This self-check enables sharing of secondary supertype arrays among
5937   // non-primary types such as array-of-interface.  Otherwise, each such
5938   // type would need its own customized SSA.
5939   // We move this check to the front of the fast path because many
5940   // type checks are in fact trivially successful in this manner,
5941   // so we get a nicely predicted branch right at the start of the check.
5942   cmpptr(sub_klass, super_klass);
5943   local_jcc(Assembler::equal, *L_success);
5944 
5945   // Check the supertype display:
5946   if (must_load_sco) {
5947     // Positive movl does right thing on LP64.
5948     movl(temp_reg, super_check_offset_addr);
5949     super_check_offset = RegisterOrConstant(temp_reg);
5950   }
5951   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5952   cmpptr(super_klass, super_check_addr); // load displayed supertype
5953 
5954   // This check has worked decisively for primary supers.
5955   // Secondary supers are sought in the super_cache ('super_cache_addr').
5956   // (Secondary supers are interfaces and very deeply nested subtypes.)
5957   // This works in the same check above because of a tricky aliasing
5958   // between the super_cache and the primary super display elements.
5959   // (The 'super_check_addr' can address either, as the case requires.)
5960   // Note that the cache is updated below if it does not help us find
5961   // what we need immediately.
5962   // So if it was a primary super, we can just fail immediately.
5963   // Otherwise, it's the slow path for us (no success at this point).
5964 
5965   if (super_check_offset.is_register()) {
5966     local_jcc(Assembler::equal, *L_success);
5967     cmpl(super_check_offset.as_register(), sc_offset);
5968     if (L_failure == &L_fallthrough) {
5969       local_jcc(Assembler::equal, *L_slow_path);
5970     } else {
5971       local_jcc(Assembler::notEqual, *L_failure);
5972       final_jmp(*L_slow_path);
5973     }
5974   } else if (super_check_offset.as_constant() == sc_offset) {
5975     // Need a slow path; fast failure is impossible.
5976     if (L_slow_path == &L_fallthrough) {
5977       local_jcc(Assembler::equal, *L_success);
5978     } else {
5979       local_jcc(Assembler::notEqual, *L_slow_path);
5980       final_jmp(*L_success);
5981     }
5982   } else {
5983     // No slow path; it's a fast decision.
5984     if (L_failure == &L_fallthrough) {
5985       local_jcc(Assembler::equal, *L_success);
5986     } else {
5987       local_jcc(Assembler::notEqual, *L_failure);
5988       final_jmp(*L_success);
5989     }
5990   }
5991 
5992   bind(L_fallthrough);
5993 
5994 #undef local_jcc
5995 #undef final_jmp
5996 }
5997 
5998 
5999 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
6000                                                    Register super_klass,
6001                                                    Register temp_reg,
6002                                                    Register temp2_reg,
6003                                                    Label* L_success,
6004                                                    Label* L_failure,
6005                                                    bool set_cond_codes) {
6006   assert_different_registers(sub_klass, super_klass, temp_reg);
6007   if (temp2_reg != noreg)
6008     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
6009 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
6010 
6011   Label L_fallthrough;
6012   int label_nulls = 0;
6013   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6014   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6015   assert(label_nulls <= 1, "at most one NULL in the batch");
6016 
6017   // a couple of useful fields in sub_klass:
6018   int ss_offset = in_bytes(Klass::secondary_supers_offset());
6019   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6020   Address secondary_supers_addr(sub_klass, ss_offset);
6021   Address super_cache_addr(     sub_klass, sc_offset);
6022 
6023   // Do a linear scan of the secondary super-klass chain.
6024   // This code is rarely used, so simplicity is a virtue here.
6025   // The repne_scan instruction uses fixed registers, which we must spill.
6026   // Don't worry too much about pre-existing connections with the input regs.
6027 
6028   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
6029   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
6030 
6031   // Get super_klass value into rax (even if it was in rdi or rcx).
6032   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
6033   if (super_klass != rax || UseCompressedOops) {
6034     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
6035     mov(rax, super_klass);
6036   }
6037   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
6038   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
6039 
6040 #ifndef PRODUCT
6041   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
6042   ExternalAddress pst_counter_addr((address) pst_counter);
6043   NOT_LP64(  incrementl(pst_counter_addr) );
6044   LP64_ONLY( lea(rcx, pst_counter_addr) );
6045   LP64_ONLY( incrementl(Address(rcx, 0)) );
6046 #endif //PRODUCT
6047 
6048   // We will consult the secondary-super array.
6049   movptr(rdi, secondary_supers_addr);
6050   // Load the array length.  (Positive movl does right thing on LP64.)
6051   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6052   // Skip to start of data.
6053   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6054 
6055   // Scan RCX words at [RDI] for an occurrence of RAX.
6056   // Set NZ/Z based on last compare.
6057   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6058   // not change flags (only scas instruction which is repeated sets flags).
6059   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6060 
6061     testptr(rax,rax); // Set Z = 0
6062     repne_scan();
6063 
6064   // Unspill the temp. registers:
6065   if (pushed_rdi)  pop(rdi);
6066   if (pushed_rcx)  pop(rcx);
6067   if (pushed_rax)  pop(rax);
6068 
6069   if (set_cond_codes) {
6070     // Special hack for the AD files:  rdi is guaranteed non-zero.
6071     assert(!pushed_rdi, "rdi must be left non-NULL");
6072     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6073   }
6074 
6075   if (L_failure == &L_fallthrough)
6076         jccb(Assembler::notEqual, *L_failure);
6077   else  jcc(Assembler::notEqual, *L_failure);
6078 
6079   // Success.  Cache the super we found and proceed in triumph.
6080   movptr(super_cache_addr, super_klass);
6081 
6082   if (L_success != &L_fallthrough) {
6083     jmp(*L_success);
6084   }
6085 
6086 #undef IS_A_TEMP
6087 
6088   bind(L_fallthrough);
6089 }
6090 
6091 
6092 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6093   if (VM_Version::supports_cmov()) {
6094     cmovl(cc, dst, src);
6095   } else {
6096     Label L;
6097     jccb(negate_condition(cc), L);
6098     movl(dst, src);
6099     bind(L);
6100   }
6101 }
6102 
6103 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6104   if (VM_Version::supports_cmov()) {
6105     cmovl(cc, dst, src);
6106   } else {
6107     Label L;
6108     jccb(negate_condition(cc), L);
6109     movl(dst, src);
6110     bind(L);
6111   }
6112 }
6113 
6114 void MacroAssembler::verify_oop(Register reg, const char* s) {
6115   if (!VerifyOops) return;
6116 
6117   // Pass register number to verify_oop_subroutine
6118   const char* b = NULL;
6119   {
6120     ResourceMark rm;
6121     stringStream ss;
6122     ss.print("verify_oop: %s: %s", reg->name(), s);
6123     b = code_string(ss.as_string());
6124   }
6125   BLOCK_COMMENT("verify_oop {");
6126 #ifdef _LP64
6127   push(rscratch1);                    // save r10, trashed by movptr()
6128 #endif
6129   push(rax);                          // save rax,
6130   push(reg);                          // pass register argument
6131   ExternalAddress buffer((address) b);
6132   // avoid using pushptr, as it modifies scratch registers
6133   // and our contract is not to modify anything
6134   movptr(rax, buffer.addr());
6135   push(rax);
6136   // call indirectly to solve generation ordering problem
6137   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6138   call(rax);
6139   // Caller pops the arguments (oop, message) and restores rax, r10
6140   BLOCK_COMMENT("} verify_oop");
6141 }
6142 
6143 
6144 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6145                                                       Register tmp,
6146                                                       int offset) {
6147   intptr_t value = *delayed_value_addr;
6148   if (value != 0)
6149     return RegisterOrConstant(value + offset);
6150 
6151   // load indirectly to solve generation ordering problem
6152   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6153 
6154 #ifdef ASSERT
6155   { Label L;
6156     testptr(tmp, tmp);
6157     if (WizardMode) {
6158       const char* buf = NULL;
6159       {
6160         ResourceMark rm;
6161         stringStream ss;
6162         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6163         buf = code_string(ss.as_string());
6164       }
6165       jcc(Assembler::notZero, L);
6166       STOP(buf);
6167     } else {
6168       jccb(Assembler::notZero, L);
6169       hlt();
6170     }
6171     bind(L);
6172   }
6173 #endif
6174 
6175   if (offset != 0)
6176     addptr(tmp, offset);
6177 
6178   return RegisterOrConstant(tmp);
6179 }
6180 
6181 
6182 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6183                                          int extra_slot_offset) {
6184   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6185   int stackElementSize = Interpreter::stackElementSize;
6186   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6187 #ifdef ASSERT
6188   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6189   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6190 #endif
6191   Register             scale_reg    = noreg;
6192   Address::ScaleFactor scale_factor = Address::no_scale;
6193   if (arg_slot.is_constant()) {
6194     offset += arg_slot.as_constant() * stackElementSize;
6195   } else {
6196     scale_reg    = arg_slot.as_register();
6197     scale_factor = Address::times(stackElementSize);
6198   }
6199   offset += wordSize;           // return PC is on stack
6200   return Address(rsp, scale_reg, scale_factor, offset);
6201 }
6202 
6203 
6204 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6205   if (!VerifyOops) return;
6206 
6207   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6208   // Pass register number to verify_oop_subroutine
6209   const char* b = NULL;
6210   {
6211     ResourceMark rm;
6212     stringStream ss;
6213     ss.print("verify_oop_addr: %s", s);
6214     b = code_string(ss.as_string());
6215   }
6216 #ifdef _LP64
6217   push(rscratch1);                    // save r10, trashed by movptr()
6218 #endif
6219   push(rax);                          // save rax,
6220   // addr may contain rsp so we will have to adjust it based on the push
6221   // we just did (and on 64 bit we do two pushes)
6222   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6223   // stores rax into addr which is backwards of what was intended.
6224   if (addr.uses(rsp)) {
6225     lea(rax, addr);
6226     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6227   } else {
6228     pushptr(addr);
6229   }
6230 
6231   ExternalAddress buffer((address) b);
6232   // pass msg argument
6233   // avoid using pushptr, as it modifies scratch registers
6234   // and our contract is not to modify anything
6235   movptr(rax, buffer.addr());
6236   push(rax);
6237 
6238   // call indirectly to solve generation ordering problem
6239   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6240   call(rax);
6241   // Caller pops the arguments (addr, message) and restores rax, r10.
6242 }
6243 
6244 void MacroAssembler::verify_tlab() {
6245 #ifdef ASSERT
6246   if (UseTLAB && VerifyOops) {
6247     Label next, ok;
6248     Register t1 = rsi;
6249     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6250 
6251     push(t1);
6252     NOT_LP64(push(thread_reg));
6253     NOT_LP64(get_thread(thread_reg));
6254 
6255     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6256     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6257     jcc(Assembler::aboveEqual, next);
6258     STOP("assert(top >= start)");
6259     should_not_reach_here();
6260 
6261     bind(next);
6262     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_current_end_offset())));
6263     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6264     jcc(Assembler::aboveEqual, ok);
6265     STOP("assert(top <= end)");
6266     should_not_reach_here();
6267 
6268     bind(ok);
6269     NOT_LP64(pop(thread_reg));
6270     pop(t1);
6271   }
6272 #endif
6273 }
6274 
6275 class ControlWord {
6276  public:
6277   int32_t _value;
6278 
6279   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6280   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6281   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6282   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6283   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6284   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6285   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6286   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6287 
6288   void print() const {
6289     // rounding control
6290     const char* rc;
6291     switch (rounding_control()) {
6292       case 0: rc = "round near"; break;
6293       case 1: rc = "round down"; break;
6294       case 2: rc = "round up  "; break;
6295       case 3: rc = "chop      "; break;
6296     };
6297     // precision control
6298     const char* pc;
6299     switch (precision_control()) {
6300       case 0: pc = "24 bits "; break;
6301       case 1: pc = "reserved"; break;
6302       case 2: pc = "53 bits "; break;
6303       case 3: pc = "64 bits "; break;
6304     };
6305     // flags
6306     char f[9];
6307     f[0] = ' ';
6308     f[1] = ' ';
6309     f[2] = (precision   ()) ? 'P' : 'p';
6310     f[3] = (underflow   ()) ? 'U' : 'u';
6311     f[4] = (overflow    ()) ? 'O' : 'o';
6312     f[5] = (zero_divide ()) ? 'Z' : 'z';
6313     f[6] = (denormalized()) ? 'D' : 'd';
6314     f[7] = (invalid     ()) ? 'I' : 'i';
6315     f[8] = '\x0';
6316     // output
6317     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6318   }
6319 
6320 };
6321 
6322 class StatusWord {
6323  public:
6324   int32_t _value;
6325 
6326   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6327   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6328   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6329   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6330   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6331   int  top() const                     { return  (_value >> 11) & 7      ; }
6332   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6333   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6334   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6335   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6336   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6337   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6338   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6339   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6340 
6341   void print() const {
6342     // condition codes
6343     char c[5];
6344     c[0] = (C3()) ? '3' : '-';
6345     c[1] = (C2()) ? '2' : '-';
6346     c[2] = (C1()) ? '1' : '-';
6347     c[3] = (C0()) ? '0' : '-';
6348     c[4] = '\x0';
6349     // flags
6350     char f[9];
6351     f[0] = (error_status()) ? 'E' : '-';
6352     f[1] = (stack_fault ()) ? 'S' : '-';
6353     f[2] = (precision   ()) ? 'P' : '-';
6354     f[3] = (underflow   ()) ? 'U' : '-';
6355     f[4] = (overflow    ()) ? 'O' : '-';
6356     f[5] = (zero_divide ()) ? 'Z' : '-';
6357     f[6] = (denormalized()) ? 'D' : '-';
6358     f[7] = (invalid     ()) ? 'I' : '-';
6359     f[8] = '\x0';
6360     // output
6361     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6362   }
6363 
6364 };
6365 
6366 class TagWord {
6367  public:
6368   int32_t _value;
6369 
6370   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6371 
6372   void print() const {
6373     printf("%04x", _value & 0xFFFF);
6374   }
6375 
6376 };
6377 
6378 class FPU_Register {
6379  public:
6380   int32_t _m0;
6381   int32_t _m1;
6382   int16_t _ex;
6383 
6384   bool is_indefinite() const           {
6385     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6386   }
6387 
6388   void print() const {
6389     char  sign = (_ex < 0) ? '-' : '+';
6390     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6391     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6392   };
6393 
6394 };
6395 
6396 class FPU_State {
6397  public:
6398   enum {
6399     register_size       = 10,
6400     number_of_registers =  8,
6401     register_mask       =  7
6402   };
6403 
6404   ControlWord  _control_word;
6405   StatusWord   _status_word;
6406   TagWord      _tag_word;
6407   int32_t      _error_offset;
6408   int32_t      _error_selector;
6409   int32_t      _data_offset;
6410   int32_t      _data_selector;
6411   int8_t       _register[register_size * number_of_registers];
6412 
6413   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6414   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6415 
6416   const char* tag_as_string(int tag) const {
6417     switch (tag) {
6418       case 0: return "valid";
6419       case 1: return "zero";
6420       case 2: return "special";
6421       case 3: return "empty";
6422     }
6423     ShouldNotReachHere();
6424     return NULL;
6425   }
6426 
6427   void print() const {
6428     // print computation registers
6429     { int t = _status_word.top();
6430       for (int i = 0; i < number_of_registers; i++) {
6431         int j = (i - t) & register_mask;
6432         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6433         st(j)->print();
6434         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6435       }
6436     }
6437     printf("\n");
6438     // print control registers
6439     printf("ctrl = "); _control_word.print(); printf("\n");
6440     printf("stat = "); _status_word .print(); printf("\n");
6441     printf("tags = "); _tag_word    .print(); printf("\n");
6442   }
6443 
6444 };
6445 
6446 class Flag_Register {
6447  public:
6448   int32_t _value;
6449 
6450   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6451   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6452   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6453   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6454   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6455   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6456   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6457 
6458   void print() const {
6459     // flags
6460     char f[8];
6461     f[0] = (overflow       ()) ? 'O' : '-';
6462     f[1] = (direction      ()) ? 'D' : '-';
6463     f[2] = (sign           ()) ? 'S' : '-';
6464     f[3] = (zero           ()) ? 'Z' : '-';
6465     f[4] = (auxiliary_carry()) ? 'A' : '-';
6466     f[5] = (parity         ()) ? 'P' : '-';
6467     f[6] = (carry          ()) ? 'C' : '-';
6468     f[7] = '\x0';
6469     // output
6470     printf("%08x  flags = %s", _value, f);
6471   }
6472 
6473 };
6474 
6475 class IU_Register {
6476  public:
6477   int32_t _value;
6478 
6479   void print() const {
6480     printf("%08x  %11d", _value, _value);
6481   }
6482 
6483 };
6484 
6485 class IU_State {
6486  public:
6487   Flag_Register _eflags;
6488   IU_Register   _rdi;
6489   IU_Register   _rsi;
6490   IU_Register   _rbp;
6491   IU_Register   _rsp;
6492   IU_Register   _rbx;
6493   IU_Register   _rdx;
6494   IU_Register   _rcx;
6495   IU_Register   _rax;
6496 
6497   void print() const {
6498     // computation registers
6499     printf("rax,  = "); _rax.print(); printf("\n");
6500     printf("rbx,  = "); _rbx.print(); printf("\n");
6501     printf("rcx  = "); _rcx.print(); printf("\n");
6502     printf("rdx  = "); _rdx.print(); printf("\n");
6503     printf("rdi  = "); _rdi.print(); printf("\n");
6504     printf("rsi  = "); _rsi.print(); printf("\n");
6505     printf("rbp,  = "); _rbp.print(); printf("\n");
6506     printf("rsp  = "); _rsp.print(); printf("\n");
6507     printf("\n");
6508     // control registers
6509     printf("flgs = "); _eflags.print(); printf("\n");
6510   }
6511 };
6512 
6513 
6514 class CPU_State {
6515  public:
6516   FPU_State _fpu_state;
6517   IU_State  _iu_state;
6518 
6519   void print() const {
6520     printf("--------------------------------------------------\n");
6521     _iu_state .print();
6522     printf("\n");
6523     _fpu_state.print();
6524     printf("--------------------------------------------------\n");
6525   }
6526 
6527 };
6528 
6529 
6530 static void _print_CPU_state(CPU_State* state) {
6531   state->print();
6532 };
6533 
6534 
6535 void MacroAssembler::print_CPU_state() {
6536   push_CPU_state();
6537   push(rsp);                // pass CPU state
6538   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6539   addptr(rsp, wordSize);       // discard argument
6540   pop_CPU_state();
6541 }
6542 
6543 
6544 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6545   static int counter = 0;
6546   FPU_State* fs = &state->_fpu_state;
6547   counter++;
6548   // For leaf calls, only verify that the top few elements remain empty.
6549   // We only need 1 empty at the top for C2 code.
6550   if( stack_depth < 0 ) {
6551     if( fs->tag_for_st(7) != 3 ) {
6552       printf("FPR7 not empty\n");
6553       state->print();
6554       assert(false, "error");
6555       return false;
6556     }
6557     return true;                // All other stack states do not matter
6558   }
6559 
6560   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6561          "bad FPU control word");
6562 
6563   // compute stack depth
6564   int i = 0;
6565   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6566   int d = i;
6567   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6568   // verify findings
6569   if (i != FPU_State::number_of_registers) {
6570     // stack not contiguous
6571     printf("%s: stack not contiguous at ST%d\n", s, i);
6572     state->print();
6573     assert(false, "error");
6574     return false;
6575   }
6576   // check if computed stack depth corresponds to expected stack depth
6577   if (stack_depth < 0) {
6578     // expected stack depth is -stack_depth or less
6579     if (d > -stack_depth) {
6580       // too many elements on the stack
6581       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6582       state->print();
6583       assert(false, "error");
6584       return false;
6585     }
6586   } else {
6587     // expected stack depth is stack_depth
6588     if (d != stack_depth) {
6589       // wrong stack depth
6590       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6591       state->print();
6592       assert(false, "error");
6593       return false;
6594     }
6595   }
6596   // everything is cool
6597   return true;
6598 }
6599 
6600 
6601 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6602   if (!VerifyFPU) return;
6603   push_CPU_state();
6604   push(rsp);                // pass CPU state
6605   ExternalAddress msg((address) s);
6606   // pass message string s
6607   pushptr(msg.addr());
6608   push(stack_depth);        // pass stack depth
6609   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6610   addptr(rsp, 3 * wordSize);   // discard arguments
6611   // check for error
6612   { Label L;
6613     testl(rax, rax);
6614     jcc(Assembler::notZero, L);
6615     int3();                  // break if error condition
6616     bind(L);
6617   }
6618   pop_CPU_state();
6619 }
6620 
6621 void MacroAssembler::restore_cpu_control_state_after_jni() {
6622   // Either restore the MXCSR register after returning from the JNI Call
6623   // or verify that it wasn't changed (with -Xcheck:jni flag).
6624   if (VM_Version::supports_sse()) {
6625     if (RestoreMXCSROnJNICalls) {
6626       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6627     } else if (CheckJNICalls) {
6628       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6629     }
6630   }
6631   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6632   vzeroupper();
6633   // Reset k1 to 0xffff.
6634   if (VM_Version::supports_evex()) {
6635     push(rcx);
6636     movl(rcx, 0xffff);
6637     kmovwl(k1, rcx);
6638     pop(rcx);
6639   }
6640 
6641 #ifndef _LP64
6642   // Either restore the x87 floating pointer control word after returning
6643   // from the JNI call or verify that it wasn't changed.
6644   if (CheckJNICalls) {
6645     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6646   }
6647 #endif // _LP64
6648 }
6649 
6650 // ((OopHandle)result).resolve();
6651 void MacroAssembler::resolve_oop_handle(Register result) {
6652   // OopHandle::resolve is an indirection.
6653   movptr(result, Address(result, 0));
6654 }
6655 
6656 void MacroAssembler::load_mirror(Register mirror, Register method) {
6657   // get mirror
6658   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6659   movptr(mirror, Address(method, Method::const_offset()));
6660   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6661   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6662   movptr(mirror, Address(mirror, mirror_offset));
6663   resolve_oop_handle(mirror);
6664 }
6665 
6666 void MacroAssembler::load_klass(Register dst, Register src) {
6667 #ifdef _LP64
6668   if (UseCompressedClassPointers) {
6669     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6670     decode_klass_not_null(dst);
6671   } else
6672 #endif
6673     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6674 }
6675 
6676 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6677   load_klass(dst, src);
6678   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6679 }
6680 
6681 void MacroAssembler::store_klass(Register dst, Register src) {
6682 #ifdef _LP64
6683   if (UseCompressedClassPointers) {
6684     encode_klass_not_null(src);
6685     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6686   } else
6687 #endif
6688     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6689 }
6690 
6691 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6692 #ifdef _LP64
6693   // FIXME: Must change all places where we try to load the klass.
6694   if (UseCompressedOops) {
6695     movl(dst, src);
6696     decode_heap_oop(dst);
6697   } else
6698 #endif
6699     movptr(dst, src);
6700 }
6701 
6702 // Doesn't do verfication, generates fixed size code
6703 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6704 #ifdef _LP64
6705   if (UseCompressedOops) {
6706     movl(dst, src);
6707     decode_heap_oop_not_null(dst);
6708   } else
6709 #endif
6710     movptr(dst, src);
6711 }
6712 
6713 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6714 #ifdef _LP64
6715   if (UseCompressedOops) {
6716     assert(!dst.uses(src), "not enough registers");
6717     encode_heap_oop(src);
6718     movl(dst, src);
6719   } else
6720 #endif
6721     movptr(dst, src);
6722 }
6723 
6724 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6725   assert_different_registers(src1, tmp);
6726 #ifdef _LP64
6727   if (UseCompressedOops) {
6728     bool did_push = false;
6729     if (tmp == noreg) {
6730       tmp = rax;
6731       push(tmp);
6732       did_push = true;
6733       assert(!src2.uses(rsp), "can't push");
6734     }
6735     load_heap_oop(tmp, src2);
6736     cmpptr(src1, tmp);
6737     if (did_push)  pop(tmp);
6738   } else
6739 #endif
6740     cmpptr(src1, src2);
6741 }
6742 
6743 // Used for storing NULLs.
6744 void MacroAssembler::store_heap_oop_null(Address dst) {
6745 #ifdef _LP64
6746   if (UseCompressedOops) {
6747     movl(dst, (int32_t)NULL_WORD);
6748   } else {
6749     movslq(dst, (int32_t)NULL_WORD);
6750   }
6751 #else
6752   movl(dst, (int32_t)NULL_WORD);
6753 #endif
6754 }
6755 
6756 #ifdef _LP64
6757 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6758   if (UseCompressedClassPointers) {
6759     // Store to klass gap in destination
6760     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6761   }
6762 }
6763 
6764 #ifdef ASSERT
6765 void MacroAssembler::verify_heapbase(const char* msg) {
6766   assert (UseCompressedOops, "should be compressed");
6767   assert (Universe::heap() != NULL, "java heap should be initialized");
6768   if (CheckCompressedOops) {
6769     Label ok;
6770     push(rscratch1); // cmpptr trashes rscratch1
6771     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6772     jcc(Assembler::equal, ok);
6773     STOP(msg);
6774     bind(ok);
6775     pop(rscratch1);
6776   }
6777 }
6778 #endif
6779 
6780 // Algorithm must match oop.inline.hpp encode_heap_oop.
6781 void MacroAssembler::encode_heap_oop(Register r) {
6782 #ifdef ASSERT
6783   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6784 #endif
6785   verify_oop(r, "broken oop in encode_heap_oop");
6786   if (Universe::narrow_oop_base() == NULL) {
6787     if (Universe::narrow_oop_shift() != 0) {
6788       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6789       shrq(r, LogMinObjAlignmentInBytes);
6790     }
6791     return;
6792   }
6793   testq(r, r);
6794   cmovq(Assembler::equal, r, r12_heapbase);
6795   subq(r, r12_heapbase);
6796   shrq(r, LogMinObjAlignmentInBytes);
6797 }
6798 
6799 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6800 #ifdef ASSERT
6801   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6802   if (CheckCompressedOops) {
6803     Label ok;
6804     testq(r, r);
6805     jcc(Assembler::notEqual, ok);
6806     STOP("null oop passed to encode_heap_oop_not_null");
6807     bind(ok);
6808   }
6809 #endif
6810   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6811   if (Universe::narrow_oop_base() != NULL) {
6812     subq(r, r12_heapbase);
6813   }
6814   if (Universe::narrow_oop_shift() != 0) {
6815     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6816     shrq(r, LogMinObjAlignmentInBytes);
6817   }
6818 }
6819 
6820 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6821 #ifdef ASSERT
6822   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6823   if (CheckCompressedOops) {
6824     Label ok;
6825     testq(src, src);
6826     jcc(Assembler::notEqual, ok);
6827     STOP("null oop passed to encode_heap_oop_not_null2");
6828     bind(ok);
6829   }
6830 #endif
6831   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6832   if (dst != src) {
6833     movq(dst, src);
6834   }
6835   if (Universe::narrow_oop_base() != NULL) {
6836     subq(dst, r12_heapbase);
6837   }
6838   if (Universe::narrow_oop_shift() != 0) {
6839     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6840     shrq(dst, LogMinObjAlignmentInBytes);
6841   }
6842 }
6843 
6844 void  MacroAssembler::decode_heap_oop(Register r) {
6845 #ifdef ASSERT
6846   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6847 #endif
6848   if (Universe::narrow_oop_base() == NULL) {
6849     if (Universe::narrow_oop_shift() != 0) {
6850       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6851       shlq(r, LogMinObjAlignmentInBytes);
6852     }
6853   } else {
6854     Label done;
6855     shlq(r, LogMinObjAlignmentInBytes);
6856     jccb(Assembler::equal, done);
6857     addq(r, r12_heapbase);
6858     bind(done);
6859   }
6860   verify_oop(r, "broken oop in decode_heap_oop");
6861 }
6862 
6863 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6864   // Note: it will change flags
6865   assert (UseCompressedOops, "should only be used for compressed headers");
6866   assert (Universe::heap() != NULL, "java heap should be initialized");
6867   // Cannot assert, unverified entry point counts instructions (see .ad file)
6868   // vtableStubs also counts instructions in pd_code_size_limit.
6869   // Also do not verify_oop as this is called by verify_oop.
6870   if (Universe::narrow_oop_shift() != 0) {
6871     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6872     shlq(r, LogMinObjAlignmentInBytes);
6873     if (Universe::narrow_oop_base() != NULL) {
6874       addq(r, r12_heapbase);
6875     }
6876   } else {
6877     assert (Universe::narrow_oop_base() == NULL, "sanity");
6878   }
6879 }
6880 
6881 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6882   // Note: it will change flags
6883   assert (UseCompressedOops, "should only be used for compressed headers");
6884   assert (Universe::heap() != NULL, "java heap should be initialized");
6885   // Cannot assert, unverified entry point counts instructions (see .ad file)
6886   // vtableStubs also counts instructions in pd_code_size_limit.
6887   // Also do not verify_oop as this is called by verify_oop.
6888   if (Universe::narrow_oop_shift() != 0) {
6889     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6890     if (LogMinObjAlignmentInBytes == Address::times_8) {
6891       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6892     } else {
6893       if (dst != src) {
6894         movq(dst, src);
6895       }
6896       shlq(dst, LogMinObjAlignmentInBytes);
6897       if (Universe::narrow_oop_base() != NULL) {
6898         addq(dst, r12_heapbase);
6899       }
6900     }
6901   } else {
6902     assert (Universe::narrow_oop_base() == NULL, "sanity");
6903     if (dst != src) {
6904       movq(dst, src);
6905     }
6906   }
6907 }
6908 
6909 void MacroAssembler::encode_klass_not_null(Register r) {
6910   if (Universe::narrow_klass_base() != NULL) {
6911     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6912     assert(r != r12_heapbase, "Encoding a klass in r12");
6913     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6914     subq(r, r12_heapbase);
6915   }
6916   if (Universe::narrow_klass_shift() != 0) {
6917     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6918     shrq(r, LogKlassAlignmentInBytes);
6919   }
6920   if (Universe::narrow_klass_base() != NULL) {
6921     reinit_heapbase();
6922   }
6923 }
6924 
6925 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6926   if (dst == src) {
6927     encode_klass_not_null(src);
6928   } else {
6929     if (Universe::narrow_klass_base() != NULL) {
6930       mov64(dst, (int64_t)Universe::narrow_klass_base());
6931       negq(dst);
6932       addq(dst, src);
6933     } else {
6934       movptr(dst, src);
6935     }
6936     if (Universe::narrow_klass_shift() != 0) {
6937       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6938       shrq(dst, LogKlassAlignmentInBytes);
6939     }
6940   }
6941 }
6942 
6943 // Function instr_size_for_decode_klass_not_null() counts the instructions
6944 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6945 // when (Universe::heap() != NULL).  Hence, if the instructions they
6946 // generate change, then this method needs to be updated.
6947 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6948   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6949   if (Universe::narrow_klass_base() != NULL) {
6950     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6951     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6952   } else {
6953     // longest load decode klass function, mov64, leaq
6954     return 16;
6955   }
6956 }
6957 
6958 // !!! If the instructions that get generated here change then function
6959 // instr_size_for_decode_klass_not_null() needs to get updated.
6960 void  MacroAssembler::decode_klass_not_null(Register r) {
6961   // Note: it will change flags
6962   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6963   assert(r != r12_heapbase, "Decoding a klass in r12");
6964   // Cannot assert, unverified entry point counts instructions (see .ad file)
6965   // vtableStubs also counts instructions in pd_code_size_limit.
6966   // Also do not verify_oop as this is called by verify_oop.
6967   if (Universe::narrow_klass_shift() != 0) {
6968     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6969     shlq(r, LogKlassAlignmentInBytes);
6970   }
6971   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6972   if (Universe::narrow_klass_base() != NULL) {
6973     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6974     addq(r, r12_heapbase);
6975     reinit_heapbase();
6976   }
6977 }
6978 
6979 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6980   // Note: it will change flags
6981   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6982   if (dst == src) {
6983     decode_klass_not_null(dst);
6984   } else {
6985     // Cannot assert, unverified entry point counts instructions (see .ad file)
6986     // vtableStubs also counts instructions in pd_code_size_limit.
6987     // Also do not verify_oop as this is called by verify_oop.
6988     mov64(dst, (int64_t)Universe::narrow_klass_base());
6989     if (Universe::narrow_klass_shift() != 0) {
6990       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6991       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6992       leaq(dst, Address(dst, src, Address::times_8, 0));
6993     } else {
6994       addq(dst, src);
6995     }
6996   }
6997 }
6998 
6999 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
7000   assert (UseCompressedOops, "should only be used for compressed headers");
7001   assert (Universe::heap() != NULL, "java heap should be initialized");
7002   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7003   int oop_index = oop_recorder()->find_index(obj);
7004   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7005   mov_narrow_oop(dst, oop_index, rspec);
7006 }
7007 
7008 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
7009   assert (UseCompressedOops, "should only be used for compressed headers");
7010   assert (Universe::heap() != NULL, "java heap should be initialized");
7011   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7012   int oop_index = oop_recorder()->find_index(obj);
7013   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7014   mov_narrow_oop(dst, oop_index, rspec);
7015 }
7016 
7017 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
7018   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7019   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7020   int klass_index = oop_recorder()->find_index(k);
7021   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7022   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7023 }
7024 
7025 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7026   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7027   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7028   int klass_index = oop_recorder()->find_index(k);
7029   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7030   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7031 }
7032 
7033 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7034   assert (UseCompressedOops, "should only be used for compressed headers");
7035   assert (Universe::heap() != NULL, "java heap should be initialized");
7036   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7037   int oop_index = oop_recorder()->find_index(obj);
7038   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7039   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7040 }
7041 
7042 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7043   assert (UseCompressedOops, "should only be used for compressed headers");
7044   assert (Universe::heap() != NULL, "java heap should be initialized");
7045   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7046   int oop_index = oop_recorder()->find_index(obj);
7047   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7048   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7049 }
7050 
7051 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7052   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7053   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7054   int klass_index = oop_recorder()->find_index(k);
7055   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7056   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7057 }
7058 
7059 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7060   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7061   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7062   int klass_index = oop_recorder()->find_index(k);
7063   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7064   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7065 }
7066 
7067 void MacroAssembler::reinit_heapbase() {
7068   if (UseCompressedOops || UseCompressedClassPointers) {
7069     if (Universe::heap() != NULL) {
7070       if (Universe::narrow_oop_base() == NULL) {
7071         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7072       } else {
7073         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7074       }
7075     } else {
7076       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7077     }
7078   }
7079 }
7080 
7081 #endif // _LP64
7082 
7083 // C2 compiled method's prolog code.
7084 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7085 
7086   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7087   // NativeJump::patch_verified_entry will be able to patch out the entry
7088   // code safely. The push to verify stack depth is ok at 5 bytes,
7089   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7090   // stack bang then we must use the 6 byte frame allocation even if
7091   // we have no frame. :-(
7092   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7093 
7094   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7095   // Remove word for return addr
7096   framesize -= wordSize;
7097   stack_bang_size -= wordSize;
7098 
7099   // Calls to C2R adapters often do not accept exceptional returns.
7100   // We require that their callers must bang for them.  But be careful, because
7101   // some VM calls (such as call site linkage) can use several kilobytes of
7102   // stack.  But the stack safety zone should account for that.
7103   // See bugs 4446381, 4468289, 4497237.
7104   if (stack_bang_size > 0) {
7105     generate_stack_overflow_check(stack_bang_size);
7106 
7107     // We always push rbp, so that on return to interpreter rbp, will be
7108     // restored correctly and we can correct the stack.
7109     push(rbp);
7110     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7111     if (PreserveFramePointer) {
7112       mov(rbp, rsp);
7113     }
7114     // Remove word for ebp
7115     framesize -= wordSize;
7116 
7117     // Create frame
7118     if (framesize) {
7119       subptr(rsp, framesize);
7120     }
7121   } else {
7122     // Create frame (force generation of a 4 byte immediate value)
7123     subptr_imm32(rsp, framesize);
7124 
7125     // Save RBP register now.
7126     framesize -= wordSize;
7127     movptr(Address(rsp, framesize), rbp);
7128     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7129     if (PreserveFramePointer) {
7130       movptr(rbp, rsp);
7131       if (framesize > 0) {
7132         addptr(rbp, framesize);
7133       }
7134     }
7135   }
7136 
7137   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7138     framesize -= wordSize;
7139     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7140   }
7141 
7142 #ifndef _LP64
7143   // If method sets FPU control word do it now
7144   if (fp_mode_24b) {
7145     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7146   }
7147   if (UseSSE >= 2 && VerifyFPU) {
7148     verify_FPU(0, "FPU stack must be clean on entry");
7149   }
7150 #endif
7151 
7152 #ifdef ASSERT
7153   if (VerifyStackAtCalls) {
7154     Label L;
7155     push(rax);
7156     mov(rax, rsp);
7157     andptr(rax, StackAlignmentInBytes-1);
7158     cmpptr(rax, StackAlignmentInBytes-wordSize);
7159     pop(rax);
7160     jcc(Assembler::equal, L);
7161     STOP("Stack is not properly aligned!");
7162     bind(L);
7163   }
7164 #endif
7165 
7166 }
7167 
7168 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
7169   // cnt - number of qwords (8-byte words).
7170   // base - start address, qword aligned.
7171   // is_large - if optimizers know cnt is larger than InitArrayShortSize
7172   assert(base==rdi, "base register must be edi for rep stos");
7173   assert(tmp==rax,   "tmp register must be eax for rep stos");
7174   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7175   assert(InitArrayShortSize % BytesPerLong == 0,
7176     "InitArrayShortSize should be the multiple of BytesPerLong");
7177 
7178   Label DONE;
7179 
7180   xorptr(tmp, tmp);
7181 
7182   if (!is_large) {
7183     Label LOOP, LONG;
7184     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7185     jccb(Assembler::greater, LONG);
7186 
7187     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7188 
7189     decrement(cnt);
7190     jccb(Assembler::negative, DONE); // Zero length
7191 
7192     // Use individual pointer-sized stores for small counts:
7193     BIND(LOOP);
7194     movptr(Address(base, cnt, Address::times_ptr), tmp);
7195     decrement(cnt);
7196     jccb(Assembler::greaterEqual, LOOP);
7197     jmpb(DONE);
7198 
7199     BIND(LONG);
7200   }
7201 
7202   // Use longer rep-prefixed ops for non-small counts:
7203   if (UseFastStosb) {
7204     shlptr(cnt, 3); // convert to number of bytes
7205     rep_stosb();
7206   } else {
7207     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7208     rep_stos();
7209   }
7210 
7211   BIND(DONE);
7212 }
7213 
7214 #ifdef COMPILER2
7215 
7216 // IndexOf for constant substrings with size >= 8 chars
7217 // which don't need to be loaded through stack.
7218 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7219                                       Register cnt1, Register cnt2,
7220                                       int int_cnt2,  Register result,
7221                                       XMMRegister vec, Register tmp,
7222                                       int ae) {
7223   ShortBranchVerifier sbv(this);
7224   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7225   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7226 
7227   // This method uses the pcmpestri instruction with bound registers
7228   //   inputs:
7229   //     xmm - substring
7230   //     rax - substring length (elements count)
7231   //     mem - scanned string
7232   //     rdx - string length (elements count)
7233   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7234   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7235   //   outputs:
7236   //     rcx - matched index in string
7237   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7238   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7239   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7240   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7241   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7242 
7243   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7244         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7245         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7246 
7247   // Note, inline_string_indexOf() generates checks:
7248   // if (substr.count > string.count) return -1;
7249   // if (substr.count == 0) return 0;
7250   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7251 
7252   // Load substring.
7253   if (ae == StrIntrinsicNode::UL) {
7254     pmovzxbw(vec, Address(str2, 0));
7255   } else {
7256     movdqu(vec, Address(str2, 0));
7257   }
7258   movl(cnt2, int_cnt2);
7259   movptr(result, str1); // string addr
7260 
7261   if (int_cnt2 > stride) {
7262     jmpb(SCAN_TO_SUBSTR);
7263 
7264     // Reload substr for rescan, this code
7265     // is executed only for large substrings (> 8 chars)
7266     bind(RELOAD_SUBSTR);
7267     if (ae == StrIntrinsicNode::UL) {
7268       pmovzxbw(vec, Address(str2, 0));
7269     } else {
7270       movdqu(vec, Address(str2, 0));
7271     }
7272     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7273 
7274     bind(RELOAD_STR);
7275     // We came here after the beginning of the substring was
7276     // matched but the rest of it was not so we need to search
7277     // again. Start from the next element after the previous match.
7278 
7279     // cnt2 is number of substring reminding elements and
7280     // cnt1 is number of string reminding elements when cmp failed.
7281     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7282     subl(cnt1, cnt2);
7283     addl(cnt1, int_cnt2);
7284     movl(cnt2, int_cnt2); // Now restore cnt2
7285 
7286     decrementl(cnt1);     // Shift to next element
7287     cmpl(cnt1, cnt2);
7288     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7289 
7290     addptr(result, (1<<scale1));
7291 
7292   } // (int_cnt2 > 8)
7293 
7294   // Scan string for start of substr in 16-byte vectors
7295   bind(SCAN_TO_SUBSTR);
7296   pcmpestri(vec, Address(result, 0), mode);
7297   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7298   subl(cnt1, stride);
7299   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7300   cmpl(cnt1, cnt2);
7301   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7302   addptr(result, 16);
7303   jmpb(SCAN_TO_SUBSTR);
7304 
7305   // Found a potential substr
7306   bind(FOUND_CANDIDATE);
7307   // Matched whole vector if first element matched (tmp(rcx) == 0).
7308   if (int_cnt2 == stride) {
7309     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7310   } else { // int_cnt2 > 8
7311     jccb(Assembler::overflow, FOUND_SUBSTR);
7312   }
7313   // After pcmpestri tmp(rcx) contains matched element index
7314   // Compute start addr of substr
7315   lea(result, Address(result, tmp, scale1));
7316 
7317   // Make sure string is still long enough
7318   subl(cnt1, tmp);
7319   cmpl(cnt1, cnt2);
7320   if (int_cnt2 == stride) {
7321     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7322   } else { // int_cnt2 > 8
7323     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7324   }
7325   // Left less then substring.
7326 
7327   bind(RET_NOT_FOUND);
7328   movl(result, -1);
7329   jmp(EXIT);
7330 
7331   if (int_cnt2 > stride) {
7332     // This code is optimized for the case when whole substring
7333     // is matched if its head is matched.
7334     bind(MATCH_SUBSTR_HEAD);
7335     pcmpestri(vec, Address(result, 0), mode);
7336     // Reload only string if does not match
7337     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7338 
7339     Label CONT_SCAN_SUBSTR;
7340     // Compare the rest of substring (> 8 chars).
7341     bind(FOUND_SUBSTR);
7342     // First 8 chars are already matched.
7343     negptr(cnt2);
7344     addptr(cnt2, stride);
7345 
7346     bind(SCAN_SUBSTR);
7347     subl(cnt1, stride);
7348     cmpl(cnt2, -stride); // Do not read beyond substring
7349     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7350     // Back-up strings to avoid reading beyond substring:
7351     // cnt1 = cnt1 - cnt2 + 8
7352     addl(cnt1, cnt2); // cnt2 is negative
7353     addl(cnt1, stride);
7354     movl(cnt2, stride); negptr(cnt2);
7355     bind(CONT_SCAN_SUBSTR);
7356     if (int_cnt2 < (int)G) {
7357       int tail_off1 = int_cnt2<<scale1;
7358       int tail_off2 = int_cnt2<<scale2;
7359       if (ae == StrIntrinsicNode::UL) {
7360         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7361       } else {
7362         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7363       }
7364       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7365     } else {
7366       // calculate index in register to avoid integer overflow (int_cnt2*2)
7367       movl(tmp, int_cnt2);
7368       addptr(tmp, cnt2);
7369       if (ae == StrIntrinsicNode::UL) {
7370         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7371       } else {
7372         movdqu(vec, Address(str2, tmp, scale2, 0));
7373       }
7374       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7375     }
7376     // Need to reload strings pointers if not matched whole vector
7377     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7378     addptr(cnt2, stride);
7379     jcc(Assembler::negative, SCAN_SUBSTR);
7380     // Fall through if found full substring
7381 
7382   } // (int_cnt2 > 8)
7383 
7384   bind(RET_FOUND);
7385   // Found result if we matched full small substring.
7386   // Compute substr offset
7387   subptr(result, str1);
7388   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7389     shrl(result, 1); // index
7390   }
7391   bind(EXIT);
7392 
7393 } // string_indexofC8
7394 
7395 // Small strings are loaded through stack if they cross page boundary.
7396 void MacroAssembler::string_indexof(Register str1, Register str2,
7397                                     Register cnt1, Register cnt2,
7398                                     int int_cnt2,  Register result,
7399                                     XMMRegister vec, Register tmp,
7400                                     int ae) {
7401   ShortBranchVerifier sbv(this);
7402   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7403   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7404 
7405   //
7406   // int_cnt2 is length of small (< 8 chars) constant substring
7407   // or (-1) for non constant substring in which case its length
7408   // is in cnt2 register.
7409   //
7410   // Note, inline_string_indexOf() generates checks:
7411   // if (substr.count > string.count) return -1;
7412   // if (substr.count == 0) return 0;
7413   //
7414   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7415   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7416   // This method uses the pcmpestri instruction with bound registers
7417   //   inputs:
7418   //     xmm - substring
7419   //     rax - substring length (elements count)
7420   //     mem - scanned string
7421   //     rdx - string length (elements count)
7422   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7423   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7424   //   outputs:
7425   //     rcx - matched index in string
7426   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7427   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7428   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7429   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7430 
7431   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7432         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7433         FOUND_CANDIDATE;
7434 
7435   { //========================================================
7436     // We don't know where these strings are located
7437     // and we can't read beyond them. Load them through stack.
7438     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7439 
7440     movptr(tmp, rsp); // save old SP
7441 
7442     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7443       if (int_cnt2 == (1>>scale2)) { // One byte
7444         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7445         load_unsigned_byte(result, Address(str2, 0));
7446         movdl(vec, result); // move 32 bits
7447       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7448         // Not enough header space in 32-bit VM: 12+3 = 15.
7449         movl(result, Address(str2, -1));
7450         shrl(result, 8);
7451         movdl(vec, result); // move 32 bits
7452       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7453         load_unsigned_short(result, Address(str2, 0));
7454         movdl(vec, result); // move 32 bits
7455       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7456         movdl(vec, Address(str2, 0)); // move 32 bits
7457       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7458         movq(vec, Address(str2, 0));  // move 64 bits
7459       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7460         // Array header size is 12 bytes in 32-bit VM
7461         // + 6 bytes for 3 chars == 18 bytes,
7462         // enough space to load vec and shift.
7463         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7464         if (ae == StrIntrinsicNode::UL) {
7465           int tail_off = int_cnt2-8;
7466           pmovzxbw(vec, Address(str2, tail_off));
7467           psrldq(vec, -2*tail_off);
7468         }
7469         else {
7470           int tail_off = int_cnt2*(1<<scale2);
7471           movdqu(vec, Address(str2, tail_off-16));
7472           psrldq(vec, 16-tail_off);
7473         }
7474       }
7475     } else { // not constant substring
7476       cmpl(cnt2, stride);
7477       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7478 
7479       // We can read beyond string if srt+16 does not cross page boundary
7480       // since heaps are aligned and mapped by pages.
7481       assert(os::vm_page_size() < (int)G, "default page should be small");
7482       movl(result, str2); // We need only low 32 bits
7483       andl(result, (os::vm_page_size()-1));
7484       cmpl(result, (os::vm_page_size()-16));
7485       jccb(Assembler::belowEqual, CHECK_STR);
7486 
7487       // Move small strings to stack to allow load 16 bytes into vec.
7488       subptr(rsp, 16);
7489       int stk_offset = wordSize-(1<<scale2);
7490       push(cnt2);
7491 
7492       bind(COPY_SUBSTR);
7493       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7494         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7495         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7496       } else if (ae == StrIntrinsicNode::UU) {
7497         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7498         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7499       }
7500       decrement(cnt2);
7501       jccb(Assembler::notZero, COPY_SUBSTR);
7502 
7503       pop(cnt2);
7504       movptr(str2, rsp);  // New substring address
7505     } // non constant
7506 
7507     bind(CHECK_STR);
7508     cmpl(cnt1, stride);
7509     jccb(Assembler::aboveEqual, BIG_STRINGS);
7510 
7511     // Check cross page boundary.
7512     movl(result, str1); // We need only low 32 bits
7513     andl(result, (os::vm_page_size()-1));
7514     cmpl(result, (os::vm_page_size()-16));
7515     jccb(Assembler::belowEqual, BIG_STRINGS);
7516 
7517     subptr(rsp, 16);
7518     int stk_offset = -(1<<scale1);
7519     if (int_cnt2 < 0) { // not constant
7520       push(cnt2);
7521       stk_offset += wordSize;
7522     }
7523     movl(cnt2, cnt1);
7524 
7525     bind(COPY_STR);
7526     if (ae == StrIntrinsicNode::LL) {
7527       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7528       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7529     } else {
7530       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7531       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7532     }
7533     decrement(cnt2);
7534     jccb(Assembler::notZero, COPY_STR);
7535 
7536     if (int_cnt2 < 0) { // not constant
7537       pop(cnt2);
7538     }
7539     movptr(str1, rsp);  // New string address
7540 
7541     bind(BIG_STRINGS);
7542     // Load substring.
7543     if (int_cnt2 < 0) { // -1
7544       if (ae == StrIntrinsicNode::UL) {
7545         pmovzxbw(vec, Address(str2, 0));
7546       } else {
7547         movdqu(vec, Address(str2, 0));
7548       }
7549       push(cnt2);       // substr count
7550       push(str2);       // substr addr
7551       push(str1);       // string addr
7552     } else {
7553       // Small (< 8 chars) constant substrings are loaded already.
7554       movl(cnt2, int_cnt2);
7555     }
7556     push(tmp);  // original SP
7557 
7558   } // Finished loading
7559 
7560   //========================================================
7561   // Start search
7562   //
7563 
7564   movptr(result, str1); // string addr
7565 
7566   if (int_cnt2  < 0) {  // Only for non constant substring
7567     jmpb(SCAN_TO_SUBSTR);
7568 
7569     // SP saved at sp+0
7570     // String saved at sp+1*wordSize
7571     // Substr saved at sp+2*wordSize
7572     // Substr count saved at sp+3*wordSize
7573 
7574     // Reload substr for rescan, this code
7575     // is executed only for large substrings (> 8 chars)
7576     bind(RELOAD_SUBSTR);
7577     movptr(str2, Address(rsp, 2*wordSize));
7578     movl(cnt2, Address(rsp, 3*wordSize));
7579     if (ae == StrIntrinsicNode::UL) {
7580       pmovzxbw(vec, Address(str2, 0));
7581     } else {
7582       movdqu(vec, Address(str2, 0));
7583     }
7584     // We came here after the beginning of the substring was
7585     // matched but the rest of it was not so we need to search
7586     // again. Start from the next element after the previous match.
7587     subptr(str1, result); // Restore counter
7588     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7589       shrl(str1, 1);
7590     }
7591     addl(cnt1, str1);
7592     decrementl(cnt1);   // Shift to next element
7593     cmpl(cnt1, cnt2);
7594     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7595 
7596     addptr(result, (1<<scale1));
7597   } // non constant
7598 
7599   // Scan string for start of substr in 16-byte vectors
7600   bind(SCAN_TO_SUBSTR);
7601   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7602   pcmpestri(vec, Address(result, 0), mode);
7603   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7604   subl(cnt1, stride);
7605   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7606   cmpl(cnt1, cnt2);
7607   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7608   addptr(result, 16);
7609 
7610   bind(ADJUST_STR);
7611   cmpl(cnt1, stride); // Do not read beyond string
7612   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7613   // Back-up string to avoid reading beyond string.
7614   lea(result, Address(result, cnt1, scale1, -16));
7615   movl(cnt1, stride);
7616   jmpb(SCAN_TO_SUBSTR);
7617 
7618   // Found a potential substr
7619   bind(FOUND_CANDIDATE);
7620   // After pcmpestri tmp(rcx) contains matched element index
7621 
7622   // Make sure string is still long enough
7623   subl(cnt1, tmp);
7624   cmpl(cnt1, cnt2);
7625   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7626   // Left less then substring.
7627 
7628   bind(RET_NOT_FOUND);
7629   movl(result, -1);
7630   jmpb(CLEANUP);
7631 
7632   bind(FOUND_SUBSTR);
7633   // Compute start addr of substr
7634   lea(result, Address(result, tmp, scale1));
7635   if (int_cnt2 > 0) { // Constant substring
7636     // Repeat search for small substring (< 8 chars)
7637     // from new point without reloading substring.
7638     // Have to check that we don't read beyond string.
7639     cmpl(tmp, stride-int_cnt2);
7640     jccb(Assembler::greater, ADJUST_STR);
7641     // Fall through if matched whole substring.
7642   } else { // non constant
7643     assert(int_cnt2 == -1, "should be != 0");
7644 
7645     addl(tmp, cnt2);
7646     // Found result if we matched whole substring.
7647     cmpl(tmp, stride);
7648     jccb(Assembler::lessEqual, RET_FOUND);
7649 
7650     // Repeat search for small substring (<= 8 chars)
7651     // from new point 'str1' without reloading substring.
7652     cmpl(cnt2, stride);
7653     // Have to check that we don't read beyond string.
7654     jccb(Assembler::lessEqual, ADJUST_STR);
7655 
7656     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7657     // Compare the rest of substring (> 8 chars).
7658     movptr(str1, result);
7659 
7660     cmpl(tmp, cnt2);
7661     // First 8 chars are already matched.
7662     jccb(Assembler::equal, CHECK_NEXT);
7663 
7664     bind(SCAN_SUBSTR);
7665     pcmpestri(vec, Address(str1, 0), mode);
7666     // Need to reload strings pointers if not matched whole vector
7667     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7668 
7669     bind(CHECK_NEXT);
7670     subl(cnt2, stride);
7671     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7672     addptr(str1, 16);
7673     if (ae == StrIntrinsicNode::UL) {
7674       addptr(str2, 8);
7675     } else {
7676       addptr(str2, 16);
7677     }
7678     subl(cnt1, stride);
7679     cmpl(cnt2, stride); // Do not read beyond substring
7680     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7681     // Back-up strings to avoid reading beyond substring.
7682 
7683     if (ae == StrIntrinsicNode::UL) {
7684       lea(str2, Address(str2, cnt2, scale2, -8));
7685       lea(str1, Address(str1, cnt2, scale1, -16));
7686     } else {
7687       lea(str2, Address(str2, cnt2, scale2, -16));
7688       lea(str1, Address(str1, cnt2, scale1, -16));
7689     }
7690     subl(cnt1, cnt2);
7691     movl(cnt2, stride);
7692     addl(cnt1, stride);
7693     bind(CONT_SCAN_SUBSTR);
7694     if (ae == StrIntrinsicNode::UL) {
7695       pmovzxbw(vec, Address(str2, 0));
7696     } else {
7697       movdqu(vec, Address(str2, 0));
7698     }
7699     jmp(SCAN_SUBSTR);
7700 
7701     bind(RET_FOUND_LONG);
7702     movptr(str1, Address(rsp, wordSize));
7703   } // non constant
7704 
7705   bind(RET_FOUND);
7706   // Compute substr offset
7707   subptr(result, str1);
7708   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7709     shrl(result, 1); // index
7710   }
7711   bind(CLEANUP);
7712   pop(rsp); // restore SP
7713 
7714 } // string_indexof
7715 
7716 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7717                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7718   ShortBranchVerifier sbv(this);
7719   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7720 
7721   int stride = 8;
7722 
7723   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7724         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7725         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7726         FOUND_SEQ_CHAR, DONE_LABEL;
7727 
7728   movptr(result, str1);
7729   if (UseAVX >= 2) {
7730     cmpl(cnt1, stride);
7731     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7732     cmpl(cnt1, 2*stride);
7733     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7734     movdl(vec1, ch);
7735     vpbroadcastw(vec1, vec1);
7736     vpxor(vec2, vec2);
7737     movl(tmp, cnt1);
7738     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7739     andl(cnt1,0x0000000F);  //tail count (in chars)
7740 
7741     bind(SCAN_TO_16_CHAR_LOOP);
7742     vmovdqu(vec3, Address(result, 0));
7743     vpcmpeqw(vec3, vec3, vec1, 1);
7744     vptest(vec2, vec3);
7745     jcc(Assembler::carryClear, FOUND_CHAR);
7746     addptr(result, 32);
7747     subl(tmp, 2*stride);
7748     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7749     jmp(SCAN_TO_8_CHAR);
7750     bind(SCAN_TO_8_CHAR_INIT);
7751     movdl(vec1, ch);
7752     pshuflw(vec1, vec1, 0x00);
7753     pshufd(vec1, vec1, 0);
7754     pxor(vec2, vec2);
7755   }
7756   bind(SCAN_TO_8_CHAR);
7757   cmpl(cnt1, stride);
7758   if (UseAVX >= 2) {
7759     jcc(Assembler::less, SCAN_TO_CHAR);
7760   } else {
7761     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7762     movdl(vec1, ch);
7763     pshuflw(vec1, vec1, 0x00);
7764     pshufd(vec1, vec1, 0);
7765     pxor(vec2, vec2);
7766   }
7767   movl(tmp, cnt1);
7768   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7769   andl(cnt1,0x00000007);  //tail count (in chars)
7770 
7771   bind(SCAN_TO_8_CHAR_LOOP);
7772   movdqu(vec3, Address(result, 0));
7773   pcmpeqw(vec3, vec1);
7774   ptest(vec2, vec3);
7775   jcc(Assembler::carryClear, FOUND_CHAR);
7776   addptr(result, 16);
7777   subl(tmp, stride);
7778   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7779   bind(SCAN_TO_CHAR);
7780   testl(cnt1, cnt1);
7781   jcc(Assembler::zero, RET_NOT_FOUND);
7782   bind(SCAN_TO_CHAR_LOOP);
7783   load_unsigned_short(tmp, Address(result, 0));
7784   cmpl(ch, tmp);
7785   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7786   addptr(result, 2);
7787   subl(cnt1, 1);
7788   jccb(Assembler::zero, RET_NOT_FOUND);
7789   jmp(SCAN_TO_CHAR_LOOP);
7790 
7791   bind(RET_NOT_FOUND);
7792   movl(result, -1);
7793   jmpb(DONE_LABEL);
7794 
7795   bind(FOUND_CHAR);
7796   if (UseAVX >= 2) {
7797     vpmovmskb(tmp, vec3);
7798   } else {
7799     pmovmskb(tmp, vec3);
7800   }
7801   bsfl(ch, tmp);
7802   addl(result, ch);
7803 
7804   bind(FOUND_SEQ_CHAR);
7805   subptr(result, str1);
7806   shrl(result, 1);
7807 
7808   bind(DONE_LABEL);
7809 } // string_indexof_char
7810 
7811 // helper function for string_compare
7812 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7813                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7814                                         Address::ScaleFactor scale2, Register index, int ae) {
7815   if (ae == StrIntrinsicNode::LL) {
7816     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7817     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7818   } else if (ae == StrIntrinsicNode::UU) {
7819     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7820     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7821   } else {
7822     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7823     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7824   }
7825 }
7826 
7827 // Compare strings, used for char[] and byte[].
7828 void MacroAssembler::string_compare(Register str1, Register str2,
7829                                     Register cnt1, Register cnt2, Register result,
7830                                     XMMRegister vec1, int ae) {
7831   ShortBranchVerifier sbv(this);
7832   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7833   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7834   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7835   int stride2x2 = 0x40;
7836   Address::ScaleFactor scale = Address::no_scale;
7837   Address::ScaleFactor scale1 = Address::no_scale;
7838   Address::ScaleFactor scale2 = Address::no_scale;
7839 
7840   if (ae != StrIntrinsicNode::LL) {
7841     stride2x2 = 0x20;
7842   }
7843 
7844   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7845     shrl(cnt2, 1);
7846   }
7847   // Compute the minimum of the string lengths and the
7848   // difference of the string lengths (stack).
7849   // Do the conditional move stuff
7850   movl(result, cnt1);
7851   subl(cnt1, cnt2);
7852   push(cnt1);
7853   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7854 
7855   // Is the minimum length zero?
7856   testl(cnt2, cnt2);
7857   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7858   if (ae == StrIntrinsicNode::LL) {
7859     // Load first bytes
7860     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7861     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7862   } else if (ae == StrIntrinsicNode::UU) {
7863     // Load first characters
7864     load_unsigned_short(result, Address(str1, 0));
7865     load_unsigned_short(cnt1, Address(str2, 0));
7866   } else {
7867     load_unsigned_byte(result, Address(str1, 0));
7868     load_unsigned_short(cnt1, Address(str2, 0));
7869   }
7870   subl(result, cnt1);
7871   jcc(Assembler::notZero,  POP_LABEL);
7872 
7873   if (ae == StrIntrinsicNode::UU) {
7874     // Divide length by 2 to get number of chars
7875     shrl(cnt2, 1);
7876   }
7877   cmpl(cnt2, 1);
7878   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7879 
7880   // Check if the strings start at the same location and setup scale and stride
7881   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7882     cmpptr(str1, str2);
7883     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7884     if (ae == StrIntrinsicNode::LL) {
7885       scale = Address::times_1;
7886       stride = 16;
7887     } else {
7888       scale = Address::times_2;
7889       stride = 8;
7890     }
7891   } else {
7892     scale1 = Address::times_1;
7893     scale2 = Address::times_2;
7894     // scale not used
7895     stride = 8;
7896   }
7897 
7898   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7899     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7900     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7901     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7902     Label COMPARE_TAIL_LONG;
7903     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7904 
7905     int pcmpmask = 0x19;
7906     if (ae == StrIntrinsicNode::LL) {
7907       pcmpmask &= ~0x01;
7908     }
7909 
7910     // Setup to compare 16-chars (32-bytes) vectors,
7911     // start from first character again because it has aligned address.
7912     if (ae == StrIntrinsicNode::LL) {
7913       stride2 = 32;
7914     } else {
7915       stride2 = 16;
7916     }
7917     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7918       adr_stride = stride << scale;
7919     } else {
7920       adr_stride1 = 8;  //stride << scale1;
7921       adr_stride2 = 16; //stride << scale2;
7922     }
7923 
7924     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7925     // rax and rdx are used by pcmpestri as elements counters
7926     movl(result, cnt2);
7927     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7928     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7929 
7930     // fast path : compare first 2 8-char vectors.
7931     bind(COMPARE_16_CHARS);
7932     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7933       movdqu(vec1, Address(str1, 0));
7934     } else {
7935       pmovzxbw(vec1, Address(str1, 0));
7936     }
7937     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7938     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7939 
7940     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7941       movdqu(vec1, Address(str1, adr_stride));
7942       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7943     } else {
7944       pmovzxbw(vec1, Address(str1, adr_stride1));
7945       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7946     }
7947     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7948     addl(cnt1, stride);
7949 
7950     // Compare the characters at index in cnt1
7951     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7952     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7953     subl(result, cnt2);
7954     jmp(POP_LABEL);
7955 
7956     // Setup the registers to start vector comparison loop
7957     bind(COMPARE_WIDE_VECTORS);
7958     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7959       lea(str1, Address(str1, result, scale));
7960       lea(str2, Address(str2, result, scale));
7961     } else {
7962       lea(str1, Address(str1, result, scale1));
7963       lea(str2, Address(str2, result, scale2));
7964     }
7965     subl(result, stride2);
7966     subl(cnt2, stride2);
7967     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7968     negptr(result);
7969 
7970     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7971     bind(COMPARE_WIDE_VECTORS_LOOP);
7972 
7973 #ifdef _LP64
7974     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7975       cmpl(cnt2, stride2x2);
7976       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7977       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7978       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7979 
7980       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7981       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7982         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7983         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7984       } else {
7985         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7986         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7987       }
7988       kortestql(k7, k7);
7989       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7990       addptr(result, stride2x2);  // update since we already compared at this addr
7991       subl(cnt2, stride2x2);      // and sub the size too
7992       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7993 
7994       vpxor(vec1, vec1);
7995       jmpb(COMPARE_WIDE_TAIL);
7996     }//if (VM_Version::supports_avx512vlbw())
7997 #endif // _LP64
7998 
7999 
8000     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8001     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8002       vmovdqu(vec1, Address(str1, result, scale));
8003       vpxor(vec1, Address(str2, result, scale));
8004     } else {
8005       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
8006       vpxor(vec1, Address(str2, result, scale2));
8007     }
8008     vptest(vec1, vec1);
8009     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
8010     addptr(result, stride2);
8011     subl(cnt2, stride2);
8012     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
8013     // clean upper bits of YMM registers
8014     vpxor(vec1, vec1);
8015 
8016     // compare wide vectors tail
8017     bind(COMPARE_WIDE_TAIL);
8018     testptr(result, result);
8019     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8020 
8021     movl(result, stride2);
8022     movl(cnt2, result);
8023     negptr(result);
8024     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8025 
8026     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8027     bind(VECTOR_NOT_EQUAL);
8028     // clean upper bits of YMM registers
8029     vpxor(vec1, vec1);
8030     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8031       lea(str1, Address(str1, result, scale));
8032       lea(str2, Address(str2, result, scale));
8033     } else {
8034       lea(str1, Address(str1, result, scale1));
8035       lea(str2, Address(str2, result, scale2));
8036     }
8037     jmp(COMPARE_16_CHARS);
8038 
8039     // Compare tail chars, length between 1 to 15 chars
8040     bind(COMPARE_TAIL_LONG);
8041     movl(cnt2, result);
8042     cmpl(cnt2, stride);
8043     jcc(Assembler::less, COMPARE_SMALL_STR);
8044 
8045     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8046       movdqu(vec1, Address(str1, 0));
8047     } else {
8048       pmovzxbw(vec1, Address(str1, 0));
8049     }
8050     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8051     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8052     subptr(cnt2, stride);
8053     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8054     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8055       lea(str1, Address(str1, result, scale));
8056       lea(str2, Address(str2, result, scale));
8057     } else {
8058       lea(str1, Address(str1, result, scale1));
8059       lea(str2, Address(str2, result, scale2));
8060     }
8061     negptr(cnt2);
8062     jmpb(WHILE_HEAD_LABEL);
8063 
8064     bind(COMPARE_SMALL_STR);
8065   } else if (UseSSE42Intrinsics) {
8066     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8067     int pcmpmask = 0x19;
8068     // Setup to compare 8-char (16-byte) vectors,
8069     // start from first character again because it has aligned address.
8070     movl(result, cnt2);
8071     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8072     if (ae == StrIntrinsicNode::LL) {
8073       pcmpmask &= ~0x01;
8074     }
8075     jcc(Assembler::zero, COMPARE_TAIL);
8076     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8077       lea(str1, Address(str1, result, scale));
8078       lea(str2, Address(str2, result, scale));
8079     } else {
8080       lea(str1, Address(str1, result, scale1));
8081       lea(str2, Address(str2, result, scale2));
8082     }
8083     negptr(result);
8084 
8085     // pcmpestri
8086     //   inputs:
8087     //     vec1- substring
8088     //     rax - negative string length (elements count)
8089     //     mem - scanned string
8090     //     rdx - string length (elements count)
8091     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8092     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8093     //   outputs:
8094     //     rcx - first mismatched element index
8095     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8096 
8097     bind(COMPARE_WIDE_VECTORS);
8098     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8099       movdqu(vec1, Address(str1, result, scale));
8100       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8101     } else {
8102       pmovzxbw(vec1, Address(str1, result, scale1));
8103       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8104     }
8105     // After pcmpestri cnt1(rcx) contains mismatched element index
8106 
8107     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8108     addptr(result, stride);
8109     subptr(cnt2, stride);
8110     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8111 
8112     // compare wide vectors tail
8113     testptr(result, result);
8114     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8115 
8116     movl(cnt2, stride);
8117     movl(result, stride);
8118     negptr(result);
8119     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8120       movdqu(vec1, Address(str1, result, scale));
8121       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8122     } else {
8123       pmovzxbw(vec1, Address(str1, result, scale1));
8124       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8125     }
8126     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8127 
8128     // Mismatched characters in the vectors
8129     bind(VECTOR_NOT_EQUAL);
8130     addptr(cnt1, result);
8131     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8132     subl(result, cnt2);
8133     jmpb(POP_LABEL);
8134 
8135     bind(COMPARE_TAIL); // limit is zero
8136     movl(cnt2, result);
8137     // Fallthru to tail compare
8138   }
8139   // Shift str2 and str1 to the end of the arrays, negate min
8140   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8141     lea(str1, Address(str1, cnt2, scale));
8142     lea(str2, Address(str2, cnt2, scale));
8143   } else {
8144     lea(str1, Address(str1, cnt2, scale1));
8145     lea(str2, Address(str2, cnt2, scale2));
8146   }
8147   decrementl(cnt2);  // first character was compared already
8148   negptr(cnt2);
8149 
8150   // Compare the rest of the elements
8151   bind(WHILE_HEAD_LABEL);
8152   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8153   subl(result, cnt1);
8154   jccb(Assembler::notZero, POP_LABEL);
8155   increment(cnt2);
8156   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8157 
8158   // Strings are equal up to min length.  Return the length difference.
8159   bind(LENGTH_DIFF_LABEL);
8160   pop(result);
8161   if (ae == StrIntrinsicNode::UU) {
8162     // Divide diff by 2 to get number of chars
8163     sarl(result, 1);
8164   }
8165   jmpb(DONE_LABEL);
8166 
8167 #ifdef _LP64
8168   if (VM_Version::supports_avx512vlbw()) {
8169 
8170     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8171 
8172     kmovql(cnt1, k7);
8173     notq(cnt1);
8174     bsfq(cnt2, cnt1);
8175     if (ae != StrIntrinsicNode::LL) {
8176       // Divide diff by 2 to get number of chars
8177       sarl(cnt2, 1);
8178     }
8179     addq(result, cnt2);
8180     if (ae == StrIntrinsicNode::LL) {
8181       load_unsigned_byte(cnt1, Address(str2, result));
8182       load_unsigned_byte(result, Address(str1, result));
8183     } else if (ae == StrIntrinsicNode::UU) {
8184       load_unsigned_short(cnt1, Address(str2, result, scale));
8185       load_unsigned_short(result, Address(str1, result, scale));
8186     } else {
8187       load_unsigned_short(cnt1, Address(str2, result, scale2));
8188       load_unsigned_byte(result, Address(str1, result, scale1));
8189     }
8190     subl(result, cnt1);
8191     jmpb(POP_LABEL);
8192   }//if (VM_Version::supports_avx512vlbw())
8193 #endif // _LP64
8194 
8195   // Discard the stored length difference
8196   bind(POP_LABEL);
8197   pop(cnt1);
8198 
8199   // That's it
8200   bind(DONE_LABEL);
8201   if(ae == StrIntrinsicNode::UL) {
8202     negl(result);
8203   }
8204 
8205 }
8206 
8207 // Search for Non-ASCII character (Negative byte value) in a byte array,
8208 // return true if it has any and false otherwise.
8209 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
8210 //   @HotSpotIntrinsicCandidate
8211 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
8212 //     for (int i = off; i < off + len; i++) {
8213 //       if (ba[i] < 0) {
8214 //         return true;
8215 //       }
8216 //     }
8217 //     return false;
8218 //   }
8219 void MacroAssembler::has_negatives(Register ary1, Register len,
8220   Register result, Register tmp1,
8221   XMMRegister vec1, XMMRegister vec2) {
8222   // rsi: byte array
8223   // rcx: len
8224   // rax: result
8225   ShortBranchVerifier sbv(this);
8226   assert_different_registers(ary1, len, result, tmp1);
8227   assert_different_registers(vec1, vec2);
8228   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8229 
8230   // len == 0
8231   testl(len, len);
8232   jcc(Assembler::zero, FALSE_LABEL);
8233 
8234   if ((UseAVX > 2) && // AVX512
8235     VM_Version::supports_avx512vlbw() &&
8236     VM_Version::supports_bmi2()) {
8237 
8238     set_vector_masking();  // opening of the stub context for programming mask registers
8239 
8240     Label test_64_loop, test_tail;
8241     Register tmp3_aliased = len;
8242 
8243     movl(tmp1, len);
8244     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
8245 
8246     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
8247     andl(len, ~(64 - 1));    // vector count (in chars)
8248     jccb(Assembler::zero, test_tail);
8249 
8250     lea(ary1, Address(ary1, len, Address::times_1));
8251     negptr(len);
8252 
8253     bind(test_64_loop);
8254     // Check whether our 64 elements of size byte contain negatives
8255     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
8256     kortestql(k2, k2);
8257     jcc(Assembler::notZero, TRUE_LABEL);
8258 
8259     addptr(len, 64);
8260     jccb(Assembler::notZero, test_64_loop);
8261 
8262 
8263     bind(test_tail);
8264     // bail out when there is nothing to be done
8265     testl(tmp1, -1);
8266     jcc(Assembler::zero, FALSE_LABEL);
8267 
8268     // Save k1
8269     kmovql(k3, k1);
8270 
8271     // ~(~0 << len) applied up to two times (for 32-bit scenario)
8272 #ifdef _LP64
8273     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
8274     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
8275     notq(tmp3_aliased);
8276     kmovql(k1, tmp3_aliased);
8277 #else
8278     Label k_init;
8279     jmp(k_init);
8280 
8281     // We could not read 64-bits from a general purpose register thus we move
8282     // data required to compose 64 1's to the instruction stream
8283     // We emit 64 byte wide series of elements from 0..63 which later on would
8284     // be used as a compare targets with tail count contained in tmp1 register.
8285     // Result would be a k1 register having tmp1 consecutive number or 1
8286     // counting from least significant bit.
8287     address tmp = pc();
8288     emit_int64(0x0706050403020100);
8289     emit_int64(0x0F0E0D0C0B0A0908);
8290     emit_int64(0x1716151413121110);
8291     emit_int64(0x1F1E1D1C1B1A1918);
8292     emit_int64(0x2726252423222120);
8293     emit_int64(0x2F2E2D2C2B2A2928);
8294     emit_int64(0x3736353433323130);
8295     emit_int64(0x3F3E3D3C3B3A3938);
8296 
8297     bind(k_init);
8298     lea(len, InternalAddress(tmp));
8299     // create mask to test for negative byte inside a vector
8300     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
8301     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
8302 
8303 #endif
8304     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
8305     ktestq(k2, k1);
8306     // Restore k1
8307     kmovql(k1, k3);
8308     jcc(Assembler::notZero, TRUE_LABEL);
8309 
8310     jmp(FALSE_LABEL);
8311 
8312     clear_vector_masking();   // closing of the stub context for programming mask registers
8313   } else {
8314     movl(result, len); // copy
8315 
8316     if (UseAVX == 2 && UseSSE >= 2) {
8317       // With AVX2, use 32-byte vector compare
8318       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8319 
8320       // Compare 32-byte vectors
8321       andl(result, 0x0000001f);  //   tail count (in bytes)
8322       andl(len, 0xffffffe0);   // vector count (in bytes)
8323       jccb(Assembler::zero, COMPARE_TAIL);
8324 
8325       lea(ary1, Address(ary1, len, Address::times_1));
8326       negptr(len);
8327 
8328       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8329       movdl(vec2, tmp1);
8330       vpbroadcastd(vec2, vec2);
8331 
8332       bind(COMPARE_WIDE_VECTORS);
8333       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8334       vptest(vec1, vec2);
8335       jccb(Assembler::notZero, TRUE_LABEL);
8336       addptr(len, 32);
8337       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8338 
8339       testl(result, result);
8340       jccb(Assembler::zero, FALSE_LABEL);
8341 
8342       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8343       vptest(vec1, vec2);
8344       jccb(Assembler::notZero, TRUE_LABEL);
8345       jmpb(FALSE_LABEL);
8346 
8347       bind(COMPARE_TAIL); // len is zero
8348       movl(len, result);
8349       // Fallthru to tail compare
8350     } else if (UseSSE42Intrinsics) {
8351       // With SSE4.2, use double quad vector compare
8352       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8353 
8354       // Compare 16-byte vectors
8355       andl(result, 0x0000000f);  //   tail count (in bytes)
8356       andl(len, 0xfffffff0);   // vector count (in bytes)
8357       jccb(Assembler::zero, COMPARE_TAIL);
8358 
8359       lea(ary1, Address(ary1, len, Address::times_1));
8360       negptr(len);
8361 
8362       movl(tmp1, 0x80808080);
8363       movdl(vec2, tmp1);
8364       pshufd(vec2, vec2, 0);
8365 
8366       bind(COMPARE_WIDE_VECTORS);
8367       movdqu(vec1, Address(ary1, len, Address::times_1));
8368       ptest(vec1, vec2);
8369       jccb(Assembler::notZero, TRUE_LABEL);
8370       addptr(len, 16);
8371       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8372 
8373       testl(result, result);
8374       jccb(Assembler::zero, FALSE_LABEL);
8375 
8376       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8377       ptest(vec1, vec2);
8378       jccb(Assembler::notZero, TRUE_LABEL);
8379       jmpb(FALSE_LABEL);
8380 
8381       bind(COMPARE_TAIL); // len is zero
8382       movl(len, result);
8383       // Fallthru to tail compare
8384     }
8385   }
8386   // Compare 4-byte vectors
8387   andl(len, 0xfffffffc); // vector count (in bytes)
8388   jccb(Assembler::zero, COMPARE_CHAR);
8389 
8390   lea(ary1, Address(ary1, len, Address::times_1));
8391   negptr(len);
8392 
8393   bind(COMPARE_VECTORS);
8394   movl(tmp1, Address(ary1, len, Address::times_1));
8395   andl(tmp1, 0x80808080);
8396   jccb(Assembler::notZero, TRUE_LABEL);
8397   addptr(len, 4);
8398   jcc(Assembler::notZero, COMPARE_VECTORS);
8399 
8400   // Compare trailing char (final 2 bytes), if any
8401   bind(COMPARE_CHAR);
8402   testl(result, 0x2);   // tail  char
8403   jccb(Assembler::zero, COMPARE_BYTE);
8404   load_unsigned_short(tmp1, Address(ary1, 0));
8405   andl(tmp1, 0x00008080);
8406   jccb(Assembler::notZero, TRUE_LABEL);
8407   subptr(result, 2);
8408   lea(ary1, Address(ary1, 2));
8409 
8410   bind(COMPARE_BYTE);
8411   testl(result, 0x1);   // tail  byte
8412   jccb(Assembler::zero, FALSE_LABEL);
8413   load_unsigned_byte(tmp1, Address(ary1, 0));
8414   andl(tmp1, 0x00000080);
8415   jccb(Assembler::notEqual, TRUE_LABEL);
8416   jmpb(FALSE_LABEL);
8417 
8418   bind(TRUE_LABEL);
8419   movl(result, 1);   // return true
8420   jmpb(DONE);
8421 
8422   bind(FALSE_LABEL);
8423   xorl(result, result); // return false
8424 
8425   // That's it
8426   bind(DONE);
8427   if (UseAVX >= 2 && UseSSE >= 2) {
8428     // clean upper bits of YMM registers
8429     vpxor(vec1, vec1);
8430     vpxor(vec2, vec2);
8431   }
8432 }
8433 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8434 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8435                                    Register limit, Register result, Register chr,
8436                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8437   ShortBranchVerifier sbv(this);
8438   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8439 
8440   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8441   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8442 
8443   if (is_array_equ) {
8444     // Check the input args
8445     cmpoop(ary1, ary2);
8446     jcc(Assembler::equal, TRUE_LABEL);
8447 
8448     // Need additional checks for arrays_equals.
8449     testptr(ary1, ary1);
8450     jcc(Assembler::zero, FALSE_LABEL);
8451     testptr(ary2, ary2);
8452     jcc(Assembler::zero, FALSE_LABEL);
8453 
8454     // Check the lengths
8455     movl(limit, Address(ary1, length_offset));
8456     cmpl(limit, Address(ary2, length_offset));
8457     jcc(Assembler::notEqual, FALSE_LABEL);
8458   }
8459 
8460   // count == 0
8461   testl(limit, limit);
8462   jcc(Assembler::zero, TRUE_LABEL);
8463 
8464   if (is_array_equ) {
8465     // Load array address
8466     lea(ary1, Address(ary1, base_offset));
8467     lea(ary2, Address(ary2, base_offset));
8468   }
8469 
8470   if (is_array_equ && is_char) {
8471     // arrays_equals when used for char[].
8472     shll(limit, 1);      // byte count != 0
8473   }
8474   movl(result, limit); // copy
8475 
8476   if (UseAVX >= 2) {
8477     // With AVX2, use 32-byte vector compare
8478     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8479 
8480     // Compare 32-byte vectors
8481     andl(result, 0x0000001f);  //   tail count (in bytes)
8482     andl(limit, 0xffffffe0);   // vector count (in bytes)
8483     jcc(Assembler::zero, COMPARE_TAIL);
8484 
8485     lea(ary1, Address(ary1, limit, Address::times_1));
8486     lea(ary2, Address(ary2, limit, Address::times_1));
8487     negptr(limit);
8488 
8489     bind(COMPARE_WIDE_VECTORS);
8490 
8491 #ifdef _LP64
8492     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8493       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8494 
8495       cmpl(limit, -64);
8496       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8497 
8498       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8499 
8500       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8501       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8502       kortestql(k7, k7);
8503       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8504       addptr(limit, 64);  // update since we already compared at this addr
8505       cmpl(limit, -64);
8506       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8507 
8508       // At this point we may still need to compare -limit+result bytes.
8509       // We could execute the next two instruction and just continue via non-wide path:
8510       //  cmpl(limit, 0);
8511       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8512       // But since we stopped at the points ary{1,2}+limit which are
8513       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8514       // (|limit| <= 32 and result < 32),
8515       // we may just compare the last 64 bytes.
8516       //
8517       addptr(result, -64);   // it is safe, bc we just came from this area
8518       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8519       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8520       kortestql(k7, k7);
8521       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8522 
8523       jmp(TRUE_LABEL);
8524 
8525       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8526 
8527     }//if (VM_Version::supports_avx512vlbw())
8528 #endif //_LP64
8529 
8530     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8531     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8532     vpxor(vec1, vec2);
8533 
8534     vptest(vec1, vec1);
8535     jcc(Assembler::notZero, FALSE_LABEL);
8536     addptr(limit, 32);
8537     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8538 
8539     testl(result, result);
8540     jcc(Assembler::zero, TRUE_LABEL);
8541 
8542     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8543     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8544     vpxor(vec1, vec2);
8545 
8546     vptest(vec1, vec1);
8547     jccb(Assembler::notZero, FALSE_LABEL);
8548     jmpb(TRUE_LABEL);
8549 
8550     bind(COMPARE_TAIL); // limit is zero
8551     movl(limit, result);
8552     // Fallthru to tail compare
8553   } else if (UseSSE42Intrinsics) {
8554     // With SSE4.2, use double quad vector compare
8555     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8556 
8557     // Compare 16-byte vectors
8558     andl(result, 0x0000000f);  //   tail count (in bytes)
8559     andl(limit, 0xfffffff0);   // vector count (in bytes)
8560     jcc(Assembler::zero, COMPARE_TAIL);
8561 
8562     lea(ary1, Address(ary1, limit, Address::times_1));
8563     lea(ary2, Address(ary2, limit, Address::times_1));
8564     negptr(limit);
8565 
8566     bind(COMPARE_WIDE_VECTORS);
8567     movdqu(vec1, Address(ary1, limit, Address::times_1));
8568     movdqu(vec2, Address(ary2, limit, Address::times_1));
8569     pxor(vec1, vec2);
8570 
8571     ptest(vec1, vec1);
8572     jcc(Assembler::notZero, FALSE_LABEL);
8573     addptr(limit, 16);
8574     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8575 
8576     testl(result, result);
8577     jcc(Assembler::zero, TRUE_LABEL);
8578 
8579     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8580     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8581     pxor(vec1, vec2);
8582 
8583     ptest(vec1, vec1);
8584     jccb(Assembler::notZero, FALSE_LABEL);
8585     jmpb(TRUE_LABEL);
8586 
8587     bind(COMPARE_TAIL); // limit is zero
8588     movl(limit, result);
8589     // Fallthru to tail compare
8590   }
8591 
8592   // Compare 4-byte vectors
8593   andl(limit, 0xfffffffc); // vector count (in bytes)
8594   jccb(Assembler::zero, COMPARE_CHAR);
8595 
8596   lea(ary1, Address(ary1, limit, Address::times_1));
8597   lea(ary2, Address(ary2, limit, Address::times_1));
8598   negptr(limit);
8599 
8600   bind(COMPARE_VECTORS);
8601   movl(chr, Address(ary1, limit, Address::times_1));
8602   cmpl(chr, Address(ary2, limit, Address::times_1));
8603   jccb(Assembler::notEqual, FALSE_LABEL);
8604   addptr(limit, 4);
8605   jcc(Assembler::notZero, COMPARE_VECTORS);
8606 
8607   // Compare trailing char (final 2 bytes), if any
8608   bind(COMPARE_CHAR);
8609   testl(result, 0x2);   // tail  char
8610   jccb(Assembler::zero, COMPARE_BYTE);
8611   load_unsigned_short(chr, Address(ary1, 0));
8612   load_unsigned_short(limit, Address(ary2, 0));
8613   cmpl(chr, limit);
8614   jccb(Assembler::notEqual, FALSE_LABEL);
8615 
8616   if (is_array_equ && is_char) {
8617     bind(COMPARE_BYTE);
8618   } else {
8619     lea(ary1, Address(ary1, 2));
8620     lea(ary2, Address(ary2, 2));
8621 
8622     bind(COMPARE_BYTE);
8623     testl(result, 0x1);   // tail  byte
8624     jccb(Assembler::zero, TRUE_LABEL);
8625     load_unsigned_byte(chr, Address(ary1, 0));
8626     load_unsigned_byte(limit, Address(ary2, 0));
8627     cmpl(chr, limit);
8628     jccb(Assembler::notEqual, FALSE_LABEL);
8629   }
8630   bind(TRUE_LABEL);
8631   movl(result, 1);   // return true
8632   jmpb(DONE);
8633 
8634   bind(FALSE_LABEL);
8635   xorl(result, result); // return false
8636 
8637   // That's it
8638   bind(DONE);
8639   if (UseAVX >= 2) {
8640     // clean upper bits of YMM registers
8641     vpxor(vec1, vec1);
8642     vpxor(vec2, vec2);
8643   }
8644 }
8645 
8646 #endif
8647 
8648 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8649                                    Register to, Register value, Register count,
8650                                    Register rtmp, XMMRegister xtmp) {
8651   ShortBranchVerifier sbv(this);
8652   assert_different_registers(to, value, count, rtmp);
8653   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8654   Label L_fill_2_bytes, L_fill_4_bytes;
8655 
8656   int shift = -1;
8657   switch (t) {
8658     case T_BYTE:
8659       shift = 2;
8660       break;
8661     case T_SHORT:
8662       shift = 1;
8663       break;
8664     case T_INT:
8665       shift = 0;
8666       break;
8667     default: ShouldNotReachHere();
8668   }
8669 
8670   if (t == T_BYTE) {
8671     andl(value, 0xff);
8672     movl(rtmp, value);
8673     shll(rtmp, 8);
8674     orl(value, rtmp);
8675   }
8676   if (t == T_SHORT) {
8677     andl(value, 0xffff);
8678   }
8679   if (t == T_BYTE || t == T_SHORT) {
8680     movl(rtmp, value);
8681     shll(rtmp, 16);
8682     orl(value, rtmp);
8683   }
8684 
8685   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8686   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8687   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8688     // align source address at 4 bytes address boundary
8689     if (t == T_BYTE) {
8690       // One byte misalignment happens only for byte arrays
8691       testptr(to, 1);
8692       jccb(Assembler::zero, L_skip_align1);
8693       movb(Address(to, 0), value);
8694       increment(to);
8695       decrement(count);
8696       BIND(L_skip_align1);
8697     }
8698     // Two bytes misalignment happens only for byte and short (char) arrays
8699     testptr(to, 2);
8700     jccb(Assembler::zero, L_skip_align2);
8701     movw(Address(to, 0), value);
8702     addptr(to, 2);
8703     subl(count, 1<<(shift-1));
8704     BIND(L_skip_align2);
8705   }
8706   if (UseSSE < 2) {
8707     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8708     // Fill 32-byte chunks
8709     subl(count, 8 << shift);
8710     jcc(Assembler::less, L_check_fill_8_bytes);
8711     align(16);
8712 
8713     BIND(L_fill_32_bytes_loop);
8714 
8715     for (int i = 0; i < 32; i += 4) {
8716       movl(Address(to, i), value);
8717     }
8718 
8719     addptr(to, 32);
8720     subl(count, 8 << shift);
8721     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8722     BIND(L_check_fill_8_bytes);
8723     addl(count, 8 << shift);
8724     jccb(Assembler::zero, L_exit);
8725     jmpb(L_fill_8_bytes);
8726 
8727     //
8728     // length is too short, just fill qwords
8729     //
8730     BIND(L_fill_8_bytes_loop);
8731     movl(Address(to, 0), value);
8732     movl(Address(to, 4), value);
8733     addptr(to, 8);
8734     BIND(L_fill_8_bytes);
8735     subl(count, 1 << (shift + 1));
8736     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8737     // fall through to fill 4 bytes
8738   } else {
8739     Label L_fill_32_bytes;
8740     if (!UseUnalignedLoadStores) {
8741       // align to 8 bytes, we know we are 4 byte aligned to start
8742       testptr(to, 4);
8743       jccb(Assembler::zero, L_fill_32_bytes);
8744       movl(Address(to, 0), value);
8745       addptr(to, 4);
8746       subl(count, 1<<shift);
8747     }
8748     BIND(L_fill_32_bytes);
8749     {
8750       assert( UseSSE >= 2, "supported cpu only" );
8751       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8752       if (UseAVX > 2) {
8753         movl(rtmp, 0xffff);
8754         kmovwl(k1, rtmp);
8755       }
8756       movdl(xtmp, value);
8757       if (UseAVX > 2 && UseUnalignedLoadStores) {
8758         // Fill 64-byte chunks
8759         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8760         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8761 
8762         subl(count, 16 << shift);
8763         jcc(Assembler::less, L_check_fill_32_bytes);
8764         align(16);
8765 
8766         BIND(L_fill_64_bytes_loop);
8767         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8768         addptr(to, 64);
8769         subl(count, 16 << shift);
8770         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8771 
8772         BIND(L_check_fill_32_bytes);
8773         addl(count, 8 << shift);
8774         jccb(Assembler::less, L_check_fill_8_bytes);
8775         vmovdqu(Address(to, 0), xtmp);
8776         addptr(to, 32);
8777         subl(count, 8 << shift);
8778 
8779         BIND(L_check_fill_8_bytes);
8780       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8781         // Fill 64-byte chunks
8782         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8783         vpbroadcastd(xtmp, xtmp);
8784 
8785         subl(count, 16 << shift);
8786         jcc(Assembler::less, L_check_fill_32_bytes);
8787         align(16);
8788 
8789         BIND(L_fill_64_bytes_loop);
8790         vmovdqu(Address(to, 0), xtmp);
8791         vmovdqu(Address(to, 32), xtmp);
8792         addptr(to, 64);
8793         subl(count, 16 << shift);
8794         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8795 
8796         BIND(L_check_fill_32_bytes);
8797         addl(count, 8 << shift);
8798         jccb(Assembler::less, L_check_fill_8_bytes);
8799         vmovdqu(Address(to, 0), xtmp);
8800         addptr(to, 32);
8801         subl(count, 8 << shift);
8802 
8803         BIND(L_check_fill_8_bytes);
8804         // clean upper bits of YMM registers
8805         movdl(xtmp, value);
8806         pshufd(xtmp, xtmp, 0);
8807       } else {
8808         // Fill 32-byte chunks
8809         pshufd(xtmp, xtmp, 0);
8810 
8811         subl(count, 8 << shift);
8812         jcc(Assembler::less, L_check_fill_8_bytes);
8813         align(16);
8814 
8815         BIND(L_fill_32_bytes_loop);
8816 
8817         if (UseUnalignedLoadStores) {
8818           movdqu(Address(to, 0), xtmp);
8819           movdqu(Address(to, 16), xtmp);
8820         } else {
8821           movq(Address(to, 0), xtmp);
8822           movq(Address(to, 8), xtmp);
8823           movq(Address(to, 16), xtmp);
8824           movq(Address(to, 24), xtmp);
8825         }
8826 
8827         addptr(to, 32);
8828         subl(count, 8 << shift);
8829         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8830 
8831         BIND(L_check_fill_8_bytes);
8832       }
8833       addl(count, 8 << shift);
8834       jccb(Assembler::zero, L_exit);
8835       jmpb(L_fill_8_bytes);
8836 
8837       //
8838       // length is too short, just fill qwords
8839       //
8840       BIND(L_fill_8_bytes_loop);
8841       movq(Address(to, 0), xtmp);
8842       addptr(to, 8);
8843       BIND(L_fill_8_bytes);
8844       subl(count, 1 << (shift + 1));
8845       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8846     }
8847   }
8848   // fill trailing 4 bytes
8849   BIND(L_fill_4_bytes);
8850   testl(count, 1<<shift);
8851   jccb(Assembler::zero, L_fill_2_bytes);
8852   movl(Address(to, 0), value);
8853   if (t == T_BYTE || t == T_SHORT) {
8854     addptr(to, 4);
8855     BIND(L_fill_2_bytes);
8856     // fill trailing 2 bytes
8857     testl(count, 1<<(shift-1));
8858     jccb(Assembler::zero, L_fill_byte);
8859     movw(Address(to, 0), value);
8860     if (t == T_BYTE) {
8861       addptr(to, 2);
8862       BIND(L_fill_byte);
8863       // fill trailing byte
8864       testl(count, 1);
8865       jccb(Assembler::zero, L_exit);
8866       movb(Address(to, 0), value);
8867     } else {
8868       BIND(L_fill_byte);
8869     }
8870   } else {
8871     BIND(L_fill_2_bytes);
8872   }
8873   BIND(L_exit);
8874 }
8875 
8876 // encode char[] to byte[] in ISO_8859_1
8877    //@HotSpotIntrinsicCandidate
8878    //private static int implEncodeISOArray(byte[] sa, int sp,
8879    //byte[] da, int dp, int len) {
8880    //  int i = 0;
8881    //  for (; i < len; i++) {
8882    //    char c = StringUTF16.getChar(sa, sp++);
8883    //    if (c > '\u00FF')
8884    //      break;
8885    //    da[dp++] = (byte)c;
8886    //  }
8887    //  return i;
8888    //}
8889 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8890   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8891   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8892   Register tmp5, Register result) {
8893 
8894   // rsi: src
8895   // rdi: dst
8896   // rdx: len
8897   // rcx: tmp5
8898   // rax: result
8899   ShortBranchVerifier sbv(this);
8900   assert_different_registers(src, dst, len, tmp5, result);
8901   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8902 
8903   // set result
8904   xorl(result, result);
8905   // check for zero length
8906   testl(len, len);
8907   jcc(Assembler::zero, L_done);
8908 
8909   movl(result, len);
8910 
8911   // Setup pointers
8912   lea(src, Address(src, len, Address::times_2)); // char[]
8913   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8914   negptr(len);
8915 
8916   if (UseSSE42Intrinsics || UseAVX >= 2) {
8917     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8918     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8919 
8920     if (UseAVX >= 2) {
8921       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8922       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8923       movdl(tmp1Reg, tmp5);
8924       vpbroadcastd(tmp1Reg, tmp1Reg);
8925       jmp(L_chars_32_check);
8926 
8927       bind(L_copy_32_chars);
8928       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8929       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8930       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8931       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8932       jccb(Assembler::notZero, L_copy_32_chars_exit);
8933       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8934       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8935       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8936 
8937       bind(L_chars_32_check);
8938       addptr(len, 32);
8939       jcc(Assembler::lessEqual, L_copy_32_chars);
8940 
8941       bind(L_copy_32_chars_exit);
8942       subptr(len, 16);
8943       jccb(Assembler::greater, L_copy_16_chars_exit);
8944 
8945     } else if (UseSSE42Intrinsics) {
8946       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8947       movdl(tmp1Reg, tmp5);
8948       pshufd(tmp1Reg, tmp1Reg, 0);
8949       jmpb(L_chars_16_check);
8950     }
8951 
8952     bind(L_copy_16_chars);
8953     if (UseAVX >= 2) {
8954       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8955       vptest(tmp2Reg, tmp1Reg);
8956       jcc(Assembler::notZero, L_copy_16_chars_exit);
8957       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8958       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8959     } else {
8960       if (UseAVX > 0) {
8961         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8962         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8963         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8964       } else {
8965         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8966         por(tmp2Reg, tmp3Reg);
8967         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8968         por(tmp2Reg, tmp4Reg);
8969       }
8970       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8971       jccb(Assembler::notZero, L_copy_16_chars_exit);
8972       packuswb(tmp3Reg, tmp4Reg);
8973     }
8974     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8975 
8976     bind(L_chars_16_check);
8977     addptr(len, 16);
8978     jcc(Assembler::lessEqual, L_copy_16_chars);
8979 
8980     bind(L_copy_16_chars_exit);
8981     if (UseAVX >= 2) {
8982       // clean upper bits of YMM registers
8983       vpxor(tmp2Reg, tmp2Reg);
8984       vpxor(tmp3Reg, tmp3Reg);
8985       vpxor(tmp4Reg, tmp4Reg);
8986       movdl(tmp1Reg, tmp5);
8987       pshufd(tmp1Reg, tmp1Reg, 0);
8988     }
8989     subptr(len, 8);
8990     jccb(Assembler::greater, L_copy_8_chars_exit);
8991 
8992     bind(L_copy_8_chars);
8993     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8994     ptest(tmp3Reg, tmp1Reg);
8995     jccb(Assembler::notZero, L_copy_8_chars_exit);
8996     packuswb(tmp3Reg, tmp1Reg);
8997     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8998     addptr(len, 8);
8999     jccb(Assembler::lessEqual, L_copy_8_chars);
9000 
9001     bind(L_copy_8_chars_exit);
9002     subptr(len, 8);
9003     jccb(Assembler::zero, L_done);
9004   }
9005 
9006   bind(L_copy_1_char);
9007   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
9008   testl(tmp5, 0xff00);      // check if Unicode char
9009   jccb(Assembler::notZero, L_copy_1_char_exit);
9010   movb(Address(dst, len, Address::times_1, 0), tmp5);
9011   addptr(len, 1);
9012   jccb(Assembler::less, L_copy_1_char);
9013 
9014   bind(L_copy_1_char_exit);
9015   addptr(result, len); // len is negative count of not processed elements
9016 
9017   bind(L_done);
9018 }
9019 
9020 #ifdef _LP64
9021 /**
9022  * Helper for multiply_to_len().
9023  */
9024 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
9025   addq(dest_lo, src1);
9026   adcq(dest_hi, 0);
9027   addq(dest_lo, src2);
9028   adcq(dest_hi, 0);
9029 }
9030 
9031 /**
9032  * Multiply 64 bit by 64 bit first loop.
9033  */
9034 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
9035                                            Register y, Register y_idx, Register z,
9036                                            Register carry, Register product,
9037                                            Register idx, Register kdx) {
9038   //
9039   //  jlong carry, x[], y[], z[];
9040   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9041   //    huge_128 product = y[idx] * x[xstart] + carry;
9042   //    z[kdx] = (jlong)product;
9043   //    carry  = (jlong)(product >>> 64);
9044   //  }
9045   //  z[xstart] = carry;
9046   //
9047 
9048   Label L_first_loop, L_first_loop_exit;
9049   Label L_one_x, L_one_y, L_multiply;
9050 
9051   decrementl(xstart);
9052   jcc(Assembler::negative, L_one_x);
9053 
9054   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9055   rorq(x_xstart, 32); // convert big-endian to little-endian
9056 
9057   bind(L_first_loop);
9058   decrementl(idx);
9059   jcc(Assembler::negative, L_first_loop_exit);
9060   decrementl(idx);
9061   jcc(Assembler::negative, L_one_y);
9062   movq(y_idx, Address(y, idx, Address::times_4,  0));
9063   rorq(y_idx, 32); // convert big-endian to little-endian
9064   bind(L_multiply);
9065   movq(product, x_xstart);
9066   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9067   addq(product, carry);
9068   adcq(rdx, 0);
9069   subl(kdx, 2);
9070   movl(Address(z, kdx, Address::times_4,  4), product);
9071   shrq(product, 32);
9072   movl(Address(z, kdx, Address::times_4,  0), product);
9073   movq(carry, rdx);
9074   jmp(L_first_loop);
9075 
9076   bind(L_one_y);
9077   movl(y_idx, Address(y,  0));
9078   jmp(L_multiply);
9079 
9080   bind(L_one_x);
9081   movl(x_xstart, Address(x,  0));
9082   jmp(L_first_loop);
9083 
9084   bind(L_first_loop_exit);
9085 }
9086 
9087 /**
9088  * Multiply 64 bit by 64 bit and add 128 bit.
9089  */
9090 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9091                                             Register yz_idx, Register idx,
9092                                             Register carry, Register product, int offset) {
9093   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9094   //     z[kdx] = (jlong)product;
9095 
9096   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9097   rorq(yz_idx, 32); // convert big-endian to little-endian
9098   movq(product, x_xstart);
9099   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9100   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9101   rorq(yz_idx, 32); // convert big-endian to little-endian
9102 
9103   add2_with_carry(rdx, product, carry, yz_idx);
9104 
9105   movl(Address(z, idx, Address::times_4,  offset+4), product);
9106   shrq(product, 32);
9107   movl(Address(z, idx, Address::times_4,  offset), product);
9108 
9109 }
9110 
9111 /**
9112  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9113  */
9114 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9115                                              Register yz_idx, Register idx, Register jdx,
9116                                              Register carry, Register product,
9117                                              Register carry2) {
9118   //   jlong carry, x[], y[], z[];
9119   //   int kdx = ystart+1;
9120   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9121   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9122   //     z[kdx+idx+1] = (jlong)product;
9123   //     jlong carry2  = (jlong)(product >>> 64);
9124   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9125   //     z[kdx+idx] = (jlong)product;
9126   //     carry  = (jlong)(product >>> 64);
9127   //   }
9128   //   idx += 2;
9129   //   if (idx > 0) {
9130   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9131   //     z[kdx+idx] = (jlong)product;
9132   //     carry  = (jlong)(product >>> 64);
9133   //   }
9134   //
9135 
9136   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9137 
9138   movl(jdx, idx);
9139   andl(jdx, 0xFFFFFFFC);
9140   shrl(jdx, 2);
9141 
9142   bind(L_third_loop);
9143   subl(jdx, 1);
9144   jcc(Assembler::negative, L_third_loop_exit);
9145   subl(idx, 4);
9146 
9147   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9148   movq(carry2, rdx);
9149 
9150   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9151   movq(carry, rdx);
9152   jmp(L_third_loop);
9153 
9154   bind (L_third_loop_exit);
9155 
9156   andl (idx, 0x3);
9157   jcc(Assembler::zero, L_post_third_loop_done);
9158 
9159   Label L_check_1;
9160   subl(idx, 2);
9161   jcc(Assembler::negative, L_check_1);
9162 
9163   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9164   movq(carry, rdx);
9165 
9166   bind (L_check_1);
9167   addl (idx, 0x2);
9168   andl (idx, 0x1);
9169   subl(idx, 1);
9170   jcc(Assembler::negative, L_post_third_loop_done);
9171 
9172   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9173   movq(product, x_xstart);
9174   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9175   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9176 
9177   add2_with_carry(rdx, product, yz_idx, carry);
9178 
9179   movl(Address(z, idx, Address::times_4,  0), product);
9180   shrq(product, 32);
9181 
9182   shlq(rdx, 32);
9183   orq(product, rdx);
9184   movq(carry, product);
9185 
9186   bind(L_post_third_loop_done);
9187 }
9188 
9189 /**
9190  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9191  *
9192  */
9193 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9194                                                   Register carry, Register carry2,
9195                                                   Register idx, Register jdx,
9196                                                   Register yz_idx1, Register yz_idx2,
9197                                                   Register tmp, Register tmp3, Register tmp4) {
9198   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9199 
9200   //   jlong carry, x[], y[], z[];
9201   //   int kdx = ystart+1;
9202   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9203   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9204   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9205   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9206   //     carry  = (jlong)(tmp4 >>> 64);
9207   //     z[kdx+idx+1] = (jlong)tmp3;
9208   //     z[kdx+idx] = (jlong)tmp4;
9209   //   }
9210   //   idx += 2;
9211   //   if (idx > 0) {
9212   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9213   //     z[kdx+idx] = (jlong)yz_idx1;
9214   //     carry  = (jlong)(yz_idx1 >>> 64);
9215   //   }
9216   //
9217 
9218   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9219 
9220   movl(jdx, idx);
9221   andl(jdx, 0xFFFFFFFC);
9222   shrl(jdx, 2);
9223 
9224   bind(L_third_loop);
9225   subl(jdx, 1);
9226   jcc(Assembler::negative, L_third_loop_exit);
9227   subl(idx, 4);
9228 
9229   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9230   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9231   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9232   rorxq(yz_idx2, yz_idx2, 32);
9233 
9234   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9235   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9236 
9237   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9238   rorxq(yz_idx1, yz_idx1, 32);
9239   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9240   rorxq(yz_idx2, yz_idx2, 32);
9241 
9242   if (VM_Version::supports_adx()) {
9243     adcxq(tmp3, carry);
9244     adoxq(tmp3, yz_idx1);
9245 
9246     adcxq(tmp4, tmp);
9247     adoxq(tmp4, yz_idx2);
9248 
9249     movl(carry, 0); // does not affect flags
9250     adcxq(carry2, carry);
9251     adoxq(carry2, carry);
9252   } else {
9253     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9254     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9255   }
9256   movq(carry, carry2);
9257 
9258   movl(Address(z, idx, Address::times_4, 12), tmp3);
9259   shrq(tmp3, 32);
9260   movl(Address(z, idx, Address::times_4,  8), tmp3);
9261 
9262   movl(Address(z, idx, Address::times_4,  4), tmp4);
9263   shrq(tmp4, 32);
9264   movl(Address(z, idx, Address::times_4,  0), tmp4);
9265 
9266   jmp(L_third_loop);
9267 
9268   bind (L_third_loop_exit);
9269 
9270   andl (idx, 0x3);
9271   jcc(Assembler::zero, L_post_third_loop_done);
9272 
9273   Label L_check_1;
9274   subl(idx, 2);
9275   jcc(Assembler::negative, L_check_1);
9276 
9277   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9278   rorxq(yz_idx1, yz_idx1, 32);
9279   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9280   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9281   rorxq(yz_idx2, yz_idx2, 32);
9282 
9283   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9284 
9285   movl(Address(z, idx, Address::times_4,  4), tmp3);
9286   shrq(tmp3, 32);
9287   movl(Address(z, idx, Address::times_4,  0), tmp3);
9288   movq(carry, tmp4);
9289 
9290   bind (L_check_1);
9291   addl (idx, 0x2);
9292   andl (idx, 0x1);
9293   subl(idx, 1);
9294   jcc(Assembler::negative, L_post_third_loop_done);
9295   movl(tmp4, Address(y, idx, Address::times_4,  0));
9296   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9297   movl(tmp4, Address(z, idx, Address::times_4,  0));
9298 
9299   add2_with_carry(carry2, tmp3, tmp4, carry);
9300 
9301   movl(Address(z, idx, Address::times_4,  0), tmp3);
9302   shrq(tmp3, 32);
9303 
9304   shlq(carry2, 32);
9305   orq(tmp3, carry2);
9306   movq(carry, tmp3);
9307 
9308   bind(L_post_third_loop_done);
9309 }
9310 
9311 /**
9312  * Code for BigInteger::multiplyToLen() instrinsic.
9313  *
9314  * rdi: x
9315  * rax: xlen
9316  * rsi: y
9317  * rcx: ylen
9318  * r8:  z
9319  * r11: zlen
9320  * r12: tmp1
9321  * r13: tmp2
9322  * r14: tmp3
9323  * r15: tmp4
9324  * rbx: tmp5
9325  *
9326  */
9327 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9328                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9329   ShortBranchVerifier sbv(this);
9330   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9331 
9332   push(tmp1);
9333   push(tmp2);
9334   push(tmp3);
9335   push(tmp4);
9336   push(tmp5);
9337 
9338   push(xlen);
9339   push(zlen);
9340 
9341   const Register idx = tmp1;
9342   const Register kdx = tmp2;
9343   const Register xstart = tmp3;
9344 
9345   const Register y_idx = tmp4;
9346   const Register carry = tmp5;
9347   const Register product  = xlen;
9348   const Register x_xstart = zlen;  // reuse register
9349 
9350   // First Loop.
9351   //
9352   //  final static long LONG_MASK = 0xffffffffL;
9353   //  int xstart = xlen - 1;
9354   //  int ystart = ylen - 1;
9355   //  long carry = 0;
9356   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9357   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9358   //    z[kdx] = (int)product;
9359   //    carry = product >>> 32;
9360   //  }
9361   //  z[xstart] = (int)carry;
9362   //
9363 
9364   movl(idx, ylen);      // idx = ylen;
9365   movl(kdx, zlen);      // kdx = xlen+ylen;
9366   xorq(carry, carry);   // carry = 0;
9367 
9368   Label L_done;
9369 
9370   movl(xstart, xlen);
9371   decrementl(xstart);
9372   jcc(Assembler::negative, L_done);
9373 
9374   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9375 
9376   Label L_second_loop;
9377   testl(kdx, kdx);
9378   jcc(Assembler::zero, L_second_loop);
9379 
9380   Label L_carry;
9381   subl(kdx, 1);
9382   jcc(Assembler::zero, L_carry);
9383 
9384   movl(Address(z, kdx, Address::times_4,  0), carry);
9385   shrq(carry, 32);
9386   subl(kdx, 1);
9387 
9388   bind(L_carry);
9389   movl(Address(z, kdx, Address::times_4,  0), carry);
9390 
9391   // Second and third (nested) loops.
9392   //
9393   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9394   //   carry = 0;
9395   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9396   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9397   //                    (z[k] & LONG_MASK) + carry;
9398   //     z[k] = (int)product;
9399   //     carry = product >>> 32;
9400   //   }
9401   //   z[i] = (int)carry;
9402   // }
9403   //
9404   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9405 
9406   const Register jdx = tmp1;
9407 
9408   bind(L_second_loop);
9409   xorl(carry, carry);    // carry = 0;
9410   movl(jdx, ylen);       // j = ystart+1
9411 
9412   subl(xstart, 1);       // i = xstart-1;
9413   jcc(Assembler::negative, L_done);
9414 
9415   push (z);
9416 
9417   Label L_last_x;
9418   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9419   subl(xstart, 1);       // i = xstart-1;
9420   jcc(Assembler::negative, L_last_x);
9421 
9422   if (UseBMI2Instructions) {
9423     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9424     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9425   } else {
9426     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9427     rorq(x_xstart, 32);  // convert big-endian to little-endian
9428   }
9429 
9430   Label L_third_loop_prologue;
9431   bind(L_third_loop_prologue);
9432 
9433   push (x);
9434   push (xstart);
9435   push (ylen);
9436 
9437 
9438   if (UseBMI2Instructions) {
9439     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9440   } else { // !UseBMI2Instructions
9441     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9442   }
9443 
9444   pop(ylen);
9445   pop(xlen);
9446   pop(x);
9447   pop(z);
9448 
9449   movl(tmp3, xlen);
9450   addl(tmp3, 1);
9451   movl(Address(z, tmp3, Address::times_4,  0), carry);
9452   subl(tmp3, 1);
9453   jccb(Assembler::negative, L_done);
9454 
9455   shrq(carry, 32);
9456   movl(Address(z, tmp3, Address::times_4,  0), carry);
9457   jmp(L_second_loop);
9458 
9459   // Next infrequent code is moved outside loops.
9460   bind(L_last_x);
9461   if (UseBMI2Instructions) {
9462     movl(rdx, Address(x,  0));
9463   } else {
9464     movl(x_xstart, Address(x,  0));
9465   }
9466   jmp(L_third_loop_prologue);
9467 
9468   bind(L_done);
9469 
9470   pop(zlen);
9471   pop(xlen);
9472 
9473   pop(tmp5);
9474   pop(tmp4);
9475   pop(tmp3);
9476   pop(tmp2);
9477   pop(tmp1);
9478 }
9479 
9480 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9481   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9482   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9483   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9484   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9485   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9486   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9487   Label SAME_TILL_END, DONE;
9488   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9489 
9490   //scale is in rcx in both Win64 and Unix
9491   ShortBranchVerifier sbv(this);
9492 
9493   shlq(length);
9494   xorq(result, result);
9495 
9496   if ((UseAVX > 2) &&
9497       VM_Version::supports_avx512vlbw()) {
9498     set_vector_masking();  // opening of the stub context for programming mask registers
9499     cmpq(length, 64);
9500     jcc(Assembler::less, VECTOR32_TAIL);
9501     movq(tmp1, length);
9502     andq(tmp1, 0x3F);      // tail count
9503     andq(length, ~(0x3F)); //vector count
9504 
9505     bind(VECTOR64_LOOP);
9506     // AVX512 code to compare 64 byte vectors.
9507     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9508     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9509     kortestql(k7, k7);
9510     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9511     addq(result, 64);
9512     subq(length, 64);
9513     jccb(Assembler::notZero, VECTOR64_LOOP);
9514 
9515     //bind(VECTOR64_TAIL);
9516     testq(tmp1, tmp1);
9517     jcc(Assembler::zero, SAME_TILL_END);
9518 
9519     bind(VECTOR64_TAIL);
9520     // AVX512 code to compare upto 63 byte vectors.
9521     // Save k1
9522     kmovql(k3, k1);
9523     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9524     shlxq(tmp2, tmp2, tmp1);
9525     notq(tmp2);
9526     kmovql(k1, tmp2);
9527 
9528     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9529     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9530 
9531     ktestql(k7, k1);
9532     // Restore k1
9533     kmovql(k1, k3);
9534     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9535 
9536     bind(VECTOR64_NOT_EQUAL);
9537     kmovql(tmp1, k7);
9538     notq(tmp1);
9539     tzcntq(tmp1, tmp1);
9540     addq(result, tmp1);
9541     shrq(result);
9542     jmp(DONE);
9543     bind(VECTOR32_TAIL);
9544     clear_vector_masking();   // closing of the stub context for programming mask registers
9545   }
9546 
9547   cmpq(length, 8);
9548   jcc(Assembler::equal, VECTOR8_LOOP);
9549   jcc(Assembler::less, VECTOR4_TAIL);
9550 
9551   if (UseAVX >= 2) {
9552 
9553     cmpq(length, 16);
9554     jcc(Assembler::equal, VECTOR16_LOOP);
9555     jcc(Assembler::less, VECTOR8_LOOP);
9556 
9557     cmpq(length, 32);
9558     jccb(Assembler::less, VECTOR16_TAIL);
9559 
9560     subq(length, 32);
9561     bind(VECTOR32_LOOP);
9562     vmovdqu(rymm0, Address(obja, result));
9563     vmovdqu(rymm1, Address(objb, result));
9564     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9565     vptest(rymm2, rymm2);
9566     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9567     addq(result, 32);
9568     subq(length, 32);
9569     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9570     addq(length, 32);
9571     jcc(Assembler::equal, SAME_TILL_END);
9572     //falling through if less than 32 bytes left //close the branch here.
9573 
9574     bind(VECTOR16_TAIL);
9575     cmpq(length, 16);
9576     jccb(Assembler::less, VECTOR8_TAIL);
9577     bind(VECTOR16_LOOP);
9578     movdqu(rymm0, Address(obja, result));
9579     movdqu(rymm1, Address(objb, result));
9580     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9581     ptest(rymm2, rymm2);
9582     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9583     addq(result, 16);
9584     subq(length, 16);
9585     jcc(Assembler::equal, SAME_TILL_END);
9586     //falling through if less than 16 bytes left
9587   } else {//regular intrinsics
9588 
9589     cmpq(length, 16);
9590     jccb(Assembler::less, VECTOR8_TAIL);
9591 
9592     subq(length, 16);
9593     bind(VECTOR16_LOOP);
9594     movdqu(rymm0, Address(obja, result));
9595     movdqu(rymm1, Address(objb, result));
9596     pxor(rymm0, rymm1);
9597     ptest(rymm0, rymm0);
9598     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9599     addq(result, 16);
9600     subq(length, 16);
9601     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9602     addq(length, 16);
9603     jcc(Assembler::equal, SAME_TILL_END);
9604     //falling through if less than 16 bytes left
9605   }
9606 
9607   bind(VECTOR8_TAIL);
9608   cmpq(length, 8);
9609   jccb(Assembler::less, VECTOR4_TAIL);
9610   bind(VECTOR8_LOOP);
9611   movq(tmp1, Address(obja, result));
9612   movq(tmp2, Address(objb, result));
9613   xorq(tmp1, tmp2);
9614   testq(tmp1, tmp1);
9615   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9616   addq(result, 8);
9617   subq(length, 8);
9618   jcc(Assembler::equal, SAME_TILL_END);
9619   //falling through if less than 8 bytes left
9620 
9621   bind(VECTOR4_TAIL);
9622   cmpq(length, 4);
9623   jccb(Assembler::less, BYTES_TAIL);
9624   bind(VECTOR4_LOOP);
9625   movl(tmp1, Address(obja, result));
9626   xorl(tmp1, Address(objb, result));
9627   testl(tmp1, tmp1);
9628   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9629   addq(result, 4);
9630   subq(length, 4);
9631   jcc(Assembler::equal, SAME_TILL_END);
9632   //falling through if less than 4 bytes left
9633 
9634   bind(BYTES_TAIL);
9635   bind(BYTES_LOOP);
9636   load_unsigned_byte(tmp1, Address(obja, result));
9637   load_unsigned_byte(tmp2, Address(objb, result));
9638   xorl(tmp1, tmp2);
9639   testl(tmp1, tmp1);
9640   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9641   decq(length);
9642   jccb(Assembler::zero, SAME_TILL_END);
9643   incq(result);
9644   load_unsigned_byte(tmp1, Address(obja, result));
9645   load_unsigned_byte(tmp2, Address(objb, result));
9646   xorl(tmp1, tmp2);
9647   testl(tmp1, tmp1);
9648   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9649   decq(length);
9650   jccb(Assembler::zero, SAME_TILL_END);
9651   incq(result);
9652   load_unsigned_byte(tmp1, Address(obja, result));
9653   load_unsigned_byte(tmp2, Address(objb, result));
9654   xorl(tmp1, tmp2);
9655   testl(tmp1, tmp1);
9656   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9657   jmpb(SAME_TILL_END);
9658 
9659   if (UseAVX >= 2) {
9660     bind(VECTOR32_NOT_EQUAL);
9661     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9662     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9663     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9664     vpmovmskb(tmp1, rymm0);
9665     bsfq(tmp1, tmp1);
9666     addq(result, tmp1);
9667     shrq(result);
9668     jmpb(DONE);
9669   }
9670 
9671   bind(VECTOR16_NOT_EQUAL);
9672   if (UseAVX >= 2) {
9673     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9674     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9675     pxor(rymm0, rymm2);
9676   } else {
9677     pcmpeqb(rymm2, rymm2);
9678     pxor(rymm0, rymm1);
9679     pcmpeqb(rymm0, rymm1);
9680     pxor(rymm0, rymm2);
9681   }
9682   pmovmskb(tmp1, rymm0);
9683   bsfq(tmp1, tmp1);
9684   addq(result, tmp1);
9685   shrq(result);
9686   jmpb(DONE);
9687 
9688   bind(VECTOR8_NOT_EQUAL);
9689   bind(VECTOR4_NOT_EQUAL);
9690   bsfq(tmp1, tmp1);
9691   shrq(tmp1, 3);
9692   addq(result, tmp1);
9693   bind(BYTES_NOT_EQUAL);
9694   shrq(result);
9695   jmpb(DONE);
9696 
9697   bind(SAME_TILL_END);
9698   mov64(result, -1);
9699 
9700   bind(DONE);
9701 }
9702 
9703 //Helper functions for square_to_len()
9704 
9705 /**
9706  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9707  * Preserves x and z and modifies rest of the registers.
9708  */
9709 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9710   // Perform square and right shift by 1
9711   // Handle odd xlen case first, then for even xlen do the following
9712   // jlong carry = 0;
9713   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9714   //     huge_128 product = x[j:j+1] * x[j:j+1];
9715   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9716   //     z[i+2:i+3] = (jlong)(product >>> 1);
9717   //     carry = (jlong)product;
9718   // }
9719 
9720   xorq(tmp5, tmp5);     // carry
9721   xorq(rdxReg, rdxReg);
9722   xorl(tmp1, tmp1);     // index for x
9723   xorl(tmp4, tmp4);     // index for z
9724 
9725   Label L_first_loop, L_first_loop_exit;
9726 
9727   testl(xlen, 1);
9728   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9729 
9730   // Square and right shift by 1 the odd element using 32 bit multiply
9731   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9732   imulq(raxReg, raxReg);
9733   shrq(raxReg, 1);
9734   adcq(tmp5, 0);
9735   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9736   incrementl(tmp1);
9737   addl(tmp4, 2);
9738 
9739   // Square and  right shift by 1 the rest using 64 bit multiply
9740   bind(L_first_loop);
9741   cmpptr(tmp1, xlen);
9742   jccb(Assembler::equal, L_first_loop_exit);
9743 
9744   // Square
9745   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9746   rorq(raxReg, 32);    // convert big-endian to little-endian
9747   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9748 
9749   // Right shift by 1 and save carry
9750   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9751   rcrq(rdxReg, 1);
9752   rcrq(raxReg, 1);
9753   adcq(tmp5, 0);
9754 
9755   // Store result in z
9756   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9757   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9758 
9759   // Update indices for x and z
9760   addl(tmp1, 2);
9761   addl(tmp4, 4);
9762   jmp(L_first_loop);
9763 
9764   bind(L_first_loop_exit);
9765 }
9766 
9767 
9768 /**
9769  * Perform the following multiply add operation using BMI2 instructions
9770  * carry:sum = sum + op1*op2 + carry
9771  * op2 should be in rdx
9772  * op2 is preserved, all other registers are modified
9773  */
9774 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9775   // assert op2 is rdx
9776   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9777   addq(sum, carry);
9778   adcq(tmp2, 0);
9779   addq(sum, op1);
9780   adcq(tmp2, 0);
9781   movq(carry, tmp2);
9782 }
9783 
9784 /**
9785  * Perform the following multiply add operation:
9786  * carry:sum = sum + op1*op2 + carry
9787  * Preserves op1, op2 and modifies rest of registers
9788  */
9789 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9790   // rdx:rax = op1 * op2
9791   movq(raxReg, op2);
9792   mulq(op1);
9793 
9794   //  rdx:rax = sum + carry + rdx:rax
9795   addq(sum, carry);
9796   adcq(rdxReg, 0);
9797   addq(sum, raxReg);
9798   adcq(rdxReg, 0);
9799 
9800   // carry:sum = rdx:sum
9801   movq(carry, rdxReg);
9802 }
9803 
9804 /**
9805  * Add 64 bit long carry into z[] with carry propogation.
9806  * Preserves z and carry register values and modifies rest of registers.
9807  *
9808  */
9809 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9810   Label L_fourth_loop, L_fourth_loop_exit;
9811 
9812   movl(tmp1, 1);
9813   subl(zlen, 2);
9814   addq(Address(z, zlen, Address::times_4, 0), carry);
9815 
9816   bind(L_fourth_loop);
9817   jccb(Assembler::carryClear, L_fourth_loop_exit);
9818   subl(zlen, 2);
9819   jccb(Assembler::negative, L_fourth_loop_exit);
9820   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9821   jmp(L_fourth_loop);
9822   bind(L_fourth_loop_exit);
9823 }
9824 
9825 /**
9826  * Shift z[] left by 1 bit.
9827  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9828  *
9829  */
9830 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9831 
9832   Label L_fifth_loop, L_fifth_loop_exit;
9833 
9834   // Fifth loop
9835   // Perform primitiveLeftShift(z, zlen, 1)
9836 
9837   const Register prev_carry = tmp1;
9838   const Register new_carry = tmp4;
9839   const Register value = tmp2;
9840   const Register zidx = tmp3;
9841 
9842   // int zidx, carry;
9843   // long value;
9844   // carry = 0;
9845   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9846   //    (carry:value)  = (z[i] << 1) | carry ;
9847   //    z[i] = value;
9848   // }
9849 
9850   movl(zidx, zlen);
9851   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9852 
9853   bind(L_fifth_loop);
9854   decl(zidx);  // Use decl to preserve carry flag
9855   decl(zidx);
9856   jccb(Assembler::negative, L_fifth_loop_exit);
9857 
9858   if (UseBMI2Instructions) {
9859      movq(value, Address(z, zidx, Address::times_4, 0));
9860      rclq(value, 1);
9861      rorxq(value, value, 32);
9862      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9863   }
9864   else {
9865     // clear new_carry
9866     xorl(new_carry, new_carry);
9867 
9868     // Shift z[i] by 1, or in previous carry and save new carry
9869     movq(value, Address(z, zidx, Address::times_4, 0));
9870     shlq(value, 1);
9871     adcl(new_carry, 0);
9872 
9873     orq(value, prev_carry);
9874     rorq(value, 0x20);
9875     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9876 
9877     // Set previous carry = new carry
9878     movl(prev_carry, new_carry);
9879   }
9880   jmp(L_fifth_loop);
9881 
9882   bind(L_fifth_loop_exit);
9883 }
9884 
9885 
9886 /**
9887  * Code for BigInteger::squareToLen() intrinsic
9888  *
9889  * rdi: x
9890  * rsi: len
9891  * r8:  z
9892  * rcx: zlen
9893  * r12: tmp1
9894  * r13: tmp2
9895  * r14: tmp3
9896  * r15: tmp4
9897  * rbx: tmp5
9898  *
9899  */
9900 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) {
9901 
9902   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;
9903   push(tmp1);
9904   push(tmp2);
9905   push(tmp3);
9906   push(tmp4);
9907   push(tmp5);
9908 
9909   // First loop
9910   // Store the squares, right shifted one bit (i.e., divided by 2).
9911   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9912 
9913   // Add in off-diagonal sums.
9914   //
9915   // Second, third (nested) and fourth loops.
9916   // zlen +=2;
9917   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9918   //    carry = 0;
9919   //    long op2 = x[xidx:xidx+1];
9920   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9921   //       k -= 2;
9922   //       long op1 = x[j:j+1];
9923   //       long sum = z[k:k+1];
9924   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9925   //       z[k:k+1] = sum;
9926   //    }
9927   //    add_one_64(z, k, carry, tmp_regs);
9928   // }
9929 
9930   const Register carry = tmp5;
9931   const Register sum = tmp3;
9932   const Register op1 = tmp4;
9933   Register op2 = tmp2;
9934 
9935   push(zlen);
9936   push(len);
9937   addl(zlen,2);
9938   bind(L_second_loop);
9939   xorq(carry, carry);
9940   subl(zlen, 4);
9941   subl(len, 2);
9942   push(zlen);
9943   push(len);
9944   cmpl(len, 0);
9945   jccb(Assembler::lessEqual, L_second_loop_exit);
9946 
9947   // Multiply an array by one 64 bit long.
9948   if (UseBMI2Instructions) {
9949     op2 = rdxReg;
9950     movq(op2, Address(x, len, Address::times_4,  0));
9951     rorxq(op2, op2, 32);
9952   }
9953   else {
9954     movq(op2, Address(x, len, Address::times_4,  0));
9955     rorq(op2, 32);
9956   }
9957 
9958   bind(L_third_loop);
9959   decrementl(len);
9960   jccb(Assembler::negative, L_third_loop_exit);
9961   decrementl(len);
9962   jccb(Assembler::negative, L_last_x);
9963 
9964   movq(op1, Address(x, len, Address::times_4,  0));
9965   rorq(op1, 32);
9966 
9967   bind(L_multiply);
9968   subl(zlen, 2);
9969   movq(sum, Address(z, zlen, Address::times_4,  0));
9970 
9971   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9972   if (UseBMI2Instructions) {
9973     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9974   }
9975   else {
9976     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9977   }
9978 
9979   movq(Address(z, zlen, Address::times_4, 0), sum);
9980 
9981   jmp(L_third_loop);
9982   bind(L_third_loop_exit);
9983 
9984   // Fourth loop
9985   // Add 64 bit long carry into z with carry propogation.
9986   // Uses offsetted zlen.
9987   add_one_64(z, zlen, carry, tmp1);
9988 
9989   pop(len);
9990   pop(zlen);
9991   jmp(L_second_loop);
9992 
9993   // Next infrequent code is moved outside loops.
9994   bind(L_last_x);
9995   movl(op1, Address(x, 0));
9996   jmp(L_multiply);
9997 
9998   bind(L_second_loop_exit);
9999   pop(len);
10000   pop(zlen);
10001   pop(len);
10002   pop(zlen);
10003 
10004   // Fifth loop
10005   // Shift z left 1 bit.
10006   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
10007 
10008   // z[zlen-1] |= x[len-1] & 1;
10009   movl(tmp3, Address(x, len, Address::times_4, -4));
10010   andl(tmp3, 1);
10011   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
10012 
10013   pop(tmp5);
10014   pop(tmp4);
10015   pop(tmp3);
10016   pop(tmp2);
10017   pop(tmp1);
10018 }
10019 
10020 /**
10021  * Helper function for mul_add()
10022  * Multiply the in[] by int k and add to out[] starting at offset offs using
10023  * 128 bit by 32 bit multiply and return the carry in tmp5.
10024  * Only quad int aligned length of in[] is operated on in this function.
10025  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
10026  * This function preserves out, in and k registers.
10027  * len and offset point to the appropriate index in "in" & "out" correspondingly
10028  * tmp5 has the carry.
10029  * other registers are temporary and are modified.
10030  *
10031  */
10032 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
10033   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
10034   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10035 
10036   Label L_first_loop, L_first_loop_exit;
10037 
10038   movl(tmp1, len);
10039   shrl(tmp1, 2);
10040 
10041   bind(L_first_loop);
10042   subl(tmp1, 1);
10043   jccb(Assembler::negative, L_first_loop_exit);
10044 
10045   subl(len, 4);
10046   subl(offset, 4);
10047 
10048   Register op2 = tmp2;
10049   const Register sum = tmp3;
10050   const Register op1 = tmp4;
10051   const Register carry = tmp5;
10052 
10053   if (UseBMI2Instructions) {
10054     op2 = rdxReg;
10055   }
10056 
10057   movq(op1, Address(in, len, Address::times_4,  8));
10058   rorq(op1, 32);
10059   movq(sum, Address(out, offset, Address::times_4,  8));
10060   rorq(sum, 32);
10061   if (UseBMI2Instructions) {
10062     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10063   }
10064   else {
10065     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10066   }
10067   // Store back in big endian from little endian
10068   rorq(sum, 0x20);
10069   movq(Address(out, offset, Address::times_4,  8), sum);
10070 
10071   movq(op1, Address(in, len, Address::times_4,  0));
10072   rorq(op1, 32);
10073   movq(sum, Address(out, offset, Address::times_4,  0));
10074   rorq(sum, 32);
10075   if (UseBMI2Instructions) {
10076     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10077   }
10078   else {
10079     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10080   }
10081   // Store back in big endian from little endian
10082   rorq(sum, 0x20);
10083   movq(Address(out, offset, Address::times_4,  0), sum);
10084 
10085   jmp(L_first_loop);
10086   bind(L_first_loop_exit);
10087 }
10088 
10089 /**
10090  * Code for BigInteger::mulAdd() intrinsic
10091  *
10092  * rdi: out
10093  * rsi: in
10094  * r11: offs (out.length - offset)
10095  * rcx: len
10096  * r8:  k
10097  * r12: tmp1
10098  * r13: tmp2
10099  * r14: tmp3
10100  * r15: tmp4
10101  * rbx: tmp5
10102  * Multiply the in[] by word k and add to out[], return the carry in rax
10103  */
10104 void MacroAssembler::mul_add(Register out, Register in, Register offs,
10105    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
10106    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10107 
10108   Label L_carry, L_last_in, L_done;
10109 
10110 // carry = 0;
10111 // for (int j=len-1; j >= 0; j--) {
10112 //    long product = (in[j] & LONG_MASK) * kLong +
10113 //                   (out[offs] & LONG_MASK) + carry;
10114 //    out[offs--] = (int)product;
10115 //    carry = product >>> 32;
10116 // }
10117 //
10118   push(tmp1);
10119   push(tmp2);
10120   push(tmp3);
10121   push(tmp4);
10122   push(tmp5);
10123 
10124   Register op2 = tmp2;
10125   const Register sum = tmp3;
10126   const Register op1 = tmp4;
10127   const Register carry =  tmp5;
10128 
10129   if (UseBMI2Instructions) {
10130     op2 = rdxReg;
10131     movl(op2, k);
10132   }
10133   else {
10134     movl(op2, k);
10135   }
10136 
10137   xorq(carry, carry);
10138 
10139   //First loop
10140 
10141   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
10142   //The carry is in tmp5
10143   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
10144 
10145   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
10146   decrementl(len);
10147   jccb(Assembler::negative, L_carry);
10148   decrementl(len);
10149   jccb(Assembler::negative, L_last_in);
10150 
10151   movq(op1, Address(in, len, Address::times_4,  0));
10152   rorq(op1, 32);
10153 
10154   subl(offs, 2);
10155   movq(sum, Address(out, offs, Address::times_4,  0));
10156   rorq(sum, 32);
10157 
10158   if (UseBMI2Instructions) {
10159     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10160   }
10161   else {
10162     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10163   }
10164 
10165   // Store back in big endian from little endian
10166   rorq(sum, 0x20);
10167   movq(Address(out, offs, Address::times_4,  0), sum);
10168 
10169   testl(len, len);
10170   jccb(Assembler::zero, L_carry);
10171 
10172   //Multiply the last in[] entry, if any
10173   bind(L_last_in);
10174   movl(op1, Address(in, 0));
10175   movl(sum, Address(out, offs, Address::times_4,  -4));
10176 
10177   movl(raxReg, k);
10178   mull(op1); //tmp4 * eax -> edx:eax
10179   addl(sum, carry);
10180   adcl(rdxReg, 0);
10181   addl(sum, raxReg);
10182   adcl(rdxReg, 0);
10183   movl(carry, rdxReg);
10184 
10185   movl(Address(out, offs, Address::times_4,  -4), sum);
10186 
10187   bind(L_carry);
10188   //return tmp5/carry as carry in rax
10189   movl(rax, carry);
10190 
10191   bind(L_done);
10192   pop(tmp5);
10193   pop(tmp4);
10194   pop(tmp3);
10195   pop(tmp2);
10196   pop(tmp1);
10197 }
10198 #endif
10199 
10200 /**
10201  * Emits code to update CRC-32 with a byte value according to constants in table
10202  *
10203  * @param [in,out]crc   Register containing the crc.
10204  * @param [in]val       Register containing the byte to fold into the CRC.
10205  * @param [in]table     Register containing the table of crc constants.
10206  *
10207  * uint32_t crc;
10208  * val = crc_table[(val ^ crc) & 0xFF];
10209  * crc = val ^ (crc >> 8);
10210  *
10211  */
10212 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10213   xorl(val, crc);
10214   andl(val, 0xFF);
10215   shrl(crc, 8); // unsigned shift
10216   xorl(crc, Address(table, val, Address::times_4, 0));
10217 }
10218 
10219 /**
10220  * Fold 128-bit data chunk
10221  */
10222 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10223   if (UseAVX > 0) {
10224     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10225     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10226     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10227     pxor(xcrc, xtmp);
10228   } else {
10229     movdqa(xtmp, xcrc);
10230     pclmulhdq(xtmp, xK);   // [123:64]
10231     pclmulldq(xcrc, xK);   // [63:0]
10232     pxor(xcrc, xtmp);
10233     movdqu(xtmp, Address(buf, offset));
10234     pxor(xcrc, xtmp);
10235   }
10236 }
10237 
10238 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10239   if (UseAVX > 0) {
10240     vpclmulhdq(xtmp, xK, xcrc);
10241     vpclmulldq(xcrc, xK, xcrc);
10242     pxor(xcrc, xbuf);
10243     pxor(xcrc, xtmp);
10244   } else {
10245     movdqa(xtmp, xcrc);
10246     pclmulhdq(xtmp, xK);
10247     pclmulldq(xcrc, xK);
10248     pxor(xcrc, xbuf);
10249     pxor(xcrc, xtmp);
10250   }
10251 }
10252 
10253 /**
10254  * 8-bit folds to compute 32-bit CRC
10255  *
10256  * uint64_t xcrc;
10257  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10258  */
10259 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10260   movdl(tmp, xcrc);
10261   andl(tmp, 0xFF);
10262   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10263   psrldq(xcrc, 1); // unsigned shift one byte
10264   pxor(xcrc, xtmp);
10265 }
10266 
10267 /**
10268  * uint32_t crc;
10269  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10270  */
10271 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10272   movl(tmp, crc);
10273   andl(tmp, 0xFF);
10274   shrl(crc, 8);
10275   xorl(crc, Address(table, tmp, Address::times_4, 0));
10276 }
10277 
10278 /**
10279  * @param crc   register containing existing CRC (32-bit)
10280  * @param buf   register pointing to input byte buffer (byte*)
10281  * @param len   register containing number of bytes
10282  * @param table register that will contain address of CRC table
10283  * @param tmp   scratch register
10284  */
10285 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10286   assert_different_registers(crc, buf, len, table, tmp, rax);
10287 
10288   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10289   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10290 
10291   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10292   // context for the registers used, where all instructions below are using 128-bit mode
10293   // On EVEX without VL and BW, these instructions will all be AVX.
10294   if (VM_Version::supports_avx512vlbw()) {
10295     movl(tmp, 0xffff);
10296     kmovwl(k1, tmp);
10297   }
10298 
10299   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10300   notl(crc); // ~crc
10301   cmpl(len, 16);
10302   jcc(Assembler::less, L_tail);
10303 
10304   // Align buffer to 16 bytes
10305   movl(tmp, buf);
10306   andl(tmp, 0xF);
10307   jccb(Assembler::zero, L_aligned);
10308   subl(tmp,  16);
10309   addl(len, tmp);
10310 
10311   align(4);
10312   BIND(L_align_loop);
10313   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10314   update_byte_crc32(crc, rax, table);
10315   increment(buf);
10316   incrementl(tmp);
10317   jccb(Assembler::less, L_align_loop);
10318 
10319   BIND(L_aligned);
10320   movl(tmp, len); // save
10321   shrl(len, 4);
10322   jcc(Assembler::zero, L_tail_restore);
10323 
10324   // Fold crc into first bytes of vector
10325   movdqa(xmm1, Address(buf, 0));
10326   movdl(rax, xmm1);
10327   xorl(crc, rax);
10328   if (VM_Version::supports_sse4_1()) {
10329     pinsrd(xmm1, crc, 0);
10330   } else {
10331     pinsrw(xmm1, crc, 0);
10332     shrl(crc, 16);
10333     pinsrw(xmm1, crc, 1);
10334   }
10335   addptr(buf, 16);
10336   subl(len, 4); // len > 0
10337   jcc(Assembler::less, L_fold_tail);
10338 
10339   movdqa(xmm2, Address(buf,  0));
10340   movdqa(xmm3, Address(buf, 16));
10341   movdqa(xmm4, Address(buf, 32));
10342   addptr(buf, 48);
10343   subl(len, 3);
10344   jcc(Assembler::lessEqual, L_fold_512b);
10345 
10346   // Fold total 512 bits of polynomial on each iteration,
10347   // 128 bits per each of 4 parallel streams.
10348   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10349 
10350   align(32);
10351   BIND(L_fold_512b_loop);
10352   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10353   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10354   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10355   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10356   addptr(buf, 64);
10357   subl(len, 4);
10358   jcc(Assembler::greater, L_fold_512b_loop);
10359 
10360   // Fold 512 bits to 128 bits.
10361   BIND(L_fold_512b);
10362   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10363   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10364   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10365   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10366 
10367   // Fold the rest of 128 bits data chunks
10368   BIND(L_fold_tail);
10369   addl(len, 3);
10370   jccb(Assembler::lessEqual, L_fold_128b);
10371   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10372 
10373   BIND(L_fold_tail_loop);
10374   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10375   addptr(buf, 16);
10376   decrementl(len);
10377   jccb(Assembler::greater, L_fold_tail_loop);
10378 
10379   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10380   BIND(L_fold_128b);
10381   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10382   if (UseAVX > 0) {
10383     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10384     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10385     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10386   } else {
10387     movdqa(xmm2, xmm0);
10388     pclmulqdq(xmm2, xmm1, 0x1);
10389     movdqa(xmm3, xmm0);
10390     pand(xmm3, xmm2);
10391     pclmulqdq(xmm0, xmm3, 0x1);
10392   }
10393   psrldq(xmm1, 8);
10394   psrldq(xmm2, 4);
10395   pxor(xmm0, xmm1);
10396   pxor(xmm0, xmm2);
10397 
10398   // 8 8-bit folds to compute 32-bit CRC.
10399   for (int j = 0; j < 4; j++) {
10400     fold_8bit_crc32(xmm0, table, xmm1, rax);
10401   }
10402   movdl(crc, xmm0); // mov 32 bits to general register
10403   for (int j = 0; j < 4; j++) {
10404     fold_8bit_crc32(crc, table, rax);
10405   }
10406 
10407   BIND(L_tail_restore);
10408   movl(len, tmp); // restore
10409   BIND(L_tail);
10410   andl(len, 0xf);
10411   jccb(Assembler::zero, L_exit);
10412 
10413   // Fold the rest of bytes
10414   align(4);
10415   BIND(L_tail_loop);
10416   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10417   update_byte_crc32(crc, rax, table);
10418   increment(buf);
10419   decrementl(len);
10420   jccb(Assembler::greater, L_tail_loop);
10421 
10422   BIND(L_exit);
10423   notl(crc); // ~c
10424 }
10425 
10426 #ifdef _LP64
10427 // S. Gueron / Information Processing Letters 112 (2012) 184
10428 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10429 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10430 // Output: the 64-bit carry-less product of B * CONST
10431 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10432                                      Register tmp1, Register tmp2, Register tmp3) {
10433   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10434   if (n > 0) {
10435     addq(tmp3, n * 256 * 8);
10436   }
10437   //    Q1 = TABLEExt[n][B & 0xFF];
10438   movl(tmp1, in);
10439   andl(tmp1, 0x000000FF);
10440   shll(tmp1, 3);
10441   addq(tmp1, tmp3);
10442   movq(tmp1, Address(tmp1, 0));
10443 
10444   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10445   movl(tmp2, in);
10446   shrl(tmp2, 8);
10447   andl(tmp2, 0x000000FF);
10448   shll(tmp2, 3);
10449   addq(tmp2, tmp3);
10450   movq(tmp2, Address(tmp2, 0));
10451 
10452   shlq(tmp2, 8);
10453   xorq(tmp1, tmp2);
10454 
10455   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10456   movl(tmp2, in);
10457   shrl(tmp2, 16);
10458   andl(tmp2, 0x000000FF);
10459   shll(tmp2, 3);
10460   addq(tmp2, tmp3);
10461   movq(tmp2, Address(tmp2, 0));
10462 
10463   shlq(tmp2, 16);
10464   xorq(tmp1, tmp2);
10465 
10466   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10467   shrl(in, 24);
10468   andl(in, 0x000000FF);
10469   shll(in, 3);
10470   addq(in, tmp3);
10471   movq(in, Address(in, 0));
10472 
10473   shlq(in, 24);
10474   xorq(in, tmp1);
10475   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10476 }
10477 
10478 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10479                                       Register in_out,
10480                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10481                                       XMMRegister w_xtmp2,
10482                                       Register tmp1,
10483                                       Register n_tmp2, Register n_tmp3) {
10484   if (is_pclmulqdq_supported) {
10485     movdl(w_xtmp1, in_out); // modified blindly
10486 
10487     movl(tmp1, const_or_pre_comp_const_index);
10488     movdl(w_xtmp2, tmp1);
10489     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10490 
10491     movdq(in_out, w_xtmp1);
10492   } else {
10493     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10494   }
10495 }
10496 
10497 // Recombination Alternative 2: No bit-reflections
10498 // T1 = (CRC_A * U1) << 1
10499 // T2 = (CRC_B * U2) << 1
10500 // C1 = T1 >> 32
10501 // C2 = T2 >> 32
10502 // T1 = T1 & 0xFFFFFFFF
10503 // T2 = T2 & 0xFFFFFFFF
10504 // T1 = CRC32(0, T1)
10505 // T2 = CRC32(0, T2)
10506 // C1 = C1 ^ T1
10507 // C2 = C2 ^ T2
10508 // CRC = C1 ^ C2 ^ CRC_C
10509 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,
10510                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10511                                      Register tmp1, Register tmp2,
10512                                      Register n_tmp3) {
10513   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10514   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10515   shlq(in_out, 1);
10516   movl(tmp1, in_out);
10517   shrq(in_out, 32);
10518   xorl(tmp2, tmp2);
10519   crc32(tmp2, tmp1, 4);
10520   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10521   shlq(in1, 1);
10522   movl(tmp1, in1);
10523   shrq(in1, 32);
10524   xorl(tmp2, tmp2);
10525   crc32(tmp2, tmp1, 4);
10526   xorl(in1, tmp2);
10527   xorl(in_out, in1);
10528   xorl(in_out, in2);
10529 }
10530 
10531 // Set N to predefined value
10532 // Subtract from a lenght of a buffer
10533 // execute in a loop:
10534 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10535 // for i = 1 to N do
10536 //  CRC_A = CRC32(CRC_A, A[i])
10537 //  CRC_B = CRC32(CRC_B, B[i])
10538 //  CRC_C = CRC32(CRC_C, C[i])
10539 // end for
10540 // Recombine
10541 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,
10542                                        Register in_out1, Register in_out2, Register in_out3,
10543                                        Register tmp1, Register tmp2, Register tmp3,
10544                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10545                                        Register tmp4, Register tmp5,
10546                                        Register n_tmp6) {
10547   Label L_processPartitions;
10548   Label L_processPartition;
10549   Label L_exit;
10550 
10551   bind(L_processPartitions);
10552   cmpl(in_out1, 3 * size);
10553   jcc(Assembler::less, L_exit);
10554     xorl(tmp1, tmp1);
10555     xorl(tmp2, tmp2);
10556     movq(tmp3, in_out2);
10557     addq(tmp3, size);
10558 
10559     bind(L_processPartition);
10560       crc32(in_out3, Address(in_out2, 0), 8);
10561       crc32(tmp1, Address(in_out2, size), 8);
10562       crc32(tmp2, Address(in_out2, size * 2), 8);
10563       addq(in_out2, 8);
10564       cmpq(in_out2, tmp3);
10565       jcc(Assembler::less, L_processPartition);
10566     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10567             w_xtmp1, w_xtmp2, w_xtmp3,
10568             tmp4, tmp5,
10569             n_tmp6);
10570     addq(in_out2, 2 * size);
10571     subl(in_out1, 3 * size);
10572     jmp(L_processPartitions);
10573 
10574   bind(L_exit);
10575 }
10576 #else
10577 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10578                                      Register tmp1, Register tmp2, Register tmp3,
10579                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10580   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10581   if (n > 0) {
10582     addl(tmp3, n * 256 * 8);
10583   }
10584   //    Q1 = TABLEExt[n][B & 0xFF];
10585   movl(tmp1, in_out);
10586   andl(tmp1, 0x000000FF);
10587   shll(tmp1, 3);
10588   addl(tmp1, tmp3);
10589   movq(xtmp1, Address(tmp1, 0));
10590 
10591   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10592   movl(tmp2, in_out);
10593   shrl(tmp2, 8);
10594   andl(tmp2, 0x000000FF);
10595   shll(tmp2, 3);
10596   addl(tmp2, tmp3);
10597   movq(xtmp2, Address(tmp2, 0));
10598 
10599   psllq(xtmp2, 8);
10600   pxor(xtmp1, xtmp2);
10601 
10602   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10603   movl(tmp2, in_out);
10604   shrl(tmp2, 16);
10605   andl(tmp2, 0x000000FF);
10606   shll(tmp2, 3);
10607   addl(tmp2, tmp3);
10608   movq(xtmp2, Address(tmp2, 0));
10609 
10610   psllq(xtmp2, 16);
10611   pxor(xtmp1, xtmp2);
10612 
10613   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10614   shrl(in_out, 24);
10615   andl(in_out, 0x000000FF);
10616   shll(in_out, 3);
10617   addl(in_out, tmp3);
10618   movq(xtmp2, Address(in_out, 0));
10619 
10620   psllq(xtmp2, 24);
10621   pxor(xtmp1, xtmp2); // Result in CXMM
10622   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10623 }
10624 
10625 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10626                                       Register in_out,
10627                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10628                                       XMMRegister w_xtmp2,
10629                                       Register tmp1,
10630                                       Register n_tmp2, Register n_tmp3) {
10631   if (is_pclmulqdq_supported) {
10632     movdl(w_xtmp1, in_out);
10633 
10634     movl(tmp1, const_or_pre_comp_const_index);
10635     movdl(w_xtmp2, tmp1);
10636     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10637     // Keep result in XMM since GPR is 32 bit in length
10638   } else {
10639     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10640   }
10641 }
10642 
10643 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,
10644                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10645                                      Register tmp1, Register tmp2,
10646                                      Register n_tmp3) {
10647   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10648   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10649 
10650   psllq(w_xtmp1, 1);
10651   movdl(tmp1, w_xtmp1);
10652   psrlq(w_xtmp1, 32);
10653   movdl(in_out, w_xtmp1);
10654 
10655   xorl(tmp2, tmp2);
10656   crc32(tmp2, tmp1, 4);
10657   xorl(in_out, tmp2);
10658 
10659   psllq(w_xtmp2, 1);
10660   movdl(tmp1, w_xtmp2);
10661   psrlq(w_xtmp2, 32);
10662   movdl(in1, w_xtmp2);
10663 
10664   xorl(tmp2, tmp2);
10665   crc32(tmp2, tmp1, 4);
10666   xorl(in1, tmp2);
10667   xorl(in_out, in1);
10668   xorl(in_out, in2);
10669 }
10670 
10671 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,
10672                                        Register in_out1, Register in_out2, Register in_out3,
10673                                        Register tmp1, Register tmp2, Register tmp3,
10674                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10675                                        Register tmp4, Register tmp5,
10676                                        Register n_tmp6) {
10677   Label L_processPartitions;
10678   Label L_processPartition;
10679   Label L_exit;
10680 
10681   bind(L_processPartitions);
10682   cmpl(in_out1, 3 * size);
10683   jcc(Assembler::less, L_exit);
10684     xorl(tmp1, tmp1);
10685     xorl(tmp2, tmp2);
10686     movl(tmp3, in_out2);
10687     addl(tmp3, size);
10688 
10689     bind(L_processPartition);
10690       crc32(in_out3, Address(in_out2, 0), 4);
10691       crc32(tmp1, Address(in_out2, size), 4);
10692       crc32(tmp2, Address(in_out2, size*2), 4);
10693       crc32(in_out3, Address(in_out2, 0+4), 4);
10694       crc32(tmp1, Address(in_out2, size+4), 4);
10695       crc32(tmp2, Address(in_out2, size*2+4), 4);
10696       addl(in_out2, 8);
10697       cmpl(in_out2, tmp3);
10698       jcc(Assembler::less, L_processPartition);
10699 
10700         push(tmp3);
10701         push(in_out1);
10702         push(in_out2);
10703         tmp4 = tmp3;
10704         tmp5 = in_out1;
10705         n_tmp6 = in_out2;
10706 
10707       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10708             w_xtmp1, w_xtmp2, w_xtmp3,
10709             tmp4, tmp5,
10710             n_tmp6);
10711 
10712         pop(in_out2);
10713         pop(in_out1);
10714         pop(tmp3);
10715 
10716     addl(in_out2, 2 * size);
10717     subl(in_out1, 3 * size);
10718     jmp(L_processPartitions);
10719 
10720   bind(L_exit);
10721 }
10722 #endif //LP64
10723 
10724 #ifdef _LP64
10725 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10726 // Input: A buffer I of L bytes.
10727 // Output: the CRC32C value of the buffer.
10728 // Notations:
10729 // Write L = 24N + r, with N = floor (L/24).
10730 // r = L mod 24 (0 <= r < 24).
10731 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10732 // N quadwords, and R consists of r bytes.
10733 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10734 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10735 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10736 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10737 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10738                                           Register tmp1, Register tmp2, Register tmp3,
10739                                           Register tmp4, Register tmp5, Register tmp6,
10740                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10741                                           bool is_pclmulqdq_supported) {
10742   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10743   Label L_wordByWord;
10744   Label L_byteByByteProlog;
10745   Label L_byteByByte;
10746   Label L_exit;
10747 
10748   if (is_pclmulqdq_supported ) {
10749     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10750     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10751 
10752     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10753     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10754 
10755     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10756     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10757     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10758   } else {
10759     const_or_pre_comp_const_index[0] = 1;
10760     const_or_pre_comp_const_index[1] = 0;
10761 
10762     const_or_pre_comp_const_index[2] = 3;
10763     const_or_pre_comp_const_index[3] = 2;
10764 
10765     const_or_pre_comp_const_index[4] = 5;
10766     const_or_pre_comp_const_index[5] = 4;
10767    }
10768   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10769                     in2, in1, in_out,
10770                     tmp1, tmp2, tmp3,
10771                     w_xtmp1, w_xtmp2, w_xtmp3,
10772                     tmp4, tmp5,
10773                     tmp6);
10774   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10775                     in2, in1, in_out,
10776                     tmp1, tmp2, tmp3,
10777                     w_xtmp1, w_xtmp2, w_xtmp3,
10778                     tmp4, tmp5,
10779                     tmp6);
10780   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10781                     in2, in1, in_out,
10782                     tmp1, tmp2, tmp3,
10783                     w_xtmp1, w_xtmp2, w_xtmp3,
10784                     tmp4, tmp5,
10785                     tmp6);
10786   movl(tmp1, in2);
10787   andl(tmp1, 0x00000007);
10788   negl(tmp1);
10789   addl(tmp1, in2);
10790   addq(tmp1, in1);
10791 
10792   BIND(L_wordByWord);
10793   cmpq(in1, tmp1);
10794   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10795     crc32(in_out, Address(in1, 0), 4);
10796     addq(in1, 4);
10797     jmp(L_wordByWord);
10798 
10799   BIND(L_byteByByteProlog);
10800   andl(in2, 0x00000007);
10801   movl(tmp2, 1);
10802 
10803   BIND(L_byteByByte);
10804   cmpl(tmp2, in2);
10805   jccb(Assembler::greater, L_exit);
10806     crc32(in_out, Address(in1, 0), 1);
10807     incq(in1);
10808     incl(tmp2);
10809     jmp(L_byteByByte);
10810 
10811   BIND(L_exit);
10812 }
10813 #else
10814 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10815                                           Register tmp1, Register  tmp2, Register tmp3,
10816                                           Register tmp4, Register  tmp5, Register tmp6,
10817                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10818                                           bool is_pclmulqdq_supported) {
10819   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10820   Label L_wordByWord;
10821   Label L_byteByByteProlog;
10822   Label L_byteByByte;
10823   Label L_exit;
10824 
10825   if (is_pclmulqdq_supported) {
10826     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10827     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10828 
10829     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10830     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10831 
10832     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10833     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10834   } else {
10835     const_or_pre_comp_const_index[0] = 1;
10836     const_or_pre_comp_const_index[1] = 0;
10837 
10838     const_or_pre_comp_const_index[2] = 3;
10839     const_or_pre_comp_const_index[3] = 2;
10840 
10841     const_or_pre_comp_const_index[4] = 5;
10842     const_or_pre_comp_const_index[5] = 4;
10843   }
10844   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10845                     in2, in1, in_out,
10846                     tmp1, tmp2, tmp3,
10847                     w_xtmp1, w_xtmp2, w_xtmp3,
10848                     tmp4, tmp5,
10849                     tmp6);
10850   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10851                     in2, in1, in_out,
10852                     tmp1, tmp2, tmp3,
10853                     w_xtmp1, w_xtmp2, w_xtmp3,
10854                     tmp4, tmp5,
10855                     tmp6);
10856   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10857                     in2, in1, in_out,
10858                     tmp1, tmp2, tmp3,
10859                     w_xtmp1, w_xtmp2, w_xtmp3,
10860                     tmp4, tmp5,
10861                     tmp6);
10862   movl(tmp1, in2);
10863   andl(tmp1, 0x00000007);
10864   negl(tmp1);
10865   addl(tmp1, in2);
10866   addl(tmp1, in1);
10867 
10868   BIND(L_wordByWord);
10869   cmpl(in1, tmp1);
10870   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10871     crc32(in_out, Address(in1,0), 4);
10872     addl(in1, 4);
10873     jmp(L_wordByWord);
10874 
10875   BIND(L_byteByByteProlog);
10876   andl(in2, 0x00000007);
10877   movl(tmp2, 1);
10878 
10879   BIND(L_byteByByte);
10880   cmpl(tmp2, in2);
10881   jccb(Assembler::greater, L_exit);
10882     movb(tmp1, Address(in1, 0));
10883     crc32(in_out, tmp1, 1);
10884     incl(in1);
10885     incl(tmp2);
10886     jmp(L_byteByByte);
10887 
10888   BIND(L_exit);
10889 }
10890 #endif // LP64
10891 #undef BIND
10892 #undef BLOCK_COMMENT
10893 
10894 // Compress char[] array to byte[].
10895 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10896 //   @HotSpotIntrinsicCandidate
10897 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10898 //     for (int i = 0; i < len; i++) {
10899 //       int c = src[srcOff++];
10900 //       if (c >>> 8 != 0) {
10901 //         return 0;
10902 //       }
10903 //       dst[dstOff++] = (byte)c;
10904 //     }
10905 //     return len;
10906 //   }
10907 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10908   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10909   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10910   Register tmp5, Register result) {
10911   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10912 
10913   // rsi: src
10914   // rdi: dst
10915   // rdx: len
10916   // rcx: tmp5
10917   // rax: result
10918 
10919   // rsi holds start addr of source char[] to be compressed
10920   // rdi holds start addr of destination byte[]
10921   // rdx holds length
10922 
10923   assert(len != result, "");
10924 
10925   // save length for return
10926   push(len);
10927 
10928   if ((UseAVX > 2) && // AVX512
10929     VM_Version::supports_avx512vlbw() &&
10930     VM_Version::supports_bmi2()) {
10931 
10932     set_vector_masking();  // opening of the stub context for programming mask registers
10933 
10934     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10935 
10936     // alignement
10937     Label post_alignement;
10938 
10939     // if length of the string is less than 16, handle it in an old fashioned
10940     // way
10941     testl(len, -32);
10942     jcc(Assembler::zero, below_threshold);
10943 
10944     // First check whether a character is compressable ( <= 0xFF).
10945     // Create mask to test for Unicode chars inside zmm vector
10946     movl(result, 0x00FF);
10947     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10948 
10949     // Save k1
10950     kmovql(k3, k1);
10951 
10952     testl(len, -64);
10953     jcc(Assembler::zero, post_alignement);
10954 
10955     movl(tmp5, dst);
10956     andl(tmp5, (32 - 1));
10957     negl(tmp5);
10958     andl(tmp5, (32 - 1));
10959 
10960     // bail out when there is nothing to be done
10961     testl(tmp5, 0xFFFFFFFF);
10962     jcc(Assembler::zero, post_alignement);
10963 
10964     // ~(~0 << len), where len is the # of remaining elements to process
10965     movl(result, 0xFFFFFFFF);
10966     shlxl(result, result, tmp5);
10967     notl(result);
10968     kmovdl(k1, result);
10969 
10970     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10971     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10972     ktestd(k2, k1);
10973     jcc(Assembler::carryClear, restore_k1_return_zero);
10974 
10975     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10976 
10977     addptr(src, tmp5);
10978     addptr(src, tmp5);
10979     addptr(dst, tmp5);
10980     subl(len, tmp5);
10981 
10982     bind(post_alignement);
10983     // end of alignement
10984 
10985     movl(tmp5, len);
10986     andl(tmp5, (32 - 1));    // tail count (in chars)
10987     andl(len, ~(32 - 1));    // vector count (in chars)
10988     jcc(Assembler::zero, copy_loop_tail);
10989 
10990     lea(src, Address(src, len, Address::times_2));
10991     lea(dst, Address(dst, len, Address::times_1));
10992     negptr(len);
10993 
10994     bind(copy_32_loop);
10995     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10996     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10997     kortestdl(k2, k2);
10998     jcc(Assembler::carryClear, restore_k1_return_zero);
10999 
11000     // All elements in current processed chunk are valid candidates for
11001     // compression. Write a truncated byte elements to the memory.
11002     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
11003     addptr(len, 32);
11004     jcc(Assembler::notZero, copy_32_loop);
11005 
11006     bind(copy_loop_tail);
11007     // bail out when there is nothing to be done
11008     testl(tmp5, 0xFFFFFFFF);
11009     // Restore k1
11010     kmovql(k1, k3);
11011     jcc(Assembler::zero, return_length);
11012 
11013     movl(len, tmp5);
11014 
11015     // ~(~0 << len), where len is the # of remaining elements to process
11016     movl(result, 0xFFFFFFFF);
11017     shlxl(result, result, len);
11018     notl(result);
11019 
11020     kmovdl(k1, result);
11021 
11022     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11023     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11024     ktestd(k2, k1);
11025     jcc(Assembler::carryClear, restore_k1_return_zero);
11026 
11027     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11028     // Restore k1
11029     kmovql(k1, k3);
11030     jmp(return_length);
11031 
11032     bind(restore_k1_return_zero);
11033     // Restore k1
11034     kmovql(k1, k3);
11035     jmp(return_zero);
11036 
11037     clear_vector_masking();   // closing of the stub context for programming mask registers
11038   }
11039   if (UseSSE42Intrinsics) {
11040     Label copy_32_loop, copy_16, copy_tail;
11041 
11042     bind(below_threshold);
11043 
11044     movl(result, len);
11045 
11046     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
11047 
11048     // vectored compression
11049     andl(len, 0xfffffff0);    // vector count (in chars)
11050     andl(result, 0x0000000f);    // tail count (in chars)
11051     testl(len, len);
11052     jccb(Assembler::zero, copy_16);
11053 
11054     // compress 16 chars per iter
11055     movdl(tmp1Reg, tmp5);
11056     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11057     pxor(tmp4Reg, tmp4Reg);
11058 
11059     lea(src, Address(src, len, Address::times_2));
11060     lea(dst, Address(dst, len, Address::times_1));
11061     negptr(len);
11062 
11063     bind(copy_32_loop);
11064     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
11065     por(tmp4Reg, tmp2Reg);
11066     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
11067     por(tmp4Reg, tmp3Reg);
11068     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
11069     jcc(Assembler::notZero, return_zero);
11070     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
11071     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
11072     addptr(len, 16);
11073     jcc(Assembler::notZero, copy_32_loop);
11074 
11075     // compress next vector of 8 chars (if any)
11076     bind(copy_16);
11077     movl(len, result);
11078     andl(len, 0xfffffff8);    // vector count (in chars)
11079     andl(result, 0x00000007);    // tail count (in chars)
11080     testl(len, len);
11081     jccb(Assembler::zero, copy_tail);
11082 
11083     movdl(tmp1Reg, tmp5);
11084     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11085     pxor(tmp3Reg, tmp3Reg);
11086 
11087     movdqu(tmp2Reg, Address(src, 0));
11088     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
11089     jccb(Assembler::notZero, return_zero);
11090     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
11091     movq(Address(dst, 0), tmp2Reg);
11092     addptr(src, 16);
11093     addptr(dst, 8);
11094 
11095     bind(copy_tail);
11096     movl(len, result);
11097   }
11098   // compress 1 char per iter
11099   testl(len, len);
11100   jccb(Assembler::zero, return_length);
11101   lea(src, Address(src, len, Address::times_2));
11102   lea(dst, Address(dst, len, Address::times_1));
11103   negptr(len);
11104 
11105   bind(copy_chars_loop);
11106   load_unsigned_short(result, Address(src, len, Address::times_2));
11107   testl(result, 0xff00);      // check if Unicode char
11108   jccb(Assembler::notZero, return_zero);
11109   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
11110   increment(len);
11111   jcc(Assembler::notZero, copy_chars_loop);
11112 
11113   // if compression succeeded, return length
11114   bind(return_length);
11115   pop(result);
11116   jmpb(done);
11117 
11118   // if compression failed, return 0
11119   bind(return_zero);
11120   xorl(result, result);
11121   addptr(rsp, wordSize);
11122 
11123   bind(done);
11124 }
11125 
11126 // Inflate byte[] array to char[].
11127 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
11128 //   @HotSpotIntrinsicCandidate
11129 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
11130 //     for (int i = 0; i < len; i++) {
11131 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
11132 //     }
11133 //   }
11134 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
11135   XMMRegister tmp1, Register tmp2) {
11136   Label copy_chars_loop, done, below_threshold;
11137   // rsi: src
11138   // rdi: dst
11139   // rdx: len
11140   // rcx: tmp2
11141 
11142   // rsi holds start addr of source byte[] to be inflated
11143   // rdi holds start addr of destination char[]
11144   // rdx holds length
11145   assert_different_registers(src, dst, len, tmp2);
11146 
11147   if ((UseAVX > 2) && // AVX512
11148     VM_Version::supports_avx512vlbw() &&
11149     VM_Version::supports_bmi2()) {
11150 
11151     set_vector_masking();  // opening of the stub context for programming mask registers
11152 
11153     Label copy_32_loop, copy_tail;
11154     Register tmp3_aliased = len;
11155 
11156     // if length of the string is less than 16, handle it in an old fashioned
11157     // way
11158     testl(len, -16);
11159     jcc(Assembler::zero, below_threshold);
11160 
11161     // In order to use only one arithmetic operation for the main loop we use
11162     // this pre-calculation
11163     movl(tmp2, len);
11164     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
11165     andl(len, -32);     // vector count
11166     jccb(Assembler::zero, copy_tail);
11167 
11168     lea(src, Address(src, len, Address::times_1));
11169     lea(dst, Address(dst, len, Address::times_2));
11170     negptr(len);
11171 
11172 
11173     // inflate 32 chars per iter
11174     bind(copy_32_loop);
11175     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
11176     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
11177     addptr(len, 32);
11178     jcc(Assembler::notZero, copy_32_loop);
11179 
11180     bind(copy_tail);
11181     // bail out when there is nothing to be done
11182     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
11183     jcc(Assembler::zero, done);
11184 
11185     // Save k1
11186     kmovql(k2, k1);
11187 
11188     // ~(~0 << length), where length is the # of remaining elements to process
11189     movl(tmp3_aliased, -1);
11190     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
11191     notl(tmp3_aliased);
11192     kmovdl(k1, tmp3_aliased);
11193     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
11194     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
11195 
11196     // Restore k1
11197     kmovql(k1, k2);
11198     jmp(done);
11199 
11200     clear_vector_masking();   // closing of the stub context for programming mask registers
11201   }
11202   if (UseSSE42Intrinsics) {
11203     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
11204 
11205     movl(tmp2, len);
11206 
11207     if (UseAVX > 1) {
11208       andl(tmp2, (16 - 1));
11209       andl(len, -16);
11210       jccb(Assembler::zero, copy_new_tail);
11211     } else {
11212       andl(tmp2, 0x00000007);   // tail count (in chars)
11213       andl(len, 0xfffffff8);    // vector count (in chars)
11214       jccb(Assembler::zero, copy_tail);
11215     }
11216 
11217     // vectored inflation
11218     lea(src, Address(src, len, Address::times_1));
11219     lea(dst, Address(dst, len, Address::times_2));
11220     negptr(len);
11221 
11222     if (UseAVX > 1) {
11223       bind(copy_16_loop);
11224       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
11225       vmovdqu(Address(dst, len, Address::times_2), tmp1);
11226       addptr(len, 16);
11227       jcc(Assembler::notZero, copy_16_loop);
11228 
11229       bind(below_threshold);
11230       bind(copy_new_tail);
11231       if ((UseAVX > 2) &&
11232         VM_Version::supports_avx512vlbw() &&
11233         VM_Version::supports_bmi2()) {
11234         movl(tmp2, len);
11235       } else {
11236         movl(len, tmp2);
11237       }
11238       andl(tmp2, 0x00000007);
11239       andl(len, 0xFFFFFFF8);
11240       jccb(Assembler::zero, copy_tail);
11241 
11242       pmovzxbw(tmp1, Address(src, 0));
11243       movdqu(Address(dst, 0), tmp1);
11244       addptr(src, 8);
11245       addptr(dst, 2 * 8);
11246 
11247       jmp(copy_tail, true);
11248     }
11249 
11250     // inflate 8 chars per iter
11251     bind(copy_8_loop);
11252     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
11253     movdqu(Address(dst, len, Address::times_2), tmp1);
11254     addptr(len, 8);
11255     jcc(Assembler::notZero, copy_8_loop);
11256 
11257     bind(copy_tail);
11258     movl(len, tmp2);
11259 
11260     cmpl(len, 4);
11261     jccb(Assembler::less, copy_bytes);
11262 
11263     movdl(tmp1, Address(src, 0));  // load 4 byte chars
11264     pmovzxbw(tmp1, tmp1);
11265     movq(Address(dst, 0), tmp1);
11266     subptr(len, 4);
11267     addptr(src, 4);
11268     addptr(dst, 8);
11269 
11270     bind(copy_bytes);
11271   }
11272   testl(len, len);
11273   jccb(Assembler::zero, done);
11274   lea(src, Address(src, len, Address::times_1));
11275   lea(dst, Address(dst, len, Address::times_2));
11276   negptr(len);
11277 
11278   // inflate 1 char per iter
11279   bind(copy_chars_loop);
11280   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11281   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11282   increment(len);
11283   jcc(Assembler::notZero, copy_chars_loop);
11284 
11285   bind(done);
11286 }
11287 
11288 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11289   switch (cond) {
11290     // Note some conditions are synonyms for others
11291     case Assembler::zero:         return Assembler::notZero;
11292     case Assembler::notZero:      return Assembler::zero;
11293     case Assembler::less:         return Assembler::greaterEqual;
11294     case Assembler::lessEqual:    return Assembler::greater;
11295     case Assembler::greater:      return Assembler::lessEqual;
11296     case Assembler::greaterEqual: return Assembler::less;
11297     case Assembler::below:        return Assembler::aboveEqual;
11298     case Assembler::belowEqual:   return Assembler::above;
11299     case Assembler::above:        return Assembler::belowEqual;
11300     case Assembler::aboveEqual:   return Assembler::below;
11301     case Assembler::overflow:     return Assembler::noOverflow;
11302     case Assembler::noOverflow:   return Assembler::overflow;
11303     case Assembler::negative:     return Assembler::positive;
11304     case Assembler::positive:     return Assembler::negative;
11305     case Assembler::parity:       return Assembler::noParity;
11306     case Assembler::noParity:     return Assembler::parity;
11307   }
11308   ShouldNotReachHere(); return Assembler::overflow;
11309 }
11310 
11311 SkipIfEqual::SkipIfEqual(
11312     MacroAssembler* masm, const bool* flag_addr, bool value) {
11313   _masm = masm;
11314   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11315   _masm->jcc(Assembler::equal, _label);
11316 }
11317 
11318 SkipIfEqual::~SkipIfEqual() {
11319   _masm->bind(_label);
11320 }
11321 
11322 // 32-bit Windows has its own fast-path implementation
11323 // of get_thread
11324 #if !defined(WIN32) || defined(_LP64)
11325 
11326 // This is simply a call to Thread::current()
11327 void MacroAssembler::get_thread(Register thread) {
11328   if (thread != rax) {
11329     push(rax);
11330   }
11331   LP64_ONLY(push(rdi);)
11332   LP64_ONLY(push(rsi);)
11333   push(rdx);
11334   push(rcx);
11335 #ifdef _LP64
11336   push(r8);
11337   push(r9);
11338   push(r10);
11339   push(r11);
11340 #endif
11341 
11342   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11343 
11344 #ifdef _LP64
11345   pop(r11);
11346   pop(r10);
11347   pop(r9);
11348   pop(r8);
11349 #endif
11350   pop(rcx);
11351   pop(rdx);
11352   LP64_ONLY(pop(rsi);)
11353   LP64_ONLY(pop(rdi);)
11354   if (thread != rax) {
11355     mov(thread, rax);
11356     pop(rax);
11357   }
11358 }
11359 
11360 #endif