rev 47398 : 8166317: InterpreterCodeSize should be computed
Reviewed-by: kvn, coleenp

   1 /*
   2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "asm/assembler.hpp"
  27 #include "asm/assembler.inline.hpp"
  28 #include "compiler/disassembler.hpp"
  29 #include "gc/shared/cardTableModRefBS.hpp"
  30 #include "gc/shared/collectedHeap.inline.hpp"
  31 #include "interpreter/interpreter.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "memory/universe.hpp"
  34 #include "oops/klass.inline.hpp"
  35 #include "prims/jvm.h"
  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/sharedRuntime.hpp"
  42 #include "runtime/stubRoutines.hpp"
  43 #include "runtime/thread.hpp"
  44 #include "utilities/macros.hpp"
  45 #if INCLUDE_ALL_GCS
  46 #include "gc/g1/g1CollectedHeap.inline.hpp"
  47 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  48 #include "gc/g1/heapRegion.hpp"
  49 #endif // INCLUDE_ALL_GCS
  50 #include "crc32c.h"
  51 #ifdef COMPILER2
  52 #include "opto/intrinsicnode.hpp"
  53 #endif
  54 
  55 #ifdef PRODUCT
  56 #define BLOCK_COMMENT(str) /* nothing */
  57 #define STOP(error) stop(error)
  58 #else
  59 #define BLOCK_COMMENT(str) block_comment(str)
  60 #define STOP(error) block_comment(error); stop(error)
  61 #endif
  62 
  63 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  64 
  65 #ifdef ASSERT
  66 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  67 #endif
  68 
  69 static Assembler::Condition reverse[] = {
  70     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  71     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  72     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  73     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  74     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  75     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  76     Assembler::above          /* belowEqual    = 0x6 */ ,
  77     Assembler::belowEqual     /* above         = 0x7 */ ,
  78     Assembler::positive       /* negative      = 0x8 */ ,
  79     Assembler::negative       /* positive      = 0x9 */ ,
  80     Assembler::noParity       /* parity        = 0xa */ ,
  81     Assembler::parity         /* noParity      = 0xb */ ,
  82     Assembler::greaterEqual   /* less          = 0xc */ ,
  83     Assembler::less           /* greaterEqual  = 0xd */ ,
  84     Assembler::greater        /* lessEqual     = 0xe */ ,
  85     Assembler::lessEqual      /* greater       = 0xf, */
  86 
  87 };
  88 
  89 
  90 // Implementation of MacroAssembler
  91 
  92 // First all the versions that have distinct versions depending on 32/64 bit
  93 // Unless the difference is trivial (1 line or so).
  94 
  95 #ifndef _LP64
  96 
  97 // 32bit versions
  98 
  99 Address MacroAssembler::as_Address(AddressLiteral adr) {
 100   return Address(adr.target(), adr.rspec());
 101 }
 102 
 103 Address MacroAssembler::as_Address(ArrayAddress adr) {
 104   return Address::make_array(adr);
 105 }
 106 
 107 void MacroAssembler::call_VM_leaf_base(address entry_point,
 108                                        int number_of_arguments) {
 109   call(RuntimeAddress(entry_point));
 110   increment(rsp, number_of_arguments * wordSize);
 111 }
 112 
 113 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 114   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 115 }
 116 
 117 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 118   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 119 }
 120 
 121 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 122   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 123 }
 124 
 125 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 126   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 127 }
 128 
 129 void MacroAssembler::extend_sign(Register hi, Register lo) {
 130   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 131   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 132     cdql();
 133   } else {
 134     movl(hi, lo);
 135     sarl(hi, 31);
 136   }
 137 }
 138 
 139 void MacroAssembler::jC2(Register tmp, Label& L) {
 140   // set parity bit if FPU flag C2 is set (via rax)
 141   save_rax(tmp);
 142   fwait(); fnstsw_ax();
 143   sahf();
 144   restore_rax(tmp);
 145   // branch
 146   jcc(Assembler::parity, L);
 147 }
 148 
 149 void MacroAssembler::jnC2(Register tmp, Label& L) {
 150   // set parity bit if FPU flag C2 is set (via rax)
 151   save_rax(tmp);
 152   fwait(); fnstsw_ax();
 153   sahf();
 154   restore_rax(tmp);
 155   // branch
 156   jcc(Assembler::noParity, L);
 157 }
 158 
 159 // 32bit can do a case table jump in one instruction but we no longer allow the base
 160 // to be installed in the Address class
 161 void MacroAssembler::jump(ArrayAddress entry) {
 162   jmp(as_Address(entry));
 163 }
 164 
 165 // Note: y_lo will be destroyed
 166 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 167   // Long compare for Java (semantics as described in JVM spec.)
 168   Label high, low, done;
 169 
 170   cmpl(x_hi, y_hi);
 171   jcc(Assembler::less, low);
 172   jcc(Assembler::greater, high);
 173   // x_hi is the return register
 174   xorl(x_hi, x_hi);
 175   cmpl(x_lo, y_lo);
 176   jcc(Assembler::below, low);
 177   jcc(Assembler::equal, done);
 178 
 179   bind(high);
 180   xorl(x_hi, x_hi);
 181   increment(x_hi);
 182   jmp(done);
 183 
 184   bind(low);
 185   xorl(x_hi, x_hi);
 186   decrementl(x_hi);
 187 
 188   bind(done);
 189 }
 190 
 191 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 192     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 193 }
 194 
 195 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 196   // leal(dst, as_Address(adr));
 197   // see note in movl as to why we must use a move
 198   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 199 }
 200 
 201 void MacroAssembler::leave() {
 202   mov(rsp, rbp);
 203   pop(rbp);
 204 }
 205 
 206 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 207   // Multiplication of two Java long values stored on the stack
 208   // as illustrated below. Result is in rdx:rax.
 209   //
 210   // rsp ---> [  ??  ] \               \
 211   //            ....    | y_rsp_offset  |
 212   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 213   //          [ y_hi ]                  | (in bytes)
 214   //            ....                    |
 215   //          [ x_lo ]                 /
 216   //          [ x_hi ]
 217   //            ....
 218   //
 219   // Basic idea: lo(result) = lo(x_lo * y_lo)
 220   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 221   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 222   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 223   Label quick;
 224   // load x_hi, y_hi and check if quick
 225   // multiplication is possible
 226   movl(rbx, x_hi);
 227   movl(rcx, y_hi);
 228   movl(rax, rbx);
 229   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 230   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 231   // do full multiplication
 232   // 1st step
 233   mull(y_lo);                                    // x_hi * y_lo
 234   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 235   // 2nd step
 236   movl(rax, x_lo);
 237   mull(rcx);                                     // x_lo * y_hi
 238   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 239   // 3rd step
 240   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 241   movl(rax, x_lo);
 242   mull(y_lo);                                    // x_lo * y_lo
 243   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 244 }
 245 
 246 void MacroAssembler::lneg(Register hi, Register lo) {
 247   negl(lo);
 248   adcl(hi, 0);
 249   negl(hi);
 250 }
 251 
 252 void MacroAssembler::lshl(Register hi, Register lo) {
 253   // Java shift left long support (semantics as described in JVM spec., p.305)
 254   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 255   // shift value is in rcx !
 256   assert(hi != rcx, "must not use rcx");
 257   assert(lo != rcx, "must not use rcx");
 258   const Register s = rcx;                        // shift count
 259   const int      n = BitsPerWord;
 260   Label L;
 261   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 262   cmpl(s, n);                                    // if (s < n)
 263   jcc(Assembler::less, L);                       // else (s >= n)
 264   movl(hi, lo);                                  // x := x << n
 265   xorl(lo, lo);
 266   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 267   bind(L);                                       // s (mod n) < n
 268   shldl(hi, lo);                                 // x := x << s
 269   shll(lo);
 270 }
 271 
 272 
 273 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 274   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 275   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 276   assert(hi != rcx, "must not use rcx");
 277   assert(lo != rcx, "must not use rcx");
 278   const Register s = rcx;                        // shift count
 279   const int      n = BitsPerWord;
 280   Label L;
 281   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 282   cmpl(s, n);                                    // if (s < n)
 283   jcc(Assembler::less, L);                       // else (s >= n)
 284   movl(lo, hi);                                  // x := x >> n
 285   if (sign_extension) sarl(hi, 31);
 286   else                xorl(hi, hi);
 287   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 288   bind(L);                                       // s (mod n) < n
 289   shrdl(lo, hi);                                 // x := x >> s
 290   if (sign_extension) sarl(hi);
 291   else                shrl(hi);
 292 }
 293 
 294 void MacroAssembler::movoop(Register dst, jobject obj) {
 295   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 296 }
 297 
 298 void MacroAssembler::movoop(Address dst, jobject obj) {
 299   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 300 }
 301 
 302 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 303   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 304 }
 305 
 306 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 307   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 308 }
 309 
 310 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 311   // scratch register is not used,
 312   // it is defined to match parameters of 64-bit version of this method.
 313   if (src.is_lval()) {
 314     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 315   } else {
 316     movl(dst, as_Address(src));
 317   }
 318 }
 319 
 320 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 321   movl(as_Address(dst), src);
 322 }
 323 
 324 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 325   movl(dst, as_Address(src));
 326 }
 327 
 328 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 329 void MacroAssembler::movptr(Address dst, intptr_t src) {
 330   movl(dst, src);
 331 }
 332 
 333 
 334 void MacroAssembler::pop_callee_saved_registers() {
 335   pop(rcx);
 336   pop(rdx);
 337   pop(rdi);
 338   pop(rsi);
 339 }
 340 
 341 void MacroAssembler::pop_fTOS() {
 342   fld_d(Address(rsp, 0));
 343   addl(rsp, 2 * wordSize);
 344 }
 345 
 346 void MacroAssembler::push_callee_saved_registers() {
 347   push(rsi);
 348   push(rdi);
 349   push(rdx);
 350   push(rcx);
 351 }
 352 
 353 void MacroAssembler::push_fTOS() {
 354   subl(rsp, 2 * wordSize);
 355   fstp_d(Address(rsp, 0));
 356 }
 357 
 358 
 359 void MacroAssembler::pushoop(jobject obj) {
 360   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 361 }
 362 
 363 void MacroAssembler::pushklass(Metadata* obj) {
 364   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 365 }
 366 
 367 void MacroAssembler::pushptr(AddressLiteral src) {
 368   if (src.is_lval()) {
 369     push_literal32((int32_t)src.target(), src.rspec());
 370   } else {
 371     pushl(as_Address(src));
 372   }
 373 }
 374 
 375 void MacroAssembler::set_word_if_not_zero(Register dst) {
 376   xorl(dst, dst);
 377   set_byte_if_not_zero(dst);
 378 }
 379 
 380 static void pass_arg0(MacroAssembler* masm, Register arg) {
 381   masm->push(arg);
 382 }
 383 
 384 static void pass_arg1(MacroAssembler* masm, Register arg) {
 385   masm->push(arg);
 386 }
 387 
 388 static void pass_arg2(MacroAssembler* masm, Register arg) {
 389   masm->push(arg);
 390 }
 391 
 392 static void pass_arg3(MacroAssembler* masm, Register arg) {
 393   masm->push(arg);
 394 }
 395 
 396 #ifndef PRODUCT
 397 extern "C" void findpc(intptr_t x);
 398 #endif
 399 
 400 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 401   // In order to get locks to work, we need to fake a in_VM state
 402   JavaThread* thread = JavaThread::current();
 403   JavaThreadState saved_state = thread->thread_state();
 404   thread->set_thread_state(_thread_in_vm);
 405   if (ShowMessageBoxOnError) {
 406     JavaThread* thread = JavaThread::current();
 407     JavaThreadState saved_state = thread->thread_state();
 408     thread->set_thread_state(_thread_in_vm);
 409     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 410       ttyLocker ttyl;
 411       BytecodeCounter::print();
 412     }
 413     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 414     // This is the value of eip which points to where verify_oop will return.
 415     if (os::message_box(msg, "Execution stopped, print registers?")) {
 416       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 417       BREAKPOINT;
 418     }
 419   } else {
 420     ttyLocker ttyl;
 421     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 422   }
 423   // Don't assert holding the ttyLock
 424     assert(false, "DEBUG MESSAGE: %s", msg);
 425   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 426 }
 427 
 428 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 429   ttyLocker ttyl;
 430   FlagSetting fs(Debugging, true);
 431   tty->print_cr("eip = 0x%08x", eip);
 432 #ifndef PRODUCT
 433   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 434     tty->cr();
 435     findpc(eip);
 436     tty->cr();
 437   }
 438 #endif
 439 #define PRINT_REG(rax) \
 440   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 441   PRINT_REG(rax);
 442   PRINT_REG(rbx);
 443   PRINT_REG(rcx);
 444   PRINT_REG(rdx);
 445   PRINT_REG(rdi);
 446   PRINT_REG(rsi);
 447   PRINT_REG(rbp);
 448   PRINT_REG(rsp);
 449 #undef PRINT_REG
 450   // Print some words near top of staack.
 451   int* dump_sp = (int*) rsp;
 452   for (int col1 = 0; col1 < 8; col1++) {
 453     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 454     os::print_location(tty, *dump_sp++);
 455   }
 456   for (int row = 0; row < 16; row++) {
 457     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 458     for (int col = 0; col < 8; col++) {
 459       tty->print(" 0x%08x", *dump_sp++);
 460     }
 461     tty->cr();
 462   }
 463   // Print some instructions around pc:
 464   Disassembler::decode((address)eip-64, (address)eip);
 465   tty->print_cr("--------");
 466   Disassembler::decode((address)eip, (address)eip+32);
 467 }
 468 
 469 void MacroAssembler::stop(const char* msg) {
 470   ExternalAddress message((address)msg);
 471   // push address of message
 472   pushptr(message.addr());
 473   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 474   pusha();                                            // push registers
 475   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 476   hlt();
 477 }
 478 
 479 void MacroAssembler::warn(const char* msg) {
 480   push_CPU_state();
 481 
 482   ExternalAddress message((address) msg);
 483   // push address of message
 484   pushptr(message.addr());
 485 
 486   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 487   addl(rsp, wordSize);       // discard argument
 488   pop_CPU_state();
 489 }
 490 
 491 void MacroAssembler::print_state() {
 492   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 493   pusha();                                            // push registers
 494 
 495   push_CPU_state();
 496   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 497   pop_CPU_state();
 498 
 499   popa();
 500   addl(rsp, wordSize);
 501 }
 502 
 503 #else // _LP64
 504 
 505 // 64 bit versions
 506 
 507 Address MacroAssembler::as_Address(AddressLiteral adr) {
 508   // amd64 always does this as a pc-rel
 509   // we can be absolute or disp based on the instruction type
 510   // jmp/call are displacements others are absolute
 511   assert(!adr.is_lval(), "must be rval");
 512   assert(reachable(adr), "must be");
 513   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 514 
 515 }
 516 
 517 Address MacroAssembler::as_Address(ArrayAddress adr) {
 518   AddressLiteral base = adr.base();
 519   lea(rscratch1, base);
 520   Address index = adr.index();
 521   assert(index._disp == 0, "must not have disp"); // maybe it can?
 522   Address array(rscratch1, index._index, index._scale, index._disp);
 523   return array;
 524 }
 525 
 526 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 527   Label L, E;
 528 
 529 #ifdef _WIN64
 530   // Windows always allocates space for it's register args
 531   assert(num_args <= 4, "only register arguments supported");
 532   subq(rsp,  frame::arg_reg_save_area_bytes);
 533 #endif
 534 
 535   // Align stack if necessary
 536   testl(rsp, 15);
 537   jcc(Assembler::zero, L);
 538 
 539   subq(rsp, 8);
 540   {
 541     call(RuntimeAddress(entry_point));
 542   }
 543   addq(rsp, 8);
 544   jmp(E);
 545 
 546   bind(L);
 547   {
 548     call(RuntimeAddress(entry_point));
 549   }
 550 
 551   bind(E);
 552 
 553 #ifdef _WIN64
 554   // restore stack pointer
 555   addq(rsp, frame::arg_reg_save_area_bytes);
 556 #endif
 557 
 558 }
 559 
 560 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 561   assert(!src2.is_lval(), "should use cmpptr");
 562 
 563   if (reachable(src2)) {
 564     cmpq(src1, as_Address(src2));
 565   } else {
 566     lea(rscratch1, src2);
 567     Assembler::cmpq(src1, Address(rscratch1, 0));
 568   }
 569 }
 570 
 571 int MacroAssembler::corrected_idivq(Register reg) {
 572   // Full implementation of Java ldiv and lrem; checks for special
 573   // case as described in JVM spec., p.243 & p.271.  The function
 574   // returns the (pc) offset of the idivl instruction - may be needed
 575   // for implicit exceptions.
 576   //
 577   //         normal case                           special case
 578   //
 579   // input : rax: dividend                         min_long
 580   //         reg: divisor   (may not be eax/edx)   -1
 581   //
 582   // output: rax: quotient  (= rax idiv reg)       min_long
 583   //         rdx: remainder (= rax irem reg)       0
 584   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 585   static const int64_t min_long = 0x8000000000000000;
 586   Label normal_case, special_case;
 587 
 588   // check for special case
 589   cmp64(rax, ExternalAddress((address) &min_long));
 590   jcc(Assembler::notEqual, normal_case);
 591   xorl(rdx, rdx); // prepare rdx for possible special case (where
 592                   // remainder = 0)
 593   cmpq(reg, -1);
 594   jcc(Assembler::equal, special_case);
 595 
 596   // handle normal case
 597   bind(normal_case);
 598   cdqq();
 599   int idivq_offset = offset();
 600   idivq(reg);
 601 
 602   // normal and special case exit
 603   bind(special_case);
 604 
 605   return idivq_offset;
 606 }
 607 
 608 void MacroAssembler::decrementq(Register reg, int value) {
 609   if (value == min_jint) { subq(reg, value); return; }
 610   if (value <  0) { incrementq(reg, -value); return; }
 611   if (value == 0) {                        ; return; }
 612   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 613   /* else */      { subq(reg, value)       ; return; }
 614 }
 615 
 616 void MacroAssembler::decrementq(Address dst, int value) {
 617   if (value == min_jint) { subq(dst, value); return; }
 618   if (value <  0) { incrementq(dst, -value); return; }
 619   if (value == 0) {                        ; return; }
 620   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 621   /* else */      { subq(dst, value)       ; return; }
 622 }
 623 
 624 void MacroAssembler::incrementq(AddressLiteral dst) {
 625   if (reachable(dst)) {
 626     incrementq(as_Address(dst));
 627   } else {
 628     lea(rscratch1, dst);
 629     incrementq(Address(rscratch1, 0));
 630   }
 631 }
 632 
 633 void MacroAssembler::incrementq(Register reg, int value) {
 634   if (value == min_jint) { addq(reg, value); return; }
 635   if (value <  0) { decrementq(reg, -value); return; }
 636   if (value == 0) {                        ; return; }
 637   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 638   /* else */      { addq(reg, value)       ; return; }
 639 }
 640 
 641 void MacroAssembler::incrementq(Address dst, int value) {
 642   if (value == min_jint) { addq(dst, value); return; }
 643   if (value <  0) { decrementq(dst, -value); return; }
 644   if (value == 0) {                        ; return; }
 645   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 646   /* else */      { addq(dst, value)       ; return; }
 647 }
 648 
 649 // 32bit can do a case table jump in one instruction but we no longer allow the base
 650 // to be installed in the Address class
 651 void MacroAssembler::jump(ArrayAddress entry) {
 652   lea(rscratch1, entry.base());
 653   Address dispatch = entry.index();
 654   assert(dispatch._base == noreg, "must be");
 655   dispatch._base = rscratch1;
 656   jmp(dispatch);
 657 }
 658 
 659 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 660   ShouldNotReachHere(); // 64bit doesn't use two regs
 661   cmpq(x_lo, y_lo);
 662 }
 663 
 664 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 665     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 666 }
 667 
 668 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 669   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 670   movptr(dst, rscratch1);
 671 }
 672 
 673 void MacroAssembler::leave() {
 674   // %%% is this really better? Why not on 32bit too?
 675   emit_int8((unsigned char)0xC9); // LEAVE
 676 }
 677 
 678 void MacroAssembler::lneg(Register hi, Register lo) {
 679   ShouldNotReachHere(); // 64bit doesn't use two regs
 680   negq(lo);
 681 }
 682 
 683 void MacroAssembler::movoop(Register dst, jobject obj) {
 684   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 685 }
 686 
 687 void MacroAssembler::movoop(Address dst, jobject obj) {
 688   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 689   movq(dst, rscratch1);
 690 }
 691 
 692 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 693   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 694 }
 695 
 696 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 697   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 698   movq(dst, rscratch1);
 699 }
 700 
 701 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 702   if (src.is_lval()) {
 703     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 704   } else {
 705     if (reachable(src)) {
 706       movq(dst, as_Address(src));
 707     } else {
 708       lea(scratch, src);
 709       movq(dst, Address(scratch, 0));
 710     }
 711   }
 712 }
 713 
 714 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 715   movq(as_Address(dst), src);
 716 }
 717 
 718 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 719   movq(dst, as_Address(src));
 720 }
 721 
 722 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 723 void MacroAssembler::movptr(Address dst, intptr_t src) {
 724   mov64(rscratch1, src);
 725   movq(dst, rscratch1);
 726 }
 727 
 728 // These are mostly for initializing NULL
 729 void MacroAssembler::movptr(Address dst, int32_t src) {
 730   movslq(dst, src);
 731 }
 732 
 733 void MacroAssembler::movptr(Register dst, int32_t src) {
 734   mov64(dst, (intptr_t)src);
 735 }
 736 
 737 void MacroAssembler::pushoop(jobject obj) {
 738   movoop(rscratch1, obj);
 739   push(rscratch1);
 740 }
 741 
 742 void MacroAssembler::pushklass(Metadata* obj) {
 743   mov_metadata(rscratch1, obj);
 744   push(rscratch1);
 745 }
 746 
 747 void MacroAssembler::pushptr(AddressLiteral src) {
 748   lea(rscratch1, src);
 749   if (src.is_lval()) {
 750     push(rscratch1);
 751   } else {
 752     pushq(Address(rscratch1, 0));
 753   }
 754 }
 755 
 756 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 757   // we must set sp to zero to clear frame
 758   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 759   // must clear fp, so that compiled frames are not confused; it is
 760   // possible that we need it only for debugging
 761   if (clear_fp) {
 762     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 763   }
 764 
 765   // Always clear the pc because it could have been set by make_walkable()
 766   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 767   vzeroupper();
 768 }
 769 
 770 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 771                                          Register last_java_fp,
 772                                          address  last_java_pc) {
 773   vzeroupper();
 774   // determine last_java_sp register
 775   if (!last_java_sp->is_valid()) {
 776     last_java_sp = rsp;
 777   }
 778 
 779   // last_java_fp is optional
 780   if (last_java_fp->is_valid()) {
 781     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 782            last_java_fp);
 783   }
 784 
 785   // last_java_pc is optional
 786   if (last_java_pc != NULL) {
 787     Address java_pc(r15_thread,
 788                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 789     lea(rscratch1, InternalAddress(last_java_pc));
 790     movptr(java_pc, rscratch1);
 791   }
 792 
 793   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 794 }
 795 
 796 static void pass_arg0(MacroAssembler* masm, Register arg) {
 797   if (c_rarg0 != arg ) {
 798     masm->mov(c_rarg0, arg);
 799   }
 800 }
 801 
 802 static void pass_arg1(MacroAssembler* masm, Register arg) {
 803   if (c_rarg1 != arg ) {
 804     masm->mov(c_rarg1, arg);
 805   }
 806 }
 807 
 808 static void pass_arg2(MacroAssembler* masm, Register arg) {
 809   if (c_rarg2 != arg ) {
 810     masm->mov(c_rarg2, arg);
 811   }
 812 }
 813 
 814 static void pass_arg3(MacroAssembler* masm, Register arg) {
 815   if (c_rarg3 != arg ) {
 816     masm->mov(c_rarg3, arg);
 817   }
 818 }
 819 
 820 void MacroAssembler::stop(const char* msg) {
 821   address rip = pc();
 822   pusha(); // get regs on stack
 823   lea(c_rarg0, ExternalAddress((address) msg));
 824   lea(c_rarg1, InternalAddress(rip));
 825   movq(c_rarg2, rsp); // pass pointer to regs array
 826   andq(rsp, -16); // align stack as required by ABI
 827   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 828   hlt();
 829 }
 830 
 831 void MacroAssembler::warn(const char* msg) {
 832   push(rbp);
 833   movq(rbp, rsp);
 834   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 835   push_CPU_state();   // keeps alignment at 16 bytes
 836   lea(c_rarg0, ExternalAddress((address) msg));
 837   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 838   pop_CPU_state();
 839   mov(rsp, rbp);
 840   pop(rbp);
 841 }
 842 
 843 void MacroAssembler::print_state() {
 844   address rip = pc();
 845   pusha();            // get regs on stack
 846   push(rbp);
 847   movq(rbp, rsp);
 848   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 849   push_CPU_state();   // keeps alignment at 16 bytes
 850 
 851   lea(c_rarg0, InternalAddress(rip));
 852   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 853   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 854 
 855   pop_CPU_state();
 856   mov(rsp, rbp);
 857   pop(rbp);
 858   popa();
 859 }
 860 
 861 #ifndef PRODUCT
 862 extern "C" void findpc(intptr_t x);
 863 #endif
 864 
 865 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 866   // In order to get locks to work, we need to fake a in_VM state
 867   if (ShowMessageBoxOnError) {
 868     JavaThread* thread = JavaThread::current();
 869     JavaThreadState saved_state = thread->thread_state();
 870     thread->set_thread_state(_thread_in_vm);
 871 #ifndef PRODUCT
 872     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 873       ttyLocker ttyl;
 874       BytecodeCounter::print();
 875     }
 876 #endif
 877     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 878     // XXX correct this offset for amd64
 879     // This is the value of eip which points to where verify_oop will return.
 880     if (os::message_box(msg, "Execution stopped, print registers?")) {
 881       print_state64(pc, regs);
 882       BREAKPOINT;
 883       assert(false, "start up GDB");
 884     }
 885     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 886   } else {
 887     ttyLocker ttyl;
 888     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 889                     msg);
 890     assert(false, "DEBUG MESSAGE: %s", msg);
 891   }
 892 }
 893 
 894 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 895   ttyLocker ttyl;
 896   FlagSetting fs(Debugging, true);
 897   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 898 #ifndef PRODUCT
 899   tty->cr();
 900   findpc(pc);
 901   tty->cr();
 902 #endif
 903 #define PRINT_REG(rax, value) \
 904   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 905   PRINT_REG(rax, regs[15]);
 906   PRINT_REG(rbx, regs[12]);
 907   PRINT_REG(rcx, regs[14]);
 908   PRINT_REG(rdx, regs[13]);
 909   PRINT_REG(rdi, regs[8]);
 910   PRINT_REG(rsi, regs[9]);
 911   PRINT_REG(rbp, regs[10]);
 912   PRINT_REG(rsp, regs[11]);
 913   PRINT_REG(r8 , regs[7]);
 914   PRINT_REG(r9 , regs[6]);
 915   PRINT_REG(r10, regs[5]);
 916   PRINT_REG(r11, regs[4]);
 917   PRINT_REG(r12, regs[3]);
 918   PRINT_REG(r13, regs[2]);
 919   PRINT_REG(r14, regs[1]);
 920   PRINT_REG(r15, regs[0]);
 921 #undef PRINT_REG
 922   // Print some words near top of staack.
 923   int64_t* rsp = (int64_t*) regs[11];
 924   int64_t* dump_sp = rsp;
 925   for (int col1 = 0; col1 < 8; col1++) {
 926     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 927     os::print_location(tty, *dump_sp++);
 928   }
 929   for (int row = 0; row < 25; row++) {
 930     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 931     for (int col = 0; col < 4; col++) {
 932       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 933     }
 934     tty->cr();
 935   }
 936   // Print some instructions around pc:
 937   Disassembler::decode((address)pc-64, (address)pc);
 938   tty->print_cr("--------");
 939   Disassembler::decode((address)pc, (address)pc+32);
 940 }
 941 
 942 #endif // _LP64
 943 
 944 // Now versions that are common to 32/64 bit
 945 
 946 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 947   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 948 }
 949 
 950 void MacroAssembler::addptr(Register dst, Register src) {
 951   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 952 }
 953 
 954 void MacroAssembler::addptr(Address dst, Register src) {
 955   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 956 }
 957 
 958 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 959   if (reachable(src)) {
 960     Assembler::addsd(dst, as_Address(src));
 961   } else {
 962     lea(rscratch1, src);
 963     Assembler::addsd(dst, Address(rscratch1, 0));
 964   }
 965 }
 966 
 967 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 968   if (reachable(src)) {
 969     addss(dst, as_Address(src));
 970   } else {
 971     lea(rscratch1, src);
 972     addss(dst, Address(rscratch1, 0));
 973   }
 974 }
 975 
 976 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 977   if (reachable(src)) {
 978     Assembler::addpd(dst, as_Address(src));
 979   } else {
 980     lea(rscratch1, src);
 981     Assembler::addpd(dst, Address(rscratch1, 0));
 982   }
 983 }
 984 
 985 void MacroAssembler::align(int modulus) {
 986   align(modulus, offset());
 987 }
 988 
 989 void MacroAssembler::align(int modulus, int target) {
 990   if (target % modulus != 0) {
 991     nop(modulus - (target % modulus));
 992   }
 993 }
 994 
 995 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 996   // Used in sign-masking with aligned address.
 997   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 998   if (reachable(src)) {
 999     Assembler::andpd(dst, as_Address(src));
1000   } else {
1001     lea(rscratch1, src);
1002     Assembler::andpd(dst, Address(rscratch1, 0));
1003   }
1004 }
1005 
1006 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1007   // Used in sign-masking with aligned address.
1008   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1009   if (reachable(src)) {
1010     Assembler::andps(dst, as_Address(src));
1011   } else {
1012     lea(rscratch1, src);
1013     Assembler::andps(dst, Address(rscratch1, 0));
1014   }
1015 }
1016 
1017 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1018   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1019 }
1020 
1021 void MacroAssembler::atomic_incl(Address counter_addr) {
1022   if (os::is_MP())
1023     lock();
1024   incrementl(counter_addr);
1025 }
1026 
1027 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1028   if (reachable(counter_addr)) {
1029     atomic_incl(as_Address(counter_addr));
1030   } else {
1031     lea(scr, counter_addr);
1032     atomic_incl(Address(scr, 0));
1033   }
1034 }
1035 
1036 #ifdef _LP64
1037 void MacroAssembler::atomic_incq(Address counter_addr) {
1038   if (os::is_MP())
1039     lock();
1040   incrementq(counter_addr);
1041 }
1042 
1043 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1044   if (reachable(counter_addr)) {
1045     atomic_incq(as_Address(counter_addr));
1046   } else {
1047     lea(scr, counter_addr);
1048     atomic_incq(Address(scr, 0));
1049   }
1050 }
1051 #endif
1052 
1053 // Writes to stack successive pages until offset reached to check for
1054 // stack overflow + shadow pages.  This clobbers tmp.
1055 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1056   movptr(tmp, rsp);
1057   // Bang stack for total size given plus shadow page size.
1058   // Bang one page at a time because large size can bang beyond yellow and
1059   // red zones.
1060   Label loop;
1061   bind(loop);
1062   movl(Address(tmp, (-os::vm_page_size())), size );
1063   subptr(tmp, os::vm_page_size());
1064   subl(size, os::vm_page_size());
1065   jcc(Assembler::greater, loop);
1066 
1067   // Bang down shadow pages too.
1068   // At this point, (tmp-0) is the last address touched, so don't
1069   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1070   // was post-decremented.)  Skip this address by starting at i=1, and
1071   // touch a few more pages below.  N.B.  It is important to touch all
1072   // the way down including all pages in the shadow zone.
1073   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1074     // this could be any sized move but this is can be a debugging crumb
1075     // so the bigger the better.
1076     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1077   }
1078 }
1079 
1080 void MacroAssembler::reserved_stack_check() {
1081     // testing if reserved zone needs to be enabled
1082     Label no_reserved_zone_enabling;
1083     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1084     NOT_LP64(get_thread(rsi);)
1085 
1086     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1087     jcc(Assembler::below, no_reserved_zone_enabling);
1088 
1089     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1090     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1091     should_not_reach_here();
1092 
1093     bind(no_reserved_zone_enabling);
1094 }
1095 
1096 int MacroAssembler::biased_locking_enter(Register lock_reg,
1097                                          Register obj_reg,
1098                                          Register swap_reg,
1099                                          Register tmp_reg,
1100                                          bool swap_reg_contains_mark,
1101                                          Label& done,
1102                                          Label* slow_case,
1103                                          BiasedLockingCounters* counters) {
1104   assert(UseBiasedLocking, "why call this otherwise?");
1105   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1106   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1107   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1108   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1109   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1110   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1111 
1112   if (PrintBiasedLockingStatistics && counters == NULL) {
1113     counters = BiasedLocking::counters();
1114   }
1115   // Biased locking
1116   // See whether the lock is currently biased toward our thread and
1117   // whether the epoch is still valid
1118   // Note that the runtime guarantees sufficient alignment of JavaThread
1119   // pointers to allow age to be placed into low bits
1120   // First check to see whether biasing is even enabled for this object
1121   Label cas_label;
1122   int null_check_offset = -1;
1123   if (!swap_reg_contains_mark) {
1124     null_check_offset = offset();
1125     movptr(swap_reg, mark_addr);
1126   }
1127   movptr(tmp_reg, swap_reg);
1128   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1129   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1130   jcc(Assembler::notEqual, cas_label);
1131   // The bias pattern is present in the object's header. Need to check
1132   // whether the bias owner and the epoch are both still current.
1133 #ifndef _LP64
1134   // Note that because there is no current thread register on x86_32 we
1135   // need to store off the mark word we read out of the object to
1136   // avoid reloading it and needing to recheck invariants below. This
1137   // store is unfortunate but it makes the overall code shorter and
1138   // simpler.
1139   movptr(saved_mark_addr, swap_reg);
1140 #endif
1141   if (swap_reg_contains_mark) {
1142     null_check_offset = offset();
1143   }
1144   load_prototype_header(tmp_reg, obj_reg);
1145 #ifdef _LP64
1146   orptr(tmp_reg, r15_thread);
1147   xorptr(tmp_reg, swap_reg);
1148   Register header_reg = tmp_reg;
1149 #else
1150   xorptr(tmp_reg, swap_reg);
1151   get_thread(swap_reg);
1152   xorptr(swap_reg, tmp_reg);
1153   Register header_reg = swap_reg;
1154 #endif
1155   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1156   if (counters != NULL) {
1157     cond_inc32(Assembler::zero,
1158                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1159   }
1160   jcc(Assembler::equal, done);
1161 
1162   Label try_revoke_bias;
1163   Label try_rebias;
1164 
1165   // At this point we know that the header has the bias pattern and
1166   // that we are not the bias owner in the current epoch. We need to
1167   // figure out more details about the state of the header in order to
1168   // know what operations can be legally performed on the object's
1169   // header.
1170 
1171   // If the low three bits in the xor result aren't clear, that means
1172   // the prototype header is no longer biased and we have to revoke
1173   // the bias on this object.
1174   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1175   jccb(Assembler::notZero, try_revoke_bias);
1176 
1177   // Biasing is still enabled for this data type. See whether the
1178   // epoch of the current bias is still valid, meaning that the epoch
1179   // bits of the mark word are equal to the epoch bits of the
1180   // prototype header. (Note that the prototype header's epoch bits
1181   // only change at a safepoint.) If not, attempt to rebias the object
1182   // toward the current thread. Note that we must be absolutely sure
1183   // that the current epoch is invalid in order to do this because
1184   // otherwise the manipulations it performs on the mark word are
1185   // illegal.
1186   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1187   jccb(Assembler::notZero, try_rebias);
1188 
1189   // The epoch of the current bias is still valid but we know nothing
1190   // about the owner; it might be set or it might be clear. Try to
1191   // acquire the bias of the object using an atomic operation. If this
1192   // fails we will go in to the runtime to revoke the object's bias.
1193   // Note that we first construct the presumed unbiased header so we
1194   // don't accidentally blow away another thread's valid bias.
1195   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1196   andptr(swap_reg,
1197          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1198 #ifdef _LP64
1199   movptr(tmp_reg, swap_reg);
1200   orptr(tmp_reg, r15_thread);
1201 #else
1202   get_thread(tmp_reg);
1203   orptr(tmp_reg, swap_reg);
1204 #endif
1205   if (os::is_MP()) {
1206     lock();
1207   }
1208   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1209   // If the biasing toward our thread failed, this means that
1210   // another thread succeeded in biasing it toward itself and we
1211   // need to revoke that bias. The revocation will occur in the
1212   // interpreter runtime in the slow case.
1213   if (counters != NULL) {
1214     cond_inc32(Assembler::zero,
1215                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1216   }
1217   if (slow_case != NULL) {
1218     jcc(Assembler::notZero, *slow_case);
1219   }
1220   jmp(done);
1221 
1222   bind(try_rebias);
1223   // At this point we know the epoch has expired, meaning that the
1224   // current "bias owner", if any, is actually invalid. Under these
1225   // circumstances _only_, we are allowed to use the current header's
1226   // value as the comparison value when doing the cas to acquire the
1227   // bias in the current epoch. In other words, we allow transfer of
1228   // the bias from one thread to another directly in this situation.
1229   //
1230   // FIXME: due to a lack of registers we currently blow away the age
1231   // bits in this situation. Should attempt to preserve them.
1232   load_prototype_header(tmp_reg, obj_reg);
1233 #ifdef _LP64
1234   orptr(tmp_reg, r15_thread);
1235 #else
1236   get_thread(swap_reg);
1237   orptr(tmp_reg, swap_reg);
1238   movptr(swap_reg, saved_mark_addr);
1239 #endif
1240   if (os::is_MP()) {
1241     lock();
1242   }
1243   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1244   // If the biasing toward our thread failed, then another thread
1245   // succeeded in biasing it toward itself and we need to revoke that
1246   // bias. The revocation will occur in the runtime in the slow case.
1247   if (counters != NULL) {
1248     cond_inc32(Assembler::zero,
1249                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1250   }
1251   if (slow_case != NULL) {
1252     jcc(Assembler::notZero, *slow_case);
1253   }
1254   jmp(done);
1255 
1256   bind(try_revoke_bias);
1257   // The prototype mark in the klass doesn't have the bias bit set any
1258   // more, indicating that objects of this data type are not supposed
1259   // to be biased any more. We are going to try to reset the mark of
1260   // this object to the prototype value and fall through to the
1261   // CAS-based locking scheme. Note that if our CAS fails, it means
1262   // that another thread raced us for the privilege of revoking the
1263   // bias of this particular object, so it's okay to continue in the
1264   // normal locking code.
1265   //
1266   // FIXME: due to a lack of registers we currently blow away the age
1267   // bits in this situation. Should attempt to preserve them.
1268   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1269   load_prototype_header(tmp_reg, obj_reg);
1270   if (os::is_MP()) {
1271     lock();
1272   }
1273   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1274   // Fall through to the normal CAS-based lock, because no matter what
1275   // the result of the above CAS, some thread must have succeeded in
1276   // removing the bias bit from the object's header.
1277   if (counters != NULL) {
1278     cond_inc32(Assembler::zero,
1279                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1280   }
1281 
1282   bind(cas_label);
1283 
1284   return null_check_offset;
1285 }
1286 
1287 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1288   assert(UseBiasedLocking, "why call this otherwise?");
1289 
1290   // Check for biased locking unlock case, which is a no-op
1291   // Note: we do not have to check the thread ID for two reasons.
1292   // First, the interpreter checks for IllegalMonitorStateException at
1293   // a higher level. Second, if the bias was revoked while we held the
1294   // lock, the object could not be rebiased toward another thread, so
1295   // the bias bit would be clear.
1296   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1297   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1298   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1299   jcc(Assembler::equal, done);
1300 }
1301 
1302 #ifdef COMPILER2
1303 
1304 #if INCLUDE_RTM_OPT
1305 
1306 // Update rtm_counters based on abort status
1307 // input: abort_status
1308 //        rtm_counters (RTMLockingCounters*)
1309 // flags are killed
1310 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1311 
1312   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1313   if (PrintPreciseRTMLockingStatistics) {
1314     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1315       Label check_abort;
1316       testl(abort_status, (1<<i));
1317       jccb(Assembler::equal, check_abort);
1318       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1319       bind(check_abort);
1320     }
1321   }
1322 }
1323 
1324 // Branch if (random & (count-1) != 0), count is 2^n
1325 // tmp, scr and flags are killed
1326 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1327   assert(tmp == rax, "");
1328   assert(scr == rdx, "");
1329   rdtsc(); // modifies EDX:EAX
1330   andptr(tmp, count-1);
1331   jccb(Assembler::notZero, brLabel);
1332 }
1333 
1334 // Perform abort ratio calculation, set no_rtm bit if high ratio
1335 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1336 // tmpReg, rtm_counters_Reg and flags are killed
1337 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1338                                                  Register rtm_counters_Reg,
1339                                                  RTMLockingCounters* rtm_counters,
1340                                                  Metadata* method_data) {
1341   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1342 
1343   if (RTMLockingCalculationDelay > 0) {
1344     // Delay calculation
1345     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1346     testptr(tmpReg, tmpReg);
1347     jccb(Assembler::equal, L_done);
1348   }
1349   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1350   //   Aborted transactions = abort_count * 100
1351   //   All transactions = total_count *  RTMTotalCountIncrRate
1352   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1353 
1354   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1355   cmpptr(tmpReg, RTMAbortThreshold);
1356   jccb(Assembler::below, L_check_always_rtm2);
1357   imulptr(tmpReg, tmpReg, 100);
1358 
1359   Register scrReg = rtm_counters_Reg;
1360   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1361   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1362   imulptr(scrReg, scrReg, RTMAbortRatio);
1363   cmpptr(tmpReg, scrReg);
1364   jccb(Assembler::below, L_check_always_rtm1);
1365   if (method_data != NULL) {
1366     // set rtm_state to "no rtm" in MDO
1367     mov_metadata(tmpReg, method_data);
1368     if (os::is_MP()) {
1369       lock();
1370     }
1371     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1372   }
1373   jmpb(L_done);
1374   bind(L_check_always_rtm1);
1375   // Reload RTMLockingCounters* address
1376   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1377   bind(L_check_always_rtm2);
1378   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1379   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1380   jccb(Assembler::below, L_done);
1381   if (method_data != NULL) {
1382     // set rtm_state to "always rtm" in MDO
1383     mov_metadata(tmpReg, method_data);
1384     if (os::is_MP()) {
1385       lock();
1386     }
1387     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1388   }
1389   bind(L_done);
1390 }
1391 
1392 // Update counters and perform abort ratio calculation
1393 // input:  abort_status_Reg
1394 // rtm_counters_Reg, flags are killed
1395 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1396                                    Register rtm_counters_Reg,
1397                                    RTMLockingCounters* rtm_counters,
1398                                    Metadata* method_data,
1399                                    bool profile_rtm) {
1400 
1401   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1402   // update rtm counters based on rax value at abort
1403   // reads abort_status_Reg, updates flags
1404   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1405   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1406   if (profile_rtm) {
1407     // Save abort status because abort_status_Reg is used by following code.
1408     if (RTMRetryCount > 0) {
1409       push(abort_status_Reg);
1410     }
1411     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1412     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1413     // restore abort status
1414     if (RTMRetryCount > 0) {
1415       pop(abort_status_Reg);
1416     }
1417   }
1418 }
1419 
1420 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1421 // inputs: retry_count_Reg
1422 //       : abort_status_Reg
1423 // output: retry_count_Reg decremented by 1
1424 // flags are killed
1425 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1426   Label doneRetry;
1427   assert(abort_status_Reg == rax, "");
1428   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1429   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1430   // if reason is in 0x6 and retry count != 0 then retry
1431   andptr(abort_status_Reg, 0x6);
1432   jccb(Assembler::zero, doneRetry);
1433   testl(retry_count_Reg, retry_count_Reg);
1434   jccb(Assembler::zero, doneRetry);
1435   pause();
1436   decrementl(retry_count_Reg);
1437   jmp(retryLabel);
1438   bind(doneRetry);
1439 }
1440 
1441 // Spin and retry if lock is busy,
1442 // inputs: box_Reg (monitor address)
1443 //       : retry_count_Reg
1444 // output: retry_count_Reg decremented by 1
1445 //       : clear z flag if retry count exceeded
1446 // tmp_Reg, scr_Reg, flags are killed
1447 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1448                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1449   Label SpinLoop, SpinExit, doneRetry;
1450   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1451 
1452   testl(retry_count_Reg, retry_count_Reg);
1453   jccb(Assembler::zero, doneRetry);
1454   decrementl(retry_count_Reg);
1455   movptr(scr_Reg, RTMSpinLoopCount);
1456 
1457   bind(SpinLoop);
1458   pause();
1459   decrementl(scr_Reg);
1460   jccb(Assembler::lessEqual, SpinExit);
1461   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1462   testptr(tmp_Reg, tmp_Reg);
1463   jccb(Assembler::notZero, SpinLoop);
1464 
1465   bind(SpinExit);
1466   jmp(retryLabel);
1467   bind(doneRetry);
1468   incrementl(retry_count_Reg); // clear z flag
1469 }
1470 
1471 // Use RTM for normal stack locks
1472 // Input: objReg (object to lock)
1473 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1474                                        Register retry_on_abort_count_Reg,
1475                                        RTMLockingCounters* stack_rtm_counters,
1476                                        Metadata* method_data, bool profile_rtm,
1477                                        Label& DONE_LABEL, Label& IsInflated) {
1478   assert(UseRTMForStackLocks, "why call this otherwise?");
1479   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1480   assert(tmpReg == rax, "");
1481   assert(scrReg == rdx, "");
1482   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1483 
1484   if (RTMRetryCount > 0) {
1485     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1486     bind(L_rtm_retry);
1487   }
1488   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1489   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1490   jcc(Assembler::notZero, IsInflated);
1491 
1492   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1493     Label L_noincrement;
1494     if (RTMTotalCountIncrRate > 1) {
1495       // tmpReg, scrReg and flags are killed
1496       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1497     }
1498     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1499     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1500     bind(L_noincrement);
1501   }
1502   xbegin(L_on_abort);
1503   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1504   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1505   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1506   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1507 
1508   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1509   if (UseRTMXendForLockBusy) {
1510     xend();
1511     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1512     jmp(L_decrement_retry);
1513   }
1514   else {
1515     xabort(0);
1516   }
1517   bind(L_on_abort);
1518   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1519     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1520   }
1521   bind(L_decrement_retry);
1522   if (RTMRetryCount > 0) {
1523     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1524     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1525   }
1526 }
1527 
1528 // Use RTM for inflating locks
1529 // inputs: objReg (object to lock)
1530 //         boxReg (on-stack box address (displaced header location) - KILLED)
1531 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1532 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1533                                           Register scrReg, Register retry_on_busy_count_Reg,
1534                                           Register retry_on_abort_count_Reg,
1535                                           RTMLockingCounters* rtm_counters,
1536                                           Metadata* method_data, bool profile_rtm,
1537                                           Label& DONE_LABEL) {
1538   assert(UseRTMLocking, "why call this otherwise?");
1539   assert(tmpReg == rax, "");
1540   assert(scrReg == rdx, "");
1541   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1542   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1543 
1544   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1545   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1546   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1547 
1548   if (RTMRetryCount > 0) {
1549     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1550     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1551     bind(L_rtm_retry);
1552   }
1553   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1554     Label L_noincrement;
1555     if (RTMTotalCountIncrRate > 1) {
1556       // tmpReg, scrReg and flags are killed
1557       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1558     }
1559     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1560     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1561     bind(L_noincrement);
1562   }
1563   xbegin(L_on_abort);
1564   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1565   movptr(tmpReg, Address(tmpReg, owner_offset));
1566   testptr(tmpReg, tmpReg);
1567   jcc(Assembler::zero, DONE_LABEL);
1568   if (UseRTMXendForLockBusy) {
1569     xend();
1570     jmp(L_decrement_retry);
1571   }
1572   else {
1573     xabort(0);
1574   }
1575   bind(L_on_abort);
1576   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1577   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1578     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1579   }
1580   if (RTMRetryCount > 0) {
1581     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1582     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1583   }
1584 
1585   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1586   testptr(tmpReg, tmpReg) ;
1587   jccb(Assembler::notZero, L_decrement_retry) ;
1588 
1589   // Appears unlocked - try to swing _owner from null to non-null.
1590   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1591 #ifdef _LP64
1592   Register threadReg = r15_thread;
1593 #else
1594   get_thread(scrReg);
1595   Register threadReg = scrReg;
1596 #endif
1597   if (os::is_MP()) {
1598     lock();
1599   }
1600   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1601 
1602   if (RTMRetryCount > 0) {
1603     // success done else retry
1604     jccb(Assembler::equal, DONE_LABEL) ;
1605     bind(L_decrement_retry);
1606     // Spin and retry if lock is busy.
1607     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1608   }
1609   else {
1610     bind(L_decrement_retry);
1611   }
1612 }
1613 
1614 #endif //  INCLUDE_RTM_OPT
1615 
1616 // Fast_Lock and Fast_Unlock used by C2
1617 
1618 // Because the transitions from emitted code to the runtime
1619 // monitorenter/exit helper stubs are so slow it's critical that
1620 // we inline both the stack-locking fast-path and the inflated fast path.
1621 //
1622 // See also: cmpFastLock and cmpFastUnlock.
1623 //
1624 // What follows is a specialized inline transliteration of the code
1625 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1626 // another option would be to emit TrySlowEnter and TrySlowExit methods
1627 // at startup-time.  These methods would accept arguments as
1628 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1629 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1630 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1631 // In practice, however, the # of lock sites is bounded and is usually small.
1632 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1633 // if the processor uses simple bimodal branch predictors keyed by EIP
1634 // Since the helper routines would be called from multiple synchronization
1635 // sites.
1636 //
1637 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1638 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1639 // to those specialized methods.  That'd give us a mostly platform-independent
1640 // implementation that the JITs could optimize and inline at their pleasure.
1641 // Done correctly, the only time we'd need to cross to native could would be
1642 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1643 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1644 // (b) explicit barriers or fence operations.
1645 //
1646 // TODO:
1647 //
1648 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1649 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1650 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1651 //    the lock operators would typically be faster than reifying Self.
1652 //
1653 // *  Ideally I'd define the primitives as:
1654 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1655 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1656 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1657 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1658 //    Furthermore the register assignments are overconstrained, possibly resulting in
1659 //    sub-optimal code near the synchronization site.
1660 //
1661 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1662 //    Alternately, use a better sp-proximity test.
1663 //
1664 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1665 //    Either one is sufficient to uniquely identify a thread.
1666 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1667 //
1668 // *  Intrinsify notify() and notifyAll() for the common cases where the
1669 //    object is locked by the calling thread but the waitlist is empty.
1670 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1671 //
1672 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1673 //    But beware of excessive branch density on AMD Opterons.
1674 //
1675 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1676 //    or failure of the fast-path.  If the fast-path fails then we pass
1677 //    control to the slow-path, typically in C.  In Fast_Lock and
1678 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1679 //    will emit a conditional branch immediately after the node.
1680 //    So we have branches to branches and lots of ICC.ZF games.
1681 //    Instead, it might be better to have C2 pass a "FailureLabel"
1682 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1683 //    will drop through the node.  ICC.ZF is undefined at exit.
1684 //    In the case of failure, the node will branch directly to the
1685 //    FailureLabel
1686 
1687 
1688 // obj: object to lock
1689 // box: on-stack box address (displaced header location) - KILLED
1690 // rax,: tmp -- KILLED
1691 // scr: tmp -- KILLED
1692 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1693                                Register scrReg, Register cx1Reg, Register cx2Reg,
1694                                BiasedLockingCounters* counters,
1695                                RTMLockingCounters* rtm_counters,
1696                                RTMLockingCounters* stack_rtm_counters,
1697                                Metadata* method_data,
1698                                bool use_rtm, bool profile_rtm) {
1699   // Ensure the register assignments are disjoint
1700   assert(tmpReg == rax, "");
1701 
1702   if (use_rtm) {
1703     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1704   } else {
1705     assert(cx1Reg == noreg, "");
1706     assert(cx2Reg == noreg, "");
1707     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1708   }
1709 
1710   if (counters != NULL) {
1711     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1712   }
1713   if (EmitSync & 1) {
1714       // set box->dhw = markOopDesc::unused_mark()
1715       // Force all sync thru slow-path: slow_enter() and slow_exit()
1716       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1717       cmpptr (rsp, (int32_t)NULL_WORD);
1718   } else {
1719     // Possible cases that we'll encounter in fast_lock
1720     // ------------------------------------------------
1721     // * Inflated
1722     //    -- unlocked
1723     //    -- Locked
1724     //       = by self
1725     //       = by other
1726     // * biased
1727     //    -- by Self
1728     //    -- by other
1729     // * neutral
1730     // * stack-locked
1731     //    -- by self
1732     //       = sp-proximity test hits
1733     //       = sp-proximity test generates false-negative
1734     //    -- by other
1735     //
1736 
1737     Label IsInflated, DONE_LABEL;
1738 
1739     // it's stack-locked, biased or neutral
1740     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1741     // order to reduce the number of conditional branches in the most common cases.
1742     // Beware -- there's a subtle invariant that fetch of the markword
1743     // at [FETCH], below, will never observe a biased encoding (*101b).
1744     // If this invariant is not held we risk exclusion (safety) failure.
1745     if (UseBiasedLocking && !UseOptoBiasInlining) {
1746       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1747     }
1748 
1749 #if INCLUDE_RTM_OPT
1750     if (UseRTMForStackLocks && use_rtm) {
1751       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1752                         stack_rtm_counters, method_data, profile_rtm,
1753                         DONE_LABEL, IsInflated);
1754     }
1755 #endif // INCLUDE_RTM_OPT
1756 
1757     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1758     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1759     jccb(Assembler::notZero, IsInflated);
1760 
1761     // Attempt stack-locking ...
1762     orptr (tmpReg, markOopDesc::unlocked_value);
1763     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1764     if (os::is_MP()) {
1765       lock();
1766     }
1767     cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1768     if (counters != NULL) {
1769       cond_inc32(Assembler::equal,
1770                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1771     }
1772     jcc(Assembler::equal, DONE_LABEL);           // Success
1773 
1774     // Recursive locking.
1775     // The object is stack-locked: markword contains stack pointer to BasicLock.
1776     // Locked by current thread if difference with current SP is less than one page.
1777     subptr(tmpReg, rsp);
1778     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1779     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1780     movptr(Address(boxReg, 0), tmpReg);
1781     if (counters != NULL) {
1782       cond_inc32(Assembler::equal,
1783                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1784     }
1785     jmp(DONE_LABEL);
1786 
1787     bind(IsInflated);
1788     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1789 
1790 #if INCLUDE_RTM_OPT
1791     // Use the same RTM locking code in 32- and 64-bit VM.
1792     if (use_rtm) {
1793       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1794                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1795     } else {
1796 #endif // INCLUDE_RTM_OPT
1797 
1798 #ifndef _LP64
1799     // The object is inflated.
1800 
1801     // boxReg refers to the on-stack BasicLock in the current frame.
1802     // We'd like to write:
1803     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1804     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1805     // additional latency as we have another ST in the store buffer that must drain.
1806 
1807     if (EmitSync & 8192) {
1808        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1809        get_thread (scrReg);
1810        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1811        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1812        if (os::is_MP()) {
1813          lock();
1814        }
1815        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1816     } else
1817     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1818        // register juggle because we need tmpReg for cmpxchgptr below
1819        movptr(scrReg, boxReg);
1820        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1821 
1822        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1823        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1824           // prefetchw [eax + Offset(_owner)-2]
1825           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1826        }
1827 
1828        if ((EmitSync & 64) == 0) {
1829          // Optimistic form: consider XORL tmpReg,tmpReg
1830          movptr(tmpReg, NULL_WORD);
1831        } else {
1832          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1833          // Test-And-CAS instead of CAS
1834          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1835          testptr(tmpReg, tmpReg);                   // Locked ?
1836          jccb  (Assembler::notZero, DONE_LABEL);
1837        }
1838 
1839        // Appears unlocked - try to swing _owner from null to non-null.
1840        // Ideally, I'd manifest "Self" with get_thread and then attempt
1841        // to CAS the register containing Self into m->Owner.
1842        // But we don't have enough registers, so instead we can either try to CAS
1843        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1844        // we later store "Self" into m->Owner.  Transiently storing a stack address
1845        // (rsp or the address of the box) into  m->owner is harmless.
1846        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1847        if (os::is_MP()) {
1848          lock();
1849        }
1850        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1851        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1852        // If we weren't able to swing _owner from NULL to the BasicLock
1853        // then take the slow path.
1854        jccb  (Assembler::notZero, DONE_LABEL);
1855        // update _owner from BasicLock to thread
1856        get_thread (scrReg);                    // beware: clobbers ICCs
1857        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1858        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1859 
1860        // If the CAS fails we can either retry or pass control to the slow-path.
1861        // We use the latter tactic.
1862        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1863        // If the CAS was successful ...
1864        //   Self has acquired the lock
1865        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1866        // Intentional fall-through into DONE_LABEL ...
1867     } else {
1868        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1869        movptr(boxReg, tmpReg);
1870 
1871        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1872        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1873           // prefetchw [eax + Offset(_owner)-2]
1874           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1875        }
1876 
1877        if ((EmitSync & 64) == 0) {
1878          // Optimistic form
1879          xorptr  (tmpReg, tmpReg);
1880        } else {
1881          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1882          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1883          testptr(tmpReg, tmpReg);                   // Locked ?
1884          jccb  (Assembler::notZero, DONE_LABEL);
1885        }
1886 
1887        // Appears unlocked - try to swing _owner from null to non-null.
1888        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1889        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1890        get_thread (scrReg);
1891        if (os::is_MP()) {
1892          lock();
1893        }
1894        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1895 
1896        // If the CAS fails we can either retry or pass control to the slow-path.
1897        // We use the latter tactic.
1898        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1899        // If the CAS was successful ...
1900        //   Self has acquired the lock
1901        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1902        // Intentional fall-through into DONE_LABEL ...
1903     }
1904 #else // _LP64
1905     // It's inflated
1906     movq(scrReg, tmpReg);
1907     xorq(tmpReg, tmpReg);
1908 
1909     if (os::is_MP()) {
1910       lock();
1911     }
1912     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1913     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1914     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1915     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1916     // Intentional fall-through into DONE_LABEL ...
1917     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1918 #endif // _LP64
1919 #if INCLUDE_RTM_OPT
1920     } // use_rtm()
1921 #endif
1922     // DONE_LABEL is a hot target - we'd really like to place it at the
1923     // start of cache line by padding with NOPs.
1924     // See the AMD and Intel software optimization manuals for the
1925     // most efficient "long" NOP encodings.
1926     // Unfortunately none of our alignment mechanisms suffice.
1927     bind(DONE_LABEL);
1928 
1929     // At DONE_LABEL the icc ZFlag is set as follows ...
1930     // Fast_Unlock uses the same protocol.
1931     // ZFlag == 1 -> Success
1932     // ZFlag == 0 -> Failure - force control through the slow-path
1933   }
1934 }
1935 
1936 // obj: object to unlock
1937 // box: box address (displaced header location), killed.  Must be EAX.
1938 // tmp: killed, cannot be obj nor box.
1939 //
1940 // Some commentary on balanced locking:
1941 //
1942 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1943 // Methods that don't have provably balanced locking are forced to run in the
1944 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1945 // The interpreter provides two properties:
1946 // I1:  At return-time the interpreter automatically and quietly unlocks any
1947 //      objects acquired the current activation (frame).  Recall that the
1948 //      interpreter maintains an on-stack list of locks currently held by
1949 //      a frame.
1950 // I2:  If a method attempts to unlock an object that is not held by the
1951 //      the frame the interpreter throws IMSX.
1952 //
1953 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1954 // B() doesn't have provably balanced locking so it runs in the interpreter.
1955 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1956 // is still locked by A().
1957 //
1958 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1959 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1960 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1961 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1962 // Arguably given that the spec legislates the JNI case as undefined our implementation
1963 // could reasonably *avoid* checking owner in Fast_Unlock().
1964 // In the interest of performance we elide m->Owner==Self check in unlock.
1965 // A perfectly viable alternative is to elide the owner check except when
1966 // Xcheck:jni is enabled.
1967 
1968 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1969   assert(boxReg == rax, "");
1970   assert_different_registers(objReg, boxReg, tmpReg);
1971 
1972   if (EmitSync & 4) {
1973     // Disable - inhibit all inlining.  Force control through the slow-path
1974     cmpptr (rsp, 0);
1975   } else {
1976     Label DONE_LABEL, Stacked, CheckSucc;
1977 
1978     // Critically, the biased locking test must have precedence over
1979     // and appear before the (box->dhw == 0) recursive stack-lock test.
1980     if (UseBiasedLocking && !UseOptoBiasInlining) {
1981        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1982     }
1983 
1984 #if INCLUDE_RTM_OPT
1985     if (UseRTMForStackLocks && use_rtm) {
1986       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1987       Label L_regular_unlock;
1988       movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
1989       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1990       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1991       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1992       xend();                                       // otherwise end...
1993       jmp(DONE_LABEL);                              // ... and we're done
1994       bind(L_regular_unlock);
1995     }
1996 #endif
1997 
1998     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
1999     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2000     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
2001     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2002     jccb  (Assembler::zero, Stacked);
2003 
2004     // It's inflated.
2005 #if INCLUDE_RTM_OPT
2006     if (use_rtm) {
2007       Label L_regular_inflated_unlock;
2008       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2009       movptr(boxReg, Address(tmpReg, owner_offset));
2010       testptr(boxReg, boxReg);
2011       jccb(Assembler::notZero, L_regular_inflated_unlock);
2012       xend();
2013       jmpb(DONE_LABEL);
2014       bind(L_regular_inflated_unlock);
2015     }
2016 #endif
2017 
2018     // Despite our balanced locking property we still check that m->_owner == Self
2019     // as java routines or native JNI code called by this thread might
2020     // have released the lock.
2021     // Refer to the comments in synchronizer.cpp for how we might encode extra
2022     // state in _succ so we can avoid fetching EntryList|cxq.
2023     //
2024     // I'd like to add more cases in fast_lock() and fast_unlock() --
2025     // such as recursive enter and exit -- but we have to be wary of
2026     // I$ bloat, T$ effects and BP$ effects.
2027     //
2028     // If there's no contention try a 1-0 exit.  That is, exit without
2029     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2030     // we detect and recover from the race that the 1-0 exit admits.
2031     //
2032     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2033     // before it STs null into _owner, releasing the lock.  Updates
2034     // to data protected by the critical section must be visible before
2035     // we drop the lock (and thus before any other thread could acquire
2036     // the lock and observe the fields protected by the lock).
2037     // IA32's memory-model is SPO, so STs are ordered with respect to
2038     // each other and there's no need for an explicit barrier (fence).
2039     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2040 #ifndef _LP64
2041     get_thread (boxReg);
2042     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2043       // prefetchw [ebx + Offset(_owner)-2]
2044       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2045     }
2046 
2047     // Note that we could employ various encoding schemes to reduce
2048     // the number of loads below (currently 4) to just 2 or 3.
2049     // Refer to the comments in synchronizer.cpp.
2050     // In practice the chain of fetches doesn't seem to impact performance, however.
2051     xorptr(boxReg, boxReg);
2052     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2053        // Attempt to reduce branch density - AMD's branch predictor.
2054        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2055        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2056        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2057        jccb  (Assembler::notZero, DONE_LABEL);
2058        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2059        jmpb  (DONE_LABEL);
2060     } else {
2061        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2062        jccb  (Assembler::notZero, DONE_LABEL);
2063        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2064        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2065        jccb  (Assembler::notZero, CheckSucc);
2066        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2067        jmpb  (DONE_LABEL);
2068     }
2069 
2070     // The Following code fragment (EmitSync & 65536) improves the performance of
2071     // contended applications and contended synchronization microbenchmarks.
2072     // Unfortunately the emission of the code - even though not executed - causes regressions
2073     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2074     // with an equal number of never-executed NOPs results in the same regression.
2075     // We leave it off by default.
2076 
2077     if ((EmitSync & 65536) != 0) {
2078        Label LSuccess, LGoSlowPath ;
2079 
2080        bind  (CheckSucc);
2081 
2082        // Optional pre-test ... it's safe to elide this
2083        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2084        jccb(Assembler::zero, LGoSlowPath);
2085 
2086        // We have a classic Dekker-style idiom:
2087        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2088        // There are a number of ways to implement the barrier:
2089        // (1) lock:andl &m->_owner, 0
2090        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2091        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2092        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2093        // (2) If supported, an explicit MFENCE is appealing.
2094        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2095        //     particularly if the write-buffer is full as might be the case if
2096        //     if stores closely precede the fence or fence-equivalent instruction.
2097        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2098        //     as the situation has changed with Nehalem and Shanghai.
2099        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2100        //     The $lines underlying the top-of-stack should be in M-state.
2101        //     The locked add instruction is serializing, of course.
2102        // (4) Use xchg, which is serializing
2103        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2104        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2105        //     The integer condition codes will tell us if succ was 0.
2106        //     Since _succ and _owner should reside in the same $line and
2107        //     we just stored into _owner, it's likely that the $line
2108        //     remains in M-state for the lock:orl.
2109        //
2110        // We currently use (3), although it's likely that switching to (2)
2111        // is correct for the future.
2112 
2113        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2114        if (os::is_MP()) {
2115          lock(); addptr(Address(rsp, 0), 0);
2116        }
2117        // Ratify _succ remains non-null
2118        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2119        jccb  (Assembler::notZero, LSuccess);
2120 
2121        xorptr(boxReg, boxReg);                  // box is really EAX
2122        if (os::is_MP()) { lock(); }
2123        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2124        // There's no successor so we tried to regrab the lock with the
2125        // placeholder value. If that didn't work, then another thread
2126        // grabbed the lock so we're done (and exit was a success).
2127        jccb  (Assembler::notEqual, LSuccess);
2128        // Since we're low on registers we installed rsp as a placeholding in _owner.
2129        // Now install Self over rsp.  This is safe as we're transitioning from
2130        // non-null to non=null
2131        get_thread (boxReg);
2132        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2133        // Intentional fall-through into LGoSlowPath ...
2134 
2135        bind  (LGoSlowPath);
2136        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2137        jmpb  (DONE_LABEL);
2138 
2139        bind  (LSuccess);
2140        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2141        jmpb  (DONE_LABEL);
2142     }
2143 
2144     bind (Stacked);
2145     // It's not inflated and it's not recursively stack-locked and it's not biased.
2146     // It must be stack-locked.
2147     // Try to reset the header to displaced header.
2148     // The "box" value on the stack is stable, so we can reload
2149     // and be assured we observe the same value as above.
2150     movptr(tmpReg, Address(boxReg, 0));
2151     if (os::is_MP()) {
2152       lock();
2153     }
2154     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2155     // Intention fall-thru into DONE_LABEL
2156 
2157     // DONE_LABEL is a hot target - we'd really like to place it at the
2158     // start of cache line by padding with NOPs.
2159     // See the AMD and Intel software optimization manuals for the
2160     // most efficient "long" NOP encodings.
2161     // Unfortunately none of our alignment mechanisms suffice.
2162     if ((EmitSync & 65536) == 0) {
2163        bind (CheckSucc);
2164     }
2165 #else // _LP64
2166     // It's inflated
2167     if (EmitSync & 1024) {
2168       // Emit code to check that _owner == Self
2169       // We could fold the _owner test into subsequent code more efficiently
2170       // than using a stand-alone check, but since _owner checking is off by
2171       // default we don't bother. We also might consider predicating the
2172       // _owner==Self check on Xcheck:jni or running on a debug build.
2173       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2174       xorptr(boxReg, r15_thread);
2175     } else {
2176       xorptr(boxReg, boxReg);
2177     }
2178     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2179     jccb  (Assembler::notZero, DONE_LABEL);
2180     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2181     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2182     jccb  (Assembler::notZero, CheckSucc);
2183     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2184     jmpb  (DONE_LABEL);
2185 
2186     if ((EmitSync & 65536) == 0) {
2187       // Try to avoid passing control into the slow_path ...
2188       Label LSuccess, LGoSlowPath ;
2189       bind  (CheckSucc);
2190 
2191       // The following optional optimization can be elided if necessary
2192       // Effectively: if (succ == null) goto SlowPath
2193       // The code reduces the window for a race, however,
2194       // and thus benefits performance.
2195       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2196       jccb  (Assembler::zero, LGoSlowPath);
2197 
2198       xorptr(boxReg, boxReg);
2199       if ((EmitSync & 16) && os::is_MP()) {
2200         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2201       } else {
2202         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2203         if (os::is_MP()) {
2204           // Memory barrier/fence
2205           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2206           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2207           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2208           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2209           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2210           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2211           lock(); addl(Address(rsp, 0), 0);
2212         }
2213       }
2214       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2215       jccb  (Assembler::notZero, LSuccess);
2216 
2217       // Rare inopportune interleaving - race.
2218       // The successor vanished in the small window above.
2219       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2220       // We need to ensure progress and succession.
2221       // Try to reacquire the lock.
2222       // If that fails then the new owner is responsible for succession and this
2223       // thread needs to take no further action and can exit via the fast path (success).
2224       // If the re-acquire succeeds then pass control into the slow path.
2225       // As implemented, this latter mode is horrible because we generated more
2226       // coherence traffic on the lock *and* artifically extended the critical section
2227       // length while by virtue of passing control into the slow path.
2228 
2229       // box is really RAX -- the following CMPXCHG depends on that binding
2230       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2231       if (os::is_MP()) { lock(); }
2232       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2233       // There's no successor so we tried to regrab the lock.
2234       // If that didn't work, then another thread grabbed the
2235       // lock so we're done (and exit was a success).
2236       jccb  (Assembler::notEqual, LSuccess);
2237       // Intentional fall-through into slow-path
2238 
2239       bind  (LGoSlowPath);
2240       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2241       jmpb  (DONE_LABEL);
2242 
2243       bind  (LSuccess);
2244       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2245       jmpb  (DONE_LABEL);
2246     }
2247 
2248     bind  (Stacked);
2249     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2250     if (os::is_MP()) { lock(); }
2251     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2252 
2253     if (EmitSync & 65536) {
2254        bind (CheckSucc);
2255     }
2256 #endif
2257     bind(DONE_LABEL);
2258   }
2259 }
2260 #endif // COMPILER2
2261 
2262 void MacroAssembler::c2bool(Register x) {
2263   // implements x == 0 ? 0 : 1
2264   // note: must only look at least-significant byte of x
2265   //       since C-style booleans are stored in one byte
2266   //       only! (was bug)
2267   andl(x, 0xFF);
2268   setb(Assembler::notZero, x);
2269 }
2270 
2271 // Wouldn't need if AddressLiteral version had new name
2272 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2273   Assembler::call(L, rtype);
2274 }
2275 
2276 void MacroAssembler::call(Register entry) {
2277   Assembler::call(entry);
2278 }
2279 
2280 void MacroAssembler::call(AddressLiteral entry) {
2281   if (reachable(entry)) {
2282     Assembler::call_literal(entry.target(), entry.rspec());
2283   } else {
2284     lea(rscratch1, entry);
2285     Assembler::call(rscratch1);
2286   }
2287 }
2288 
2289 void MacroAssembler::ic_call(address entry, jint method_index) {
2290   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2291   movptr(rax, (intptr_t)Universe::non_oop_word());
2292   call(AddressLiteral(entry, rh));
2293 }
2294 
2295 // Implementation of call_VM versions
2296 
2297 void MacroAssembler::call_VM(Register oop_result,
2298                              address entry_point,
2299                              bool check_exceptions) {
2300   Label C, E;
2301   call(C, relocInfo::none);
2302   jmp(E);
2303 
2304   bind(C);
2305   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2306   ret(0);
2307 
2308   bind(E);
2309 }
2310 
2311 void MacroAssembler::call_VM(Register oop_result,
2312                              address entry_point,
2313                              Register arg_1,
2314                              bool check_exceptions) {
2315   Label C, E;
2316   call(C, relocInfo::none);
2317   jmp(E);
2318 
2319   bind(C);
2320   pass_arg1(this, arg_1);
2321   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2322   ret(0);
2323 
2324   bind(E);
2325 }
2326 
2327 void MacroAssembler::call_VM(Register oop_result,
2328                              address entry_point,
2329                              Register arg_1,
2330                              Register arg_2,
2331                              bool check_exceptions) {
2332   Label C, E;
2333   call(C, relocInfo::none);
2334   jmp(E);
2335 
2336   bind(C);
2337 
2338   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2339 
2340   pass_arg2(this, arg_2);
2341   pass_arg1(this, arg_1);
2342   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2343   ret(0);
2344 
2345   bind(E);
2346 }
2347 
2348 void MacroAssembler::call_VM(Register oop_result,
2349                              address entry_point,
2350                              Register arg_1,
2351                              Register arg_2,
2352                              Register arg_3,
2353                              bool check_exceptions) {
2354   Label C, E;
2355   call(C, relocInfo::none);
2356   jmp(E);
2357 
2358   bind(C);
2359 
2360   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2361   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2362   pass_arg3(this, arg_3);
2363 
2364   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2365   pass_arg2(this, arg_2);
2366 
2367   pass_arg1(this, arg_1);
2368   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2369   ret(0);
2370 
2371   bind(E);
2372 }
2373 
2374 void MacroAssembler::call_VM(Register oop_result,
2375                              Register last_java_sp,
2376                              address entry_point,
2377                              int number_of_arguments,
2378                              bool check_exceptions) {
2379   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2380   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2381 }
2382 
2383 void MacroAssembler::call_VM(Register oop_result,
2384                              Register last_java_sp,
2385                              address entry_point,
2386                              Register arg_1,
2387                              bool check_exceptions) {
2388   pass_arg1(this, arg_1);
2389   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2390 }
2391 
2392 void MacroAssembler::call_VM(Register oop_result,
2393                              Register last_java_sp,
2394                              address entry_point,
2395                              Register arg_1,
2396                              Register arg_2,
2397                              bool check_exceptions) {
2398 
2399   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2400   pass_arg2(this, arg_2);
2401   pass_arg1(this, arg_1);
2402   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2403 }
2404 
2405 void MacroAssembler::call_VM(Register oop_result,
2406                              Register last_java_sp,
2407                              address entry_point,
2408                              Register arg_1,
2409                              Register arg_2,
2410                              Register arg_3,
2411                              bool check_exceptions) {
2412   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2413   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2414   pass_arg3(this, arg_3);
2415   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2416   pass_arg2(this, arg_2);
2417   pass_arg1(this, arg_1);
2418   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2419 }
2420 
2421 void MacroAssembler::super_call_VM(Register oop_result,
2422                                    Register last_java_sp,
2423                                    address entry_point,
2424                                    int number_of_arguments,
2425                                    bool check_exceptions) {
2426   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2427   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2428 }
2429 
2430 void MacroAssembler::super_call_VM(Register oop_result,
2431                                    Register last_java_sp,
2432                                    address entry_point,
2433                                    Register arg_1,
2434                                    bool check_exceptions) {
2435   pass_arg1(this, arg_1);
2436   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2437 }
2438 
2439 void MacroAssembler::super_call_VM(Register oop_result,
2440                                    Register last_java_sp,
2441                                    address entry_point,
2442                                    Register arg_1,
2443                                    Register arg_2,
2444                                    bool check_exceptions) {
2445 
2446   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2447   pass_arg2(this, arg_2);
2448   pass_arg1(this, arg_1);
2449   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2450 }
2451 
2452 void MacroAssembler::super_call_VM(Register oop_result,
2453                                    Register last_java_sp,
2454                                    address entry_point,
2455                                    Register arg_1,
2456                                    Register arg_2,
2457                                    Register arg_3,
2458                                    bool check_exceptions) {
2459   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2460   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2461   pass_arg3(this, arg_3);
2462   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2463   pass_arg2(this, arg_2);
2464   pass_arg1(this, arg_1);
2465   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2466 }
2467 
2468 void MacroAssembler::call_VM_base(Register oop_result,
2469                                   Register java_thread,
2470                                   Register last_java_sp,
2471                                   address  entry_point,
2472                                   int      number_of_arguments,
2473                                   bool     check_exceptions) {
2474   // determine java_thread register
2475   if (!java_thread->is_valid()) {
2476 #ifdef _LP64
2477     java_thread = r15_thread;
2478 #else
2479     java_thread = rdi;
2480     get_thread(java_thread);
2481 #endif // LP64
2482   }
2483   // determine last_java_sp register
2484   if (!last_java_sp->is_valid()) {
2485     last_java_sp = rsp;
2486   }
2487   // debugging support
2488   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2489   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2490 #ifdef ASSERT
2491   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2492   // r12 is the heapbase.
2493   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2494 #endif // ASSERT
2495 
2496   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2497   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2498 
2499   // push java thread (becomes first argument of C function)
2500 
2501   NOT_LP64(push(java_thread); number_of_arguments++);
2502   LP64_ONLY(mov(c_rarg0, r15_thread));
2503 
2504   // set last Java frame before call
2505   assert(last_java_sp != rbp, "can't use ebp/rbp");
2506 
2507   // Only interpreter should have to set fp
2508   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2509 
2510   // do the call, remove parameters
2511   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2512 
2513   // restore the thread (cannot use the pushed argument since arguments
2514   // may be overwritten by C code generated by an optimizing compiler);
2515   // however can use the register value directly if it is callee saved.
2516   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2517     // rdi & rsi (also r15) are callee saved -> nothing to do
2518 #ifdef ASSERT
2519     guarantee(java_thread != rax, "change this code");
2520     push(rax);
2521     { Label L;
2522       get_thread(rax);
2523       cmpptr(java_thread, rax);
2524       jcc(Assembler::equal, L);
2525       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2526       bind(L);
2527     }
2528     pop(rax);
2529 #endif
2530   } else {
2531     get_thread(java_thread);
2532   }
2533   // reset last Java frame
2534   // Only interpreter should have to clear fp
2535   reset_last_Java_frame(java_thread, true);
2536 
2537    // C++ interp handles this in the interpreter
2538   check_and_handle_popframe(java_thread);
2539   check_and_handle_earlyret(java_thread);
2540 
2541   if (check_exceptions) {
2542     // check for pending exceptions (java_thread is set upon return)
2543     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2544 #ifndef _LP64
2545     jump_cc(Assembler::notEqual,
2546             RuntimeAddress(StubRoutines::forward_exception_entry()));
2547 #else
2548     // This used to conditionally jump to forward_exception however it is
2549     // possible if we relocate that the branch will not reach. So we must jump
2550     // around so we can always reach
2551 
2552     Label ok;
2553     jcc(Assembler::equal, ok);
2554     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2555     bind(ok);
2556 #endif // LP64
2557   }
2558 
2559   // get oop result if there is one and reset the value in the thread
2560   if (oop_result->is_valid()) {
2561     get_vm_result(oop_result, java_thread);
2562   }
2563 }
2564 
2565 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2566 
2567   // Calculate the value for last_Java_sp
2568   // somewhat subtle. call_VM does an intermediate call
2569   // which places a return address on the stack just under the
2570   // stack pointer as the user finsihed with it. This allows
2571   // use to retrieve last_Java_pc from last_Java_sp[-1].
2572   // On 32bit we then have to push additional args on the stack to accomplish
2573   // the actual requested call. On 64bit call_VM only can use register args
2574   // so the only extra space is the return address that call_VM created.
2575   // This hopefully explains the calculations here.
2576 
2577 #ifdef _LP64
2578   // We've pushed one address, correct last_Java_sp
2579   lea(rax, Address(rsp, wordSize));
2580 #else
2581   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2582 #endif // LP64
2583 
2584   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2585 
2586 }
2587 
2588 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2589 void MacroAssembler::call_VM_leaf0(address entry_point) {
2590   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2591 }
2592 
2593 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2594   call_VM_leaf_base(entry_point, number_of_arguments);
2595 }
2596 
2597 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2598   pass_arg0(this, arg_0);
2599   call_VM_leaf(entry_point, 1);
2600 }
2601 
2602 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2603 
2604   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2605   pass_arg1(this, arg_1);
2606   pass_arg0(this, arg_0);
2607   call_VM_leaf(entry_point, 2);
2608 }
2609 
2610 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2611   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2612   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2613   pass_arg2(this, arg_2);
2614   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2615   pass_arg1(this, arg_1);
2616   pass_arg0(this, arg_0);
2617   call_VM_leaf(entry_point, 3);
2618 }
2619 
2620 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2621   pass_arg0(this, arg_0);
2622   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2623 }
2624 
2625 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2626 
2627   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2628   pass_arg1(this, arg_1);
2629   pass_arg0(this, arg_0);
2630   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2631 }
2632 
2633 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2634   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2635   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2636   pass_arg2(this, arg_2);
2637   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2638   pass_arg1(this, arg_1);
2639   pass_arg0(this, arg_0);
2640   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2641 }
2642 
2643 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2644   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2645   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2646   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2647   pass_arg3(this, arg_3);
2648   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2649   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2650   pass_arg2(this, arg_2);
2651   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2652   pass_arg1(this, arg_1);
2653   pass_arg0(this, arg_0);
2654   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2655 }
2656 
2657 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2658   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2659   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2660   verify_oop(oop_result, "broken oop in call_VM_base");
2661 }
2662 
2663 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2664   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2665   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2666 }
2667 
2668 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2669 }
2670 
2671 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2672 }
2673 
2674 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2675   if (reachable(src1)) {
2676     cmpl(as_Address(src1), imm);
2677   } else {
2678     lea(rscratch1, src1);
2679     cmpl(Address(rscratch1, 0), imm);
2680   }
2681 }
2682 
2683 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2684   assert(!src2.is_lval(), "use cmpptr");
2685   if (reachable(src2)) {
2686     cmpl(src1, as_Address(src2));
2687   } else {
2688     lea(rscratch1, src2);
2689     cmpl(src1, Address(rscratch1, 0));
2690   }
2691 }
2692 
2693 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2694   Assembler::cmpl(src1, imm);
2695 }
2696 
2697 void MacroAssembler::cmp32(Register src1, Address src2) {
2698   Assembler::cmpl(src1, src2);
2699 }
2700 
2701 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2702   ucomisd(opr1, opr2);
2703 
2704   Label L;
2705   if (unordered_is_less) {
2706     movl(dst, -1);
2707     jcc(Assembler::parity, L);
2708     jcc(Assembler::below , L);
2709     movl(dst, 0);
2710     jcc(Assembler::equal , L);
2711     increment(dst);
2712   } else { // unordered is greater
2713     movl(dst, 1);
2714     jcc(Assembler::parity, L);
2715     jcc(Assembler::above , L);
2716     movl(dst, 0);
2717     jcc(Assembler::equal , L);
2718     decrementl(dst);
2719   }
2720   bind(L);
2721 }
2722 
2723 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2724   ucomiss(opr1, opr2);
2725 
2726   Label L;
2727   if (unordered_is_less) {
2728     movl(dst, -1);
2729     jcc(Assembler::parity, L);
2730     jcc(Assembler::below , L);
2731     movl(dst, 0);
2732     jcc(Assembler::equal , L);
2733     increment(dst);
2734   } else { // unordered is greater
2735     movl(dst, 1);
2736     jcc(Assembler::parity, L);
2737     jcc(Assembler::above , L);
2738     movl(dst, 0);
2739     jcc(Assembler::equal , L);
2740     decrementl(dst);
2741   }
2742   bind(L);
2743 }
2744 
2745 
2746 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2747   if (reachable(src1)) {
2748     cmpb(as_Address(src1), imm);
2749   } else {
2750     lea(rscratch1, src1);
2751     cmpb(Address(rscratch1, 0), imm);
2752   }
2753 }
2754 
2755 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2756 #ifdef _LP64
2757   if (src2.is_lval()) {
2758     movptr(rscratch1, src2);
2759     Assembler::cmpq(src1, rscratch1);
2760   } else if (reachable(src2)) {
2761     cmpq(src1, as_Address(src2));
2762   } else {
2763     lea(rscratch1, src2);
2764     Assembler::cmpq(src1, Address(rscratch1, 0));
2765   }
2766 #else
2767   if (src2.is_lval()) {
2768     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2769   } else {
2770     cmpl(src1, as_Address(src2));
2771   }
2772 #endif // _LP64
2773 }
2774 
2775 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2776   assert(src2.is_lval(), "not a mem-mem compare");
2777 #ifdef _LP64
2778   // moves src2's literal address
2779   movptr(rscratch1, src2);
2780   Assembler::cmpq(src1, rscratch1);
2781 #else
2782   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2783 #endif // _LP64
2784 }
2785 
2786 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2787   if (reachable(adr)) {
2788     if (os::is_MP())
2789       lock();
2790     cmpxchgptr(reg, as_Address(adr));
2791   } else {
2792     lea(rscratch1, adr);
2793     if (os::is_MP())
2794       lock();
2795     cmpxchgptr(reg, Address(rscratch1, 0));
2796   }
2797 }
2798 
2799 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2800   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2801 }
2802 
2803 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2804   if (reachable(src)) {
2805     Assembler::comisd(dst, as_Address(src));
2806   } else {
2807     lea(rscratch1, src);
2808     Assembler::comisd(dst, Address(rscratch1, 0));
2809   }
2810 }
2811 
2812 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2813   if (reachable(src)) {
2814     Assembler::comiss(dst, as_Address(src));
2815   } else {
2816     lea(rscratch1, src);
2817     Assembler::comiss(dst, Address(rscratch1, 0));
2818   }
2819 }
2820 
2821 
2822 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2823   Condition negated_cond = negate_condition(cond);
2824   Label L;
2825   jcc(negated_cond, L);
2826   pushf(); // Preserve flags
2827   atomic_incl(counter_addr);
2828   popf();
2829   bind(L);
2830 }
2831 
2832 int MacroAssembler::corrected_idivl(Register reg) {
2833   // Full implementation of Java idiv and irem; checks for
2834   // special case as described in JVM spec., p.243 & p.271.
2835   // The function returns the (pc) offset of the idivl
2836   // instruction - may be needed for implicit exceptions.
2837   //
2838   //         normal case                           special case
2839   //
2840   // input : rax,: dividend                         min_int
2841   //         reg: divisor   (may not be rax,/rdx)   -1
2842   //
2843   // output: rax,: quotient  (= rax, idiv reg)       min_int
2844   //         rdx: remainder (= rax, irem reg)       0
2845   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2846   const int min_int = 0x80000000;
2847   Label normal_case, special_case;
2848 
2849   // check for special case
2850   cmpl(rax, min_int);
2851   jcc(Assembler::notEqual, normal_case);
2852   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2853   cmpl(reg, -1);
2854   jcc(Assembler::equal, special_case);
2855 
2856   // handle normal case
2857   bind(normal_case);
2858   cdql();
2859   int idivl_offset = offset();
2860   idivl(reg);
2861 
2862   // normal and special case exit
2863   bind(special_case);
2864 
2865   return idivl_offset;
2866 }
2867 
2868 
2869 
2870 void MacroAssembler::decrementl(Register reg, int value) {
2871   if (value == min_jint) {subl(reg, value) ; return; }
2872   if (value <  0) { incrementl(reg, -value); return; }
2873   if (value == 0) {                        ; return; }
2874   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2875   /* else */      { subl(reg, value)       ; return; }
2876 }
2877 
2878 void MacroAssembler::decrementl(Address dst, int value) {
2879   if (value == min_jint) {subl(dst, value) ; return; }
2880   if (value <  0) { incrementl(dst, -value); return; }
2881   if (value == 0) {                        ; return; }
2882   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2883   /* else */      { subl(dst, value)       ; return; }
2884 }
2885 
2886 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2887   assert (shift_value > 0, "illegal shift value");
2888   Label _is_positive;
2889   testl (reg, reg);
2890   jcc (Assembler::positive, _is_positive);
2891   int offset = (1 << shift_value) - 1 ;
2892 
2893   if (offset == 1) {
2894     incrementl(reg);
2895   } else {
2896     addl(reg, offset);
2897   }
2898 
2899   bind (_is_positive);
2900   sarl(reg, shift_value);
2901 }
2902 
2903 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2904   if (reachable(src)) {
2905     Assembler::divsd(dst, as_Address(src));
2906   } else {
2907     lea(rscratch1, src);
2908     Assembler::divsd(dst, Address(rscratch1, 0));
2909   }
2910 }
2911 
2912 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2913   if (reachable(src)) {
2914     Assembler::divss(dst, as_Address(src));
2915   } else {
2916     lea(rscratch1, src);
2917     Assembler::divss(dst, Address(rscratch1, 0));
2918   }
2919 }
2920 
2921 // !defined(COMPILER2) is because of stupid core builds
2922 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2923 void MacroAssembler::empty_FPU_stack() {
2924   if (VM_Version::supports_mmx()) {
2925     emms();
2926   } else {
2927     for (int i = 8; i-- > 0; ) ffree(i);
2928   }
2929 }
2930 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2931 
2932 
2933 // Defines obj, preserves var_size_in_bytes
2934 void MacroAssembler::eden_allocate(Register obj,
2935                                    Register var_size_in_bytes,
2936                                    int con_size_in_bytes,
2937                                    Register t1,
2938                                    Label& slow_case) {
2939   assert(obj == rax, "obj must be in rax, for cmpxchg");
2940   assert_different_registers(obj, var_size_in_bytes, t1);
2941   if (!Universe::heap()->supports_inline_contig_alloc()) {
2942     jmp(slow_case);
2943   } else {
2944     Register end = t1;
2945     Label retry;
2946     bind(retry);
2947     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2948     movptr(obj, heap_top);
2949     if (var_size_in_bytes == noreg) {
2950       lea(end, Address(obj, con_size_in_bytes));
2951     } else {
2952       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2953     }
2954     // if end < obj then we wrapped around => object too long => slow case
2955     cmpptr(end, obj);
2956     jcc(Assembler::below, slow_case);
2957     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2958     jcc(Assembler::above, slow_case);
2959     // Compare obj with the top addr, and if still equal, store the new top addr in
2960     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2961     // it otherwise. Use lock prefix for atomicity on MPs.
2962     locked_cmpxchgptr(end, heap_top);
2963     jcc(Assembler::notEqual, retry);
2964   }
2965 }
2966 
2967 void MacroAssembler::enter() {
2968   push(rbp);
2969   mov(rbp, rsp);
2970 }
2971 
2972 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2973 void MacroAssembler::fat_nop() {
2974   if (UseAddressNop) {
2975     addr_nop_5();
2976   } else {
2977     emit_int8(0x26); // es:
2978     emit_int8(0x2e); // cs:
2979     emit_int8(0x64); // fs:
2980     emit_int8(0x65); // gs:
2981     emit_int8((unsigned char)0x90);
2982   }
2983 }
2984 
2985 void MacroAssembler::fcmp(Register tmp) {
2986   fcmp(tmp, 1, true, true);
2987 }
2988 
2989 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2990   assert(!pop_right || pop_left, "usage error");
2991   if (VM_Version::supports_cmov()) {
2992     assert(tmp == noreg, "unneeded temp");
2993     if (pop_left) {
2994       fucomip(index);
2995     } else {
2996       fucomi(index);
2997     }
2998     if (pop_right) {
2999       fpop();
3000     }
3001   } else {
3002     assert(tmp != noreg, "need temp");
3003     if (pop_left) {
3004       if (pop_right) {
3005         fcompp();
3006       } else {
3007         fcomp(index);
3008       }
3009     } else {
3010       fcom(index);
3011     }
3012     // convert FPU condition into eflags condition via rax,
3013     save_rax(tmp);
3014     fwait(); fnstsw_ax();
3015     sahf();
3016     restore_rax(tmp);
3017   }
3018   // condition codes set as follows:
3019   //
3020   // CF (corresponds to C0) if x < y
3021   // PF (corresponds to C2) if unordered
3022   // ZF (corresponds to C3) if x = y
3023 }
3024 
3025 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3026   fcmp2int(dst, unordered_is_less, 1, true, true);
3027 }
3028 
3029 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3030   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3031   Label L;
3032   if (unordered_is_less) {
3033     movl(dst, -1);
3034     jcc(Assembler::parity, L);
3035     jcc(Assembler::below , L);
3036     movl(dst, 0);
3037     jcc(Assembler::equal , L);
3038     increment(dst);
3039   } else { // unordered is greater
3040     movl(dst, 1);
3041     jcc(Assembler::parity, L);
3042     jcc(Assembler::above , L);
3043     movl(dst, 0);
3044     jcc(Assembler::equal , L);
3045     decrementl(dst);
3046   }
3047   bind(L);
3048 }
3049 
3050 void MacroAssembler::fld_d(AddressLiteral src) {
3051   fld_d(as_Address(src));
3052 }
3053 
3054 void MacroAssembler::fld_s(AddressLiteral src) {
3055   fld_s(as_Address(src));
3056 }
3057 
3058 void MacroAssembler::fld_x(AddressLiteral src) {
3059   Assembler::fld_x(as_Address(src));
3060 }
3061 
3062 void MacroAssembler::fldcw(AddressLiteral src) {
3063   Assembler::fldcw(as_Address(src));
3064 }
3065 
3066 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3067   if (reachable(src)) {
3068     Assembler::mulpd(dst, as_Address(src));
3069   } else {
3070     lea(rscratch1, src);
3071     Assembler::mulpd(dst, Address(rscratch1, 0));
3072   }
3073 }
3074 
3075 void MacroAssembler::increase_precision() {
3076   subptr(rsp, BytesPerWord);
3077   fnstcw(Address(rsp, 0));
3078   movl(rax, Address(rsp, 0));
3079   orl(rax, 0x300);
3080   push(rax);
3081   fldcw(Address(rsp, 0));
3082   pop(rax);
3083 }
3084 
3085 void MacroAssembler::restore_precision() {
3086   fldcw(Address(rsp, 0));
3087   addptr(rsp, BytesPerWord);
3088 }
3089 
3090 void MacroAssembler::fpop() {
3091   ffree();
3092   fincstp();
3093 }
3094 
3095 void MacroAssembler::load_float(Address src) {
3096   if (UseSSE >= 1) {
3097     movflt(xmm0, src);
3098   } else {
3099     LP64_ONLY(ShouldNotReachHere());
3100     NOT_LP64(fld_s(src));
3101   }
3102 }
3103 
3104 void MacroAssembler::store_float(Address dst) {
3105   if (UseSSE >= 1) {
3106     movflt(dst, xmm0);
3107   } else {
3108     LP64_ONLY(ShouldNotReachHere());
3109     NOT_LP64(fstp_s(dst));
3110   }
3111 }
3112 
3113 void MacroAssembler::load_double(Address src) {
3114   if (UseSSE >= 2) {
3115     movdbl(xmm0, src);
3116   } else {
3117     LP64_ONLY(ShouldNotReachHere());
3118     NOT_LP64(fld_d(src));
3119   }
3120 }
3121 
3122 void MacroAssembler::store_double(Address dst) {
3123   if (UseSSE >= 2) {
3124     movdbl(dst, xmm0);
3125   } else {
3126     LP64_ONLY(ShouldNotReachHere());
3127     NOT_LP64(fstp_d(dst));
3128   }
3129 }
3130 
3131 void MacroAssembler::fremr(Register tmp) {
3132   save_rax(tmp);
3133   { Label L;
3134     bind(L);
3135     fprem();
3136     fwait(); fnstsw_ax();
3137 #ifdef _LP64
3138     testl(rax, 0x400);
3139     jcc(Assembler::notEqual, L);
3140 #else
3141     sahf();
3142     jcc(Assembler::parity, L);
3143 #endif // _LP64
3144   }
3145   restore_rax(tmp);
3146   // Result is in ST0.
3147   // Note: fxch & fpop to get rid of ST1
3148   // (otherwise FPU stack could overflow eventually)
3149   fxch(1);
3150   fpop();
3151 }
3152 
3153 // dst = c = a * b + c
3154 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3155   Assembler::vfmadd231sd(c, a, b);
3156   if (dst != c) {
3157     movdbl(dst, c);
3158   }
3159 }
3160 
3161 // dst = c = a * b + c
3162 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3163   Assembler::vfmadd231ss(c, a, b);
3164   if (dst != c) {
3165     movflt(dst, c);
3166   }
3167 }
3168 
3169 // dst = c = a * b + c
3170 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3171   Assembler::vfmadd231pd(c, a, b, vector_len);
3172   if (dst != c) {
3173     vmovdqu(dst, c);
3174   }
3175 }
3176 
3177 // dst = c = a * b + c
3178 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3179   Assembler::vfmadd231ps(c, a, b, vector_len);
3180   if (dst != c) {
3181     vmovdqu(dst, c);
3182   }
3183 }
3184 
3185 // dst = c = a * b + c
3186 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3187   Assembler::vfmadd231pd(c, a, b, vector_len);
3188   if (dst != c) {
3189     vmovdqu(dst, c);
3190   }
3191 }
3192 
3193 // dst = c = a * b + c
3194 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3195   Assembler::vfmadd231ps(c, a, b, vector_len);
3196   if (dst != c) {
3197     vmovdqu(dst, c);
3198   }
3199 }
3200 
3201 void MacroAssembler::incrementl(AddressLiteral dst) {
3202   if (reachable(dst)) {
3203     incrementl(as_Address(dst));
3204   } else {
3205     lea(rscratch1, dst);
3206     incrementl(Address(rscratch1, 0));
3207   }
3208 }
3209 
3210 void MacroAssembler::incrementl(ArrayAddress dst) {
3211   incrementl(as_Address(dst));
3212 }
3213 
3214 void MacroAssembler::incrementl(Register reg, int value) {
3215   if (value == min_jint) {addl(reg, value) ; return; }
3216   if (value <  0) { decrementl(reg, -value); return; }
3217   if (value == 0) {                        ; return; }
3218   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3219   /* else */      { addl(reg, value)       ; return; }
3220 }
3221 
3222 void MacroAssembler::incrementl(Address dst, int value) {
3223   if (value == min_jint) {addl(dst, value) ; return; }
3224   if (value <  0) { decrementl(dst, -value); return; }
3225   if (value == 0) {                        ; return; }
3226   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3227   /* else */      { addl(dst, value)       ; return; }
3228 }
3229 
3230 void MacroAssembler::jump(AddressLiteral dst) {
3231   if (reachable(dst)) {
3232     jmp_literal(dst.target(), dst.rspec());
3233   } else {
3234     lea(rscratch1, dst);
3235     jmp(rscratch1);
3236   }
3237 }
3238 
3239 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3240   if (reachable(dst)) {
3241     InstructionMark im(this);
3242     relocate(dst.reloc());
3243     const int short_size = 2;
3244     const int long_size = 6;
3245     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3246     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3247       // 0111 tttn #8-bit disp
3248       emit_int8(0x70 | cc);
3249       emit_int8((offs - short_size) & 0xFF);
3250     } else {
3251       // 0000 1111 1000 tttn #32-bit disp
3252       emit_int8(0x0F);
3253       emit_int8((unsigned char)(0x80 | cc));
3254       emit_int32(offs - long_size);
3255     }
3256   } else {
3257 #ifdef ASSERT
3258     warning("reversing conditional branch");
3259 #endif /* ASSERT */
3260     Label skip;
3261     jccb(reverse[cc], skip);
3262     lea(rscratch1, dst);
3263     Assembler::jmp(rscratch1);
3264     bind(skip);
3265   }
3266 }
3267 
3268 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3269   if (reachable(src)) {
3270     Assembler::ldmxcsr(as_Address(src));
3271   } else {
3272     lea(rscratch1, src);
3273     Assembler::ldmxcsr(Address(rscratch1, 0));
3274   }
3275 }
3276 
3277 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3278   int off;
3279   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3280     off = offset();
3281     movsbl(dst, src); // movsxb
3282   } else {
3283     off = load_unsigned_byte(dst, src);
3284     shll(dst, 24);
3285     sarl(dst, 24);
3286   }
3287   return off;
3288 }
3289 
3290 // Note: load_signed_short used to be called load_signed_word.
3291 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3292 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3293 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3294 int MacroAssembler::load_signed_short(Register dst, Address src) {
3295   int off;
3296   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3297     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3298     // version but this is what 64bit has always done. This seems to imply
3299     // that users are only using 32bits worth.
3300     off = offset();
3301     movswl(dst, src); // movsxw
3302   } else {
3303     off = load_unsigned_short(dst, src);
3304     shll(dst, 16);
3305     sarl(dst, 16);
3306   }
3307   return off;
3308 }
3309 
3310 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3311   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3312   // and "3.9 Partial Register Penalties", p. 22).
3313   int off;
3314   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3315     off = offset();
3316     movzbl(dst, src); // movzxb
3317   } else {
3318     xorl(dst, dst);
3319     off = offset();
3320     movb(dst, src);
3321   }
3322   return off;
3323 }
3324 
3325 // Note: load_unsigned_short used to be called load_unsigned_word.
3326 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3327   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3328   // and "3.9 Partial Register Penalties", p. 22).
3329   int off;
3330   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3331     off = offset();
3332     movzwl(dst, src); // movzxw
3333   } else {
3334     xorl(dst, dst);
3335     off = offset();
3336     movw(dst, src);
3337   }
3338   return off;
3339 }
3340 
3341 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3342   switch (size_in_bytes) {
3343 #ifndef _LP64
3344   case  8:
3345     assert(dst2 != noreg, "second dest register required");
3346     movl(dst,  src);
3347     movl(dst2, src.plus_disp(BytesPerInt));
3348     break;
3349 #else
3350   case  8:  movq(dst, src); break;
3351 #endif
3352   case  4:  movl(dst, src); break;
3353   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3354   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3355   default:  ShouldNotReachHere();
3356   }
3357 }
3358 
3359 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3360   switch (size_in_bytes) {
3361 #ifndef _LP64
3362   case  8:
3363     assert(src2 != noreg, "second source register required");
3364     movl(dst,                        src);
3365     movl(dst.plus_disp(BytesPerInt), src2);
3366     break;
3367 #else
3368   case  8:  movq(dst, src); break;
3369 #endif
3370   case  4:  movl(dst, src); break;
3371   case  2:  movw(dst, src); break;
3372   case  1:  movb(dst, src); break;
3373   default:  ShouldNotReachHere();
3374   }
3375 }
3376 
3377 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3378   if (reachable(dst)) {
3379     movl(as_Address(dst), src);
3380   } else {
3381     lea(rscratch1, dst);
3382     movl(Address(rscratch1, 0), src);
3383   }
3384 }
3385 
3386 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3387   if (reachable(src)) {
3388     movl(dst, as_Address(src));
3389   } else {
3390     lea(rscratch1, src);
3391     movl(dst, Address(rscratch1, 0));
3392   }
3393 }
3394 
3395 // C++ bool manipulation
3396 
3397 void MacroAssembler::movbool(Register dst, Address src) {
3398   if(sizeof(bool) == 1)
3399     movb(dst, src);
3400   else if(sizeof(bool) == 2)
3401     movw(dst, src);
3402   else if(sizeof(bool) == 4)
3403     movl(dst, src);
3404   else
3405     // unsupported
3406     ShouldNotReachHere();
3407 }
3408 
3409 void MacroAssembler::movbool(Address dst, bool boolconst) {
3410   if(sizeof(bool) == 1)
3411     movb(dst, (int) boolconst);
3412   else if(sizeof(bool) == 2)
3413     movw(dst, (int) boolconst);
3414   else if(sizeof(bool) == 4)
3415     movl(dst, (int) boolconst);
3416   else
3417     // unsupported
3418     ShouldNotReachHere();
3419 }
3420 
3421 void MacroAssembler::movbool(Address dst, Register src) {
3422   if(sizeof(bool) == 1)
3423     movb(dst, src);
3424   else if(sizeof(bool) == 2)
3425     movw(dst, src);
3426   else if(sizeof(bool) == 4)
3427     movl(dst, src);
3428   else
3429     // unsupported
3430     ShouldNotReachHere();
3431 }
3432 
3433 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3434   movb(as_Address(dst), src);
3435 }
3436 
3437 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3438   if (reachable(src)) {
3439     movdl(dst, as_Address(src));
3440   } else {
3441     lea(rscratch1, src);
3442     movdl(dst, Address(rscratch1, 0));
3443   }
3444 }
3445 
3446 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3447   if (reachable(src)) {
3448     movq(dst, as_Address(src));
3449   } else {
3450     lea(rscratch1, src);
3451     movq(dst, Address(rscratch1, 0));
3452   }
3453 }
3454 
3455 void MacroAssembler::setvectmask(Register dst, Register src) {
3456   Assembler::movl(dst, 1);
3457   Assembler::shlxl(dst, dst, src);
3458   Assembler::decl(dst);
3459   Assembler::kmovdl(k1, dst);
3460   Assembler::movl(dst, src);
3461 }
3462 
3463 void MacroAssembler::restorevectmask() {
3464   Assembler::knotwl(k1, k0);
3465 }
3466 
3467 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3468   if (reachable(src)) {
3469     if (UseXmmLoadAndClearUpper) {
3470       movsd (dst, as_Address(src));
3471     } else {
3472       movlpd(dst, as_Address(src));
3473     }
3474   } else {
3475     lea(rscratch1, src);
3476     if (UseXmmLoadAndClearUpper) {
3477       movsd (dst, Address(rscratch1, 0));
3478     } else {
3479       movlpd(dst, Address(rscratch1, 0));
3480     }
3481   }
3482 }
3483 
3484 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3485   if (reachable(src)) {
3486     movss(dst, as_Address(src));
3487   } else {
3488     lea(rscratch1, src);
3489     movss(dst, Address(rscratch1, 0));
3490   }
3491 }
3492 
3493 void MacroAssembler::movptr(Register dst, Register src) {
3494   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3495 }
3496 
3497 void MacroAssembler::movptr(Register dst, Address src) {
3498   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3499 }
3500 
3501 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3502 void MacroAssembler::movptr(Register dst, intptr_t src) {
3503   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3504 }
3505 
3506 void MacroAssembler::movptr(Address dst, Register src) {
3507   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3508 }
3509 
3510 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3511   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3512     Assembler::vextractf32x4(dst, src, 0);
3513   } else {
3514     Assembler::movdqu(dst, src);
3515   }
3516 }
3517 
3518 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3519   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3520     Assembler::vinsertf32x4(dst, dst, src, 0);
3521   } else {
3522     Assembler::movdqu(dst, src);
3523   }
3524 }
3525 
3526 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3527   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3528     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3529   } else {
3530     Assembler::movdqu(dst, src);
3531   }
3532 }
3533 
3534 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3535   if (reachable(src)) {
3536     movdqu(dst, as_Address(src));
3537   } else {
3538     lea(scratchReg, src);
3539     movdqu(dst, Address(scratchReg, 0));
3540   }
3541 }
3542 
3543 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3544   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3545     vextractf64x4_low(dst, src);
3546   } else {
3547     Assembler::vmovdqu(dst, src);
3548   }
3549 }
3550 
3551 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3552   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3553     vinsertf64x4_low(dst, src);
3554   } else {
3555     Assembler::vmovdqu(dst, src);
3556   }
3557 }
3558 
3559 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3560   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3561     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3562   }
3563   else {
3564     Assembler::vmovdqu(dst, src);
3565   }
3566 }
3567 
3568 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3569   if (reachable(src)) {
3570     vmovdqu(dst, as_Address(src));
3571   }
3572   else {
3573     lea(rscratch1, src);
3574     vmovdqu(dst, Address(rscratch1, 0));
3575   }
3576 }
3577 
3578 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3579   if (reachable(src)) {
3580     Assembler::movdqa(dst, as_Address(src));
3581   } else {
3582     lea(rscratch1, src);
3583     Assembler::movdqa(dst, Address(rscratch1, 0));
3584   }
3585 }
3586 
3587 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3588   if (reachable(src)) {
3589     Assembler::movsd(dst, as_Address(src));
3590   } else {
3591     lea(rscratch1, src);
3592     Assembler::movsd(dst, Address(rscratch1, 0));
3593   }
3594 }
3595 
3596 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3597   if (reachable(src)) {
3598     Assembler::movss(dst, as_Address(src));
3599   } else {
3600     lea(rscratch1, src);
3601     Assembler::movss(dst, Address(rscratch1, 0));
3602   }
3603 }
3604 
3605 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3606   if (reachable(src)) {
3607     Assembler::mulsd(dst, as_Address(src));
3608   } else {
3609     lea(rscratch1, src);
3610     Assembler::mulsd(dst, Address(rscratch1, 0));
3611   }
3612 }
3613 
3614 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3615   if (reachable(src)) {
3616     Assembler::mulss(dst, as_Address(src));
3617   } else {
3618     lea(rscratch1, src);
3619     Assembler::mulss(dst, Address(rscratch1, 0));
3620   }
3621 }
3622 
3623 void MacroAssembler::null_check(Register reg, int offset) {
3624   if (needs_explicit_null_check(offset)) {
3625     // provoke OS NULL exception if reg = NULL by
3626     // accessing M[reg] w/o changing any (non-CC) registers
3627     // NOTE: cmpl is plenty here to provoke a segv
3628     cmpptr(rax, Address(reg, 0));
3629     // Note: should probably use testl(rax, Address(reg, 0));
3630     //       may be shorter code (however, this version of
3631     //       testl needs to be implemented first)
3632   } else {
3633     // nothing to do, (later) access of M[reg + offset]
3634     // will provoke OS NULL exception if reg = NULL
3635   }
3636 }
3637 
3638 void MacroAssembler::os_breakpoint() {
3639   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3640   // (e.g., MSVC can't call ps() otherwise)
3641   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3642 }
3643 
3644 void MacroAssembler::unimplemented(const char* what) {
3645   char* b = new char[1024];
3646   jio_snprintf(b, 1024, "unimplemented: %s", what);
3647   stop(b);
3648 }
3649 
3650 #ifdef _LP64
3651 #define XSTATE_BV 0x200
3652 #endif
3653 
3654 void MacroAssembler::pop_CPU_state() {
3655   pop_FPU_state();
3656   pop_IU_state();
3657 }
3658 
3659 void MacroAssembler::pop_FPU_state() {
3660 #ifndef _LP64
3661   frstor(Address(rsp, 0));
3662 #else
3663   fxrstor(Address(rsp, 0));
3664 #endif
3665   addptr(rsp, FPUStateSizeInWords * wordSize);
3666 }
3667 
3668 void MacroAssembler::pop_IU_state() {
3669   popa();
3670   LP64_ONLY(addq(rsp, 8));
3671   popf();
3672 }
3673 
3674 // Save Integer and Float state
3675 // Warning: Stack must be 16 byte aligned (64bit)
3676 void MacroAssembler::push_CPU_state() {
3677   push_IU_state();
3678   push_FPU_state();
3679 }
3680 
3681 void MacroAssembler::push_FPU_state() {
3682   subptr(rsp, FPUStateSizeInWords * wordSize);
3683 #ifndef _LP64
3684   fnsave(Address(rsp, 0));
3685   fwait();
3686 #else
3687   fxsave(Address(rsp, 0));
3688 #endif // LP64
3689 }
3690 
3691 void MacroAssembler::push_IU_state() {
3692   // Push flags first because pusha kills them
3693   pushf();
3694   // Make sure rsp stays 16-byte aligned
3695   LP64_ONLY(subq(rsp, 8));
3696   pusha();
3697 }
3698 
3699 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3700   if (!java_thread->is_valid()) {
3701     java_thread = rdi;
3702     get_thread(java_thread);
3703   }
3704   // we must set sp to zero to clear frame
3705   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3706   if (clear_fp) {
3707     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3708   }
3709 
3710   // Always clear the pc because it could have been set by make_walkable()
3711   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3712 
3713   vzeroupper();
3714 }
3715 
3716 void MacroAssembler::restore_rax(Register tmp) {
3717   if (tmp == noreg) pop(rax);
3718   else if (tmp != rax) mov(rax, tmp);
3719 }
3720 
3721 void MacroAssembler::round_to(Register reg, int modulus) {
3722   addptr(reg, modulus - 1);
3723   andptr(reg, -modulus);
3724 }
3725 
3726 void MacroAssembler::save_rax(Register tmp) {
3727   if (tmp == noreg) push(rax);
3728   else if (tmp != rax) mov(tmp, rax);
3729 }
3730 
3731 // Write serialization page so VM thread can do a pseudo remote membar.
3732 // We use the current thread pointer to calculate a thread specific
3733 // offset to write to within the page. This minimizes bus traffic
3734 // due to cache line collision.
3735 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3736   movl(tmp, thread);
3737   shrl(tmp, os::get_serialize_page_shift_count());
3738   andl(tmp, (os::vm_page_size() - sizeof(int)));
3739 
3740   Address index(noreg, tmp, Address::times_1);
3741   ExternalAddress page(os::get_memory_serialize_page());
3742 
3743   // Size of store must match masking code above
3744   movl(as_Address(ArrayAddress(page, index)), tmp);
3745 }
3746 
3747 // Calls to C land
3748 //
3749 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3750 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3751 // has to be reset to 0. This is required to allow proper stack traversal.
3752 void MacroAssembler::set_last_Java_frame(Register java_thread,
3753                                          Register last_java_sp,
3754                                          Register last_java_fp,
3755                                          address  last_java_pc) {
3756   vzeroupper();
3757   // determine java_thread register
3758   if (!java_thread->is_valid()) {
3759     java_thread = rdi;
3760     get_thread(java_thread);
3761   }
3762   // determine last_java_sp register
3763   if (!last_java_sp->is_valid()) {
3764     last_java_sp = rsp;
3765   }
3766 
3767   // last_java_fp is optional
3768 
3769   if (last_java_fp->is_valid()) {
3770     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3771   }
3772 
3773   // last_java_pc is optional
3774 
3775   if (last_java_pc != NULL) {
3776     lea(Address(java_thread,
3777                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3778         InternalAddress(last_java_pc));
3779 
3780   }
3781   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3782 }
3783 
3784 void MacroAssembler::shlptr(Register dst, int imm8) {
3785   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3786 }
3787 
3788 void MacroAssembler::shrptr(Register dst, int imm8) {
3789   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3790 }
3791 
3792 void MacroAssembler::sign_extend_byte(Register reg) {
3793   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3794     movsbl(reg, reg); // movsxb
3795   } else {
3796     shll(reg, 24);
3797     sarl(reg, 24);
3798   }
3799 }
3800 
3801 void MacroAssembler::sign_extend_short(Register reg) {
3802   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3803     movswl(reg, reg); // movsxw
3804   } else {
3805     shll(reg, 16);
3806     sarl(reg, 16);
3807   }
3808 }
3809 
3810 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3811   assert(reachable(src), "Address should be reachable");
3812   testl(dst, as_Address(src));
3813 }
3814 
3815 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3816   int dst_enc = dst->encoding();
3817   int src_enc = src->encoding();
3818   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3819     Assembler::pcmpeqb(dst, src);
3820   } else if ((dst_enc < 16) && (src_enc < 16)) {
3821     Assembler::pcmpeqb(dst, src);
3822   } else if (src_enc < 16) {
3823     subptr(rsp, 64);
3824     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3825     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3826     Assembler::pcmpeqb(xmm0, src);
3827     movdqu(dst, xmm0);
3828     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3829     addptr(rsp, 64);
3830   } else if (dst_enc < 16) {
3831     subptr(rsp, 64);
3832     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3833     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3834     Assembler::pcmpeqb(dst, xmm0);
3835     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3836     addptr(rsp, 64);
3837   } else {
3838     subptr(rsp, 64);
3839     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3840     subptr(rsp, 64);
3841     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3842     movdqu(xmm0, src);
3843     movdqu(xmm1, dst);
3844     Assembler::pcmpeqb(xmm1, xmm0);
3845     movdqu(dst, xmm1);
3846     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3847     addptr(rsp, 64);
3848     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3849     addptr(rsp, 64);
3850   }
3851 }
3852 
3853 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3854   int dst_enc = dst->encoding();
3855   int src_enc = src->encoding();
3856   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3857     Assembler::pcmpeqw(dst, src);
3858   } else if ((dst_enc < 16) && (src_enc < 16)) {
3859     Assembler::pcmpeqw(dst, src);
3860   } else if (src_enc < 16) {
3861     subptr(rsp, 64);
3862     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3863     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3864     Assembler::pcmpeqw(xmm0, src);
3865     movdqu(dst, xmm0);
3866     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3867     addptr(rsp, 64);
3868   } else if (dst_enc < 16) {
3869     subptr(rsp, 64);
3870     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3871     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3872     Assembler::pcmpeqw(dst, xmm0);
3873     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3874     addptr(rsp, 64);
3875   } else {
3876     subptr(rsp, 64);
3877     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3878     subptr(rsp, 64);
3879     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3880     movdqu(xmm0, src);
3881     movdqu(xmm1, dst);
3882     Assembler::pcmpeqw(xmm1, xmm0);
3883     movdqu(dst, xmm1);
3884     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3885     addptr(rsp, 64);
3886     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3887     addptr(rsp, 64);
3888   }
3889 }
3890 
3891 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3892   int dst_enc = dst->encoding();
3893   if (dst_enc < 16) {
3894     Assembler::pcmpestri(dst, src, imm8);
3895   } else {
3896     subptr(rsp, 64);
3897     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3898     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3899     Assembler::pcmpestri(xmm0, src, imm8);
3900     movdqu(dst, xmm0);
3901     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3902     addptr(rsp, 64);
3903   }
3904 }
3905 
3906 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3907   int dst_enc = dst->encoding();
3908   int src_enc = src->encoding();
3909   if ((dst_enc < 16) && (src_enc < 16)) {
3910     Assembler::pcmpestri(dst, src, imm8);
3911   } else if (src_enc < 16) {
3912     subptr(rsp, 64);
3913     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3914     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3915     Assembler::pcmpestri(xmm0, src, imm8);
3916     movdqu(dst, xmm0);
3917     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3918     addptr(rsp, 64);
3919   } else if (dst_enc < 16) {
3920     subptr(rsp, 64);
3921     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3922     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3923     Assembler::pcmpestri(dst, xmm0, imm8);
3924     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3925     addptr(rsp, 64);
3926   } else {
3927     subptr(rsp, 64);
3928     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3929     subptr(rsp, 64);
3930     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3931     movdqu(xmm0, src);
3932     movdqu(xmm1, dst);
3933     Assembler::pcmpestri(xmm1, xmm0, imm8);
3934     movdqu(dst, xmm1);
3935     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3936     addptr(rsp, 64);
3937     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3938     addptr(rsp, 64);
3939   }
3940 }
3941 
3942 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3943   int dst_enc = dst->encoding();
3944   int src_enc = src->encoding();
3945   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3946     Assembler::pmovzxbw(dst, src);
3947   } else if ((dst_enc < 16) && (src_enc < 16)) {
3948     Assembler::pmovzxbw(dst, src);
3949   } else if (src_enc < 16) {
3950     subptr(rsp, 64);
3951     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3952     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3953     Assembler::pmovzxbw(xmm0, src);
3954     movdqu(dst, xmm0);
3955     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3956     addptr(rsp, 64);
3957   } else if (dst_enc < 16) {
3958     subptr(rsp, 64);
3959     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3960     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3961     Assembler::pmovzxbw(dst, xmm0);
3962     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3963     addptr(rsp, 64);
3964   } else {
3965     subptr(rsp, 64);
3966     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3967     subptr(rsp, 64);
3968     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3969     movdqu(xmm0, src);
3970     movdqu(xmm1, dst);
3971     Assembler::pmovzxbw(xmm1, xmm0);
3972     movdqu(dst, xmm1);
3973     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3974     addptr(rsp, 64);
3975     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3976     addptr(rsp, 64);
3977   }
3978 }
3979 
3980 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
3981   int dst_enc = dst->encoding();
3982   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3983     Assembler::pmovzxbw(dst, src);
3984   } else if (dst_enc < 16) {
3985     Assembler::pmovzxbw(dst, src);
3986   } else {
3987     subptr(rsp, 64);
3988     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3989     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3990     Assembler::pmovzxbw(xmm0, src);
3991     movdqu(dst, xmm0);
3992     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3993     addptr(rsp, 64);
3994   }
3995 }
3996 
3997 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
3998   int src_enc = src->encoding();
3999   if (src_enc < 16) {
4000     Assembler::pmovmskb(dst, src);
4001   } else {
4002     subptr(rsp, 64);
4003     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4004     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4005     Assembler::pmovmskb(dst, xmm0);
4006     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4007     addptr(rsp, 64);
4008   }
4009 }
4010 
4011 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4012   int dst_enc = dst->encoding();
4013   int src_enc = src->encoding();
4014   if ((dst_enc < 16) && (src_enc < 16)) {
4015     Assembler::ptest(dst, src);
4016   } else if (src_enc < 16) {
4017     subptr(rsp, 64);
4018     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4019     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4020     Assembler::ptest(xmm0, src);
4021     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4022     addptr(rsp, 64);
4023   } else if (dst_enc < 16) {
4024     subptr(rsp, 64);
4025     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4026     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4027     Assembler::ptest(dst, xmm0);
4028     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4029     addptr(rsp, 64);
4030   } else {
4031     subptr(rsp, 64);
4032     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4033     subptr(rsp, 64);
4034     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4035     movdqu(xmm0, src);
4036     movdqu(xmm1, dst);
4037     Assembler::ptest(xmm1, xmm0);
4038     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4039     addptr(rsp, 64);
4040     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4041     addptr(rsp, 64);
4042   }
4043 }
4044 
4045 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4046   if (reachable(src)) {
4047     Assembler::sqrtsd(dst, as_Address(src));
4048   } else {
4049     lea(rscratch1, src);
4050     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4051   }
4052 }
4053 
4054 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4055   if (reachable(src)) {
4056     Assembler::sqrtss(dst, as_Address(src));
4057   } else {
4058     lea(rscratch1, src);
4059     Assembler::sqrtss(dst, Address(rscratch1, 0));
4060   }
4061 }
4062 
4063 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4064   if (reachable(src)) {
4065     Assembler::subsd(dst, as_Address(src));
4066   } else {
4067     lea(rscratch1, src);
4068     Assembler::subsd(dst, Address(rscratch1, 0));
4069   }
4070 }
4071 
4072 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4073   if (reachable(src)) {
4074     Assembler::subss(dst, as_Address(src));
4075   } else {
4076     lea(rscratch1, src);
4077     Assembler::subss(dst, Address(rscratch1, 0));
4078   }
4079 }
4080 
4081 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4082   if (reachable(src)) {
4083     Assembler::ucomisd(dst, as_Address(src));
4084   } else {
4085     lea(rscratch1, src);
4086     Assembler::ucomisd(dst, Address(rscratch1, 0));
4087   }
4088 }
4089 
4090 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4091   if (reachable(src)) {
4092     Assembler::ucomiss(dst, as_Address(src));
4093   } else {
4094     lea(rscratch1, src);
4095     Assembler::ucomiss(dst, Address(rscratch1, 0));
4096   }
4097 }
4098 
4099 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4100   // Used in sign-bit flipping with aligned address.
4101   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4102   if (reachable(src)) {
4103     Assembler::xorpd(dst, as_Address(src));
4104   } else {
4105     lea(rscratch1, src);
4106     Assembler::xorpd(dst, Address(rscratch1, 0));
4107   }
4108 }
4109 
4110 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4111   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4112     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4113   }
4114   else {
4115     Assembler::xorpd(dst, src);
4116   }
4117 }
4118 
4119 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4120   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4121     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4122   } else {
4123     Assembler::xorps(dst, src);
4124   }
4125 }
4126 
4127 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4128   // Used in sign-bit flipping with aligned address.
4129   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4130   if (reachable(src)) {
4131     Assembler::xorps(dst, as_Address(src));
4132   } else {
4133     lea(rscratch1, src);
4134     Assembler::xorps(dst, Address(rscratch1, 0));
4135   }
4136 }
4137 
4138 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4139   // Used in sign-bit flipping with aligned address.
4140   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4141   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4142   if (reachable(src)) {
4143     Assembler::pshufb(dst, as_Address(src));
4144   } else {
4145     lea(rscratch1, src);
4146     Assembler::pshufb(dst, Address(rscratch1, 0));
4147   }
4148 }
4149 
4150 // AVX 3-operands instructions
4151 
4152 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4153   if (reachable(src)) {
4154     vaddsd(dst, nds, as_Address(src));
4155   } else {
4156     lea(rscratch1, src);
4157     vaddsd(dst, nds, Address(rscratch1, 0));
4158   }
4159 }
4160 
4161 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4162   if (reachable(src)) {
4163     vaddss(dst, nds, as_Address(src));
4164   } else {
4165     lea(rscratch1, src);
4166     vaddss(dst, nds, Address(rscratch1, 0));
4167   }
4168 }
4169 
4170 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4171   int dst_enc = dst->encoding();
4172   int nds_enc = nds->encoding();
4173   int src_enc = src->encoding();
4174   if ((dst_enc < 16) && (nds_enc < 16)) {
4175     vandps(dst, nds, negate_field, vector_len);
4176   } else if ((src_enc < 16) && (dst_enc < 16)) {
4177     evmovdqul(src, nds, Assembler::AVX_512bit);
4178     vandps(dst, src, negate_field, vector_len);
4179   } else if (src_enc < 16) {
4180     evmovdqul(src, nds, Assembler::AVX_512bit);
4181     vandps(src, src, negate_field, vector_len);
4182     evmovdqul(dst, src, Assembler::AVX_512bit);
4183   } else if (dst_enc < 16) {
4184     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4185     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4186     vandps(dst, xmm0, negate_field, vector_len);
4187     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4188   } else {
4189     if (src_enc != dst_enc) {
4190       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4191       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4192       vandps(xmm0, xmm0, negate_field, vector_len);
4193       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4194       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4195     } else {
4196       subptr(rsp, 64);
4197       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4198       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4199       vandps(xmm0, xmm0, negate_field, vector_len);
4200       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4201       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4202       addptr(rsp, 64);
4203     }
4204   }
4205 }
4206 
4207 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4208   int dst_enc = dst->encoding();
4209   int nds_enc = nds->encoding();
4210   int src_enc = src->encoding();
4211   if ((dst_enc < 16) && (nds_enc < 16)) {
4212     vandpd(dst, nds, negate_field, vector_len);
4213   } else if ((src_enc < 16) && (dst_enc < 16)) {
4214     evmovdqul(src, nds, Assembler::AVX_512bit);
4215     vandpd(dst, src, negate_field, vector_len);
4216   } else if (src_enc < 16) {
4217     evmovdqul(src, nds, Assembler::AVX_512bit);
4218     vandpd(src, src, negate_field, vector_len);
4219     evmovdqul(dst, src, Assembler::AVX_512bit);
4220   } else if (dst_enc < 16) {
4221     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4222     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4223     vandpd(dst, xmm0, negate_field, vector_len);
4224     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4225   } else {
4226     if (src_enc != dst_enc) {
4227       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4228       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4229       vandpd(xmm0, xmm0, negate_field, vector_len);
4230       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4231       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4232     } else {
4233       subptr(rsp, 64);
4234       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4235       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4236       vandpd(xmm0, xmm0, negate_field, vector_len);
4237       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4238       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4239       addptr(rsp, 64);
4240     }
4241   }
4242 }
4243 
4244 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4245   int dst_enc = dst->encoding();
4246   int nds_enc = nds->encoding();
4247   int src_enc = src->encoding();
4248   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4249     Assembler::vpaddb(dst, nds, src, vector_len);
4250   } else if ((dst_enc < 16) && (src_enc < 16)) {
4251     Assembler::vpaddb(dst, dst, src, vector_len);
4252   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4253     // use nds as scratch for src
4254     evmovdqul(nds, src, Assembler::AVX_512bit);
4255     Assembler::vpaddb(dst, dst, nds, vector_len);
4256   } else if ((src_enc < 16) && (nds_enc < 16)) {
4257     // use nds as scratch for dst
4258     evmovdqul(nds, dst, Assembler::AVX_512bit);
4259     Assembler::vpaddb(nds, nds, src, vector_len);
4260     evmovdqul(dst, nds, Assembler::AVX_512bit);
4261   } else if (dst_enc < 16) {
4262     // use nds as scatch for xmm0 to hold src
4263     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4264     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4265     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4266     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4267   } else {
4268     // worse case scenario, all regs are in the upper bank
4269     subptr(rsp, 64);
4270     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4271     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4272     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4273     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4274     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4275     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4276     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4277     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4278     addptr(rsp, 64);
4279   }
4280 }
4281 
4282 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4283   int dst_enc = dst->encoding();
4284   int nds_enc = nds->encoding();
4285   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4286     Assembler::vpaddb(dst, nds, src, vector_len);
4287   } else if (dst_enc < 16) {
4288     Assembler::vpaddb(dst, dst, src, vector_len);
4289   } else if (nds_enc < 16) {
4290     // implies dst_enc in upper bank with src as scratch
4291     evmovdqul(nds, dst, Assembler::AVX_512bit);
4292     Assembler::vpaddb(nds, nds, src, vector_len);
4293     evmovdqul(dst, nds, Assembler::AVX_512bit);
4294   } else {
4295     // worse case scenario, all regs in upper bank
4296     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4297     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4298     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4299     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4300   }
4301 }
4302 
4303 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4304   int dst_enc = dst->encoding();
4305   int nds_enc = nds->encoding();
4306   int src_enc = src->encoding();
4307   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4308     Assembler::vpaddw(dst, nds, src, vector_len);
4309   } else if ((dst_enc < 16) && (src_enc < 16)) {
4310     Assembler::vpaddw(dst, dst, src, vector_len);
4311   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4312     // use nds as scratch for src
4313     evmovdqul(nds, src, Assembler::AVX_512bit);
4314     Assembler::vpaddw(dst, dst, nds, vector_len);
4315   } else if ((src_enc < 16) && (nds_enc < 16)) {
4316     // use nds as scratch for dst
4317     evmovdqul(nds, dst, Assembler::AVX_512bit);
4318     Assembler::vpaddw(nds, nds, src, vector_len);
4319     evmovdqul(dst, nds, Assembler::AVX_512bit);
4320   } else if (dst_enc < 16) {
4321     // use nds as scatch for xmm0 to hold src
4322     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4323     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4324     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4325     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4326   } else {
4327     // worse case scenario, all regs are in the upper bank
4328     subptr(rsp, 64);
4329     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4330     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4331     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4332     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4333     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4334     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4335     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4336     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4337     addptr(rsp, 64);
4338   }
4339 }
4340 
4341 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4342   int dst_enc = dst->encoding();
4343   int nds_enc = nds->encoding();
4344   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4345     Assembler::vpaddw(dst, nds, src, vector_len);
4346   } else if (dst_enc < 16) {
4347     Assembler::vpaddw(dst, dst, src, vector_len);
4348   } else if (nds_enc < 16) {
4349     // implies dst_enc in upper bank with src as scratch
4350     evmovdqul(nds, dst, Assembler::AVX_512bit);
4351     Assembler::vpaddw(nds, nds, src, vector_len);
4352     evmovdqul(dst, nds, Assembler::AVX_512bit);
4353   } else {
4354     // worse case scenario, all regs in upper bank
4355     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4356     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4357     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4358     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4359   }
4360 }
4361 
4362 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4363   if (reachable(src)) {
4364     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4365   } else {
4366     lea(rscratch1, src);
4367     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4368   }
4369 }
4370 
4371 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4372   int dst_enc = dst->encoding();
4373   int src_enc = src->encoding();
4374   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4375     Assembler::vpbroadcastw(dst, src);
4376   } else if ((dst_enc < 16) && (src_enc < 16)) {
4377     Assembler::vpbroadcastw(dst, src);
4378   } else if (src_enc < 16) {
4379     subptr(rsp, 64);
4380     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4381     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4382     Assembler::vpbroadcastw(xmm0, src);
4383     movdqu(dst, xmm0);
4384     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4385     addptr(rsp, 64);
4386   } else if (dst_enc < 16) {
4387     subptr(rsp, 64);
4388     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4389     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4390     Assembler::vpbroadcastw(dst, xmm0);
4391     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4392     addptr(rsp, 64);
4393   } else {
4394     subptr(rsp, 64);
4395     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4396     subptr(rsp, 64);
4397     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4398     movdqu(xmm0, src);
4399     movdqu(xmm1, dst);
4400     Assembler::vpbroadcastw(xmm1, xmm0);
4401     movdqu(dst, xmm1);
4402     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4403     addptr(rsp, 64);
4404     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4405     addptr(rsp, 64);
4406   }
4407 }
4408 
4409 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4410   int dst_enc = dst->encoding();
4411   int nds_enc = nds->encoding();
4412   int src_enc = src->encoding();
4413   assert(dst_enc == nds_enc, "");
4414   if ((dst_enc < 16) && (src_enc < 16)) {
4415     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4416   } else if (src_enc < 16) {
4417     subptr(rsp, 64);
4418     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4419     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4420     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4421     movdqu(dst, xmm0);
4422     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4423     addptr(rsp, 64);
4424   } else if (dst_enc < 16) {
4425     subptr(rsp, 64);
4426     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4427     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4428     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4429     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4430     addptr(rsp, 64);
4431   } else {
4432     subptr(rsp, 64);
4433     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4434     subptr(rsp, 64);
4435     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4436     movdqu(xmm0, src);
4437     movdqu(xmm1, dst);
4438     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4439     movdqu(dst, xmm1);
4440     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4441     addptr(rsp, 64);
4442     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4443     addptr(rsp, 64);
4444   }
4445 }
4446 
4447 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4448   int dst_enc = dst->encoding();
4449   int nds_enc = nds->encoding();
4450   int src_enc = src->encoding();
4451   assert(dst_enc == nds_enc, "");
4452   if ((dst_enc < 16) && (src_enc < 16)) {
4453     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4454   } else if (src_enc < 16) {
4455     subptr(rsp, 64);
4456     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4457     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4458     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4459     movdqu(dst, xmm0);
4460     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4461     addptr(rsp, 64);
4462   } else if (dst_enc < 16) {
4463     subptr(rsp, 64);
4464     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4465     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4466     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4467     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4468     addptr(rsp, 64);
4469   } else {
4470     subptr(rsp, 64);
4471     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4472     subptr(rsp, 64);
4473     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4474     movdqu(xmm0, src);
4475     movdqu(xmm1, dst);
4476     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4477     movdqu(dst, xmm1);
4478     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4479     addptr(rsp, 64);
4480     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4481     addptr(rsp, 64);
4482   }
4483 }
4484 
4485 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4486   int dst_enc = dst->encoding();
4487   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4488     Assembler::vpmovzxbw(dst, src, vector_len);
4489   } else if (dst_enc < 16) {
4490     Assembler::vpmovzxbw(dst, src, vector_len);
4491   } else {
4492     subptr(rsp, 64);
4493     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4494     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4495     Assembler::vpmovzxbw(xmm0, src, vector_len);
4496     movdqu(dst, xmm0);
4497     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4498     addptr(rsp, 64);
4499   }
4500 }
4501 
4502 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4503   int src_enc = src->encoding();
4504   if (src_enc < 16) {
4505     Assembler::vpmovmskb(dst, src);
4506   } else {
4507     subptr(rsp, 64);
4508     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4509     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4510     Assembler::vpmovmskb(dst, xmm0);
4511     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4512     addptr(rsp, 64);
4513   }
4514 }
4515 
4516 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4517   int dst_enc = dst->encoding();
4518   int nds_enc = nds->encoding();
4519   int src_enc = src->encoding();
4520   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4521     Assembler::vpmullw(dst, nds, src, vector_len);
4522   } else if ((dst_enc < 16) && (src_enc < 16)) {
4523     Assembler::vpmullw(dst, dst, src, vector_len);
4524   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4525     // use nds as scratch for src
4526     evmovdqul(nds, src, Assembler::AVX_512bit);
4527     Assembler::vpmullw(dst, dst, nds, vector_len);
4528   } else if ((src_enc < 16) && (nds_enc < 16)) {
4529     // use nds as scratch for dst
4530     evmovdqul(nds, dst, Assembler::AVX_512bit);
4531     Assembler::vpmullw(nds, nds, src, vector_len);
4532     evmovdqul(dst, nds, Assembler::AVX_512bit);
4533   } else if (dst_enc < 16) {
4534     // use nds as scatch for xmm0 to hold src
4535     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4536     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4537     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4538     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4539   } else {
4540     // worse case scenario, all regs are in the upper bank
4541     subptr(rsp, 64);
4542     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4543     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4544     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4545     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4546     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4547     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4548     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4549     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4550     addptr(rsp, 64);
4551   }
4552 }
4553 
4554 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4555   int dst_enc = dst->encoding();
4556   int nds_enc = nds->encoding();
4557   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4558     Assembler::vpmullw(dst, nds, src, vector_len);
4559   } else if (dst_enc < 16) {
4560     Assembler::vpmullw(dst, dst, src, vector_len);
4561   } else if (nds_enc < 16) {
4562     // implies dst_enc in upper bank with src as scratch
4563     evmovdqul(nds, dst, Assembler::AVX_512bit);
4564     Assembler::vpmullw(nds, nds, src, vector_len);
4565     evmovdqul(dst, nds, Assembler::AVX_512bit);
4566   } else {
4567     // worse case scenario, all regs in upper bank
4568     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4569     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4570     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4571     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4572   }
4573 }
4574 
4575 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4576   int dst_enc = dst->encoding();
4577   int nds_enc = nds->encoding();
4578   int src_enc = src->encoding();
4579   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4580     Assembler::vpsubb(dst, nds, src, vector_len);
4581   } else if ((dst_enc < 16) && (src_enc < 16)) {
4582     Assembler::vpsubb(dst, dst, src, vector_len);
4583   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4584     // use nds as scratch for src
4585     evmovdqul(nds, src, Assembler::AVX_512bit);
4586     Assembler::vpsubb(dst, dst, nds, vector_len);
4587   } else if ((src_enc < 16) && (nds_enc < 16)) {
4588     // use nds as scratch for dst
4589     evmovdqul(nds, dst, Assembler::AVX_512bit);
4590     Assembler::vpsubb(nds, nds, src, vector_len);
4591     evmovdqul(dst, nds, Assembler::AVX_512bit);
4592   } else if (dst_enc < 16) {
4593     // use nds as scatch for xmm0 to hold src
4594     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4595     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4596     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4597     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4598   } else {
4599     // worse case scenario, all regs are in the upper bank
4600     subptr(rsp, 64);
4601     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4602     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4603     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4604     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4605     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4606     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4607     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4608     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4609     addptr(rsp, 64);
4610   }
4611 }
4612 
4613 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4614   int dst_enc = dst->encoding();
4615   int nds_enc = nds->encoding();
4616   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4617     Assembler::vpsubb(dst, nds, src, vector_len);
4618   } else if (dst_enc < 16) {
4619     Assembler::vpsubb(dst, dst, src, vector_len);
4620   } else if (nds_enc < 16) {
4621     // implies dst_enc in upper bank with src as scratch
4622     evmovdqul(nds, dst, Assembler::AVX_512bit);
4623     Assembler::vpsubb(nds, nds, src, vector_len);
4624     evmovdqul(dst, nds, Assembler::AVX_512bit);
4625   } else {
4626     // worse case scenario, all regs in upper bank
4627     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4628     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4629     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4630     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4631   }
4632 }
4633 
4634 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4635   int dst_enc = dst->encoding();
4636   int nds_enc = nds->encoding();
4637   int src_enc = src->encoding();
4638   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4639     Assembler::vpsubw(dst, nds, src, vector_len);
4640   } else if ((dst_enc < 16) && (src_enc < 16)) {
4641     Assembler::vpsubw(dst, dst, src, vector_len);
4642   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4643     // use nds as scratch for src
4644     evmovdqul(nds, src, Assembler::AVX_512bit);
4645     Assembler::vpsubw(dst, dst, nds, vector_len);
4646   } else if ((src_enc < 16) && (nds_enc < 16)) {
4647     // use nds as scratch for dst
4648     evmovdqul(nds, dst, Assembler::AVX_512bit);
4649     Assembler::vpsubw(nds, nds, src, vector_len);
4650     evmovdqul(dst, nds, Assembler::AVX_512bit);
4651   } else if (dst_enc < 16) {
4652     // use nds as scatch for xmm0 to hold src
4653     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4654     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4655     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4656     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4657   } else {
4658     // worse case scenario, all regs are in the upper bank
4659     subptr(rsp, 64);
4660     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4661     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4662     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4663     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4664     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4665     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4666     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4667     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4668     addptr(rsp, 64);
4669   }
4670 }
4671 
4672 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4673   int dst_enc = dst->encoding();
4674   int nds_enc = nds->encoding();
4675   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4676     Assembler::vpsubw(dst, nds, src, vector_len);
4677   } else if (dst_enc < 16) {
4678     Assembler::vpsubw(dst, dst, src, vector_len);
4679   } else if (nds_enc < 16) {
4680     // implies dst_enc in upper bank with src as scratch
4681     evmovdqul(nds, dst, Assembler::AVX_512bit);
4682     Assembler::vpsubw(nds, nds, src, vector_len);
4683     evmovdqul(dst, nds, Assembler::AVX_512bit);
4684   } else {
4685     // worse case scenario, all regs in upper bank
4686     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4687     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4688     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4689     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4690   }
4691 }
4692 
4693 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4694   int dst_enc = dst->encoding();
4695   int nds_enc = nds->encoding();
4696   int shift_enc = shift->encoding();
4697   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4698     Assembler::vpsraw(dst, nds, shift, vector_len);
4699   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4700     Assembler::vpsraw(dst, dst, shift, vector_len);
4701   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4702     // use nds_enc as scratch with shift
4703     evmovdqul(nds, shift, Assembler::AVX_512bit);
4704     Assembler::vpsraw(dst, dst, nds, vector_len);
4705   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4706     // use nds as scratch with dst
4707     evmovdqul(nds, dst, Assembler::AVX_512bit);
4708     Assembler::vpsraw(nds, nds, shift, vector_len);
4709     evmovdqul(dst, nds, Assembler::AVX_512bit);
4710   } else if (dst_enc < 16) {
4711     // use nds to save a copy of xmm0 and hold shift
4712     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4713     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4714     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4715     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4716   } else if (nds_enc < 16) {
4717     // use nds as dest as temps
4718     evmovdqul(nds, dst, Assembler::AVX_512bit);
4719     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4720     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4721     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4722     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4723     evmovdqul(dst, nds, Assembler::AVX_512bit);
4724   } else {
4725     // worse case scenario, all regs are in the upper bank
4726     subptr(rsp, 64);
4727     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4728     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4729     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4730     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4731     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4732     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4733     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4734     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4735     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4736     addptr(rsp, 64);
4737   }
4738 }
4739 
4740 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4741   int dst_enc = dst->encoding();
4742   int nds_enc = nds->encoding();
4743   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4744     Assembler::vpsraw(dst, nds, shift, vector_len);
4745   } else if (dst_enc < 16) {
4746     Assembler::vpsraw(dst, dst, shift, vector_len);
4747   } else if (nds_enc < 16) {
4748     // use nds as scratch
4749     evmovdqul(nds, dst, Assembler::AVX_512bit);
4750     Assembler::vpsraw(nds, nds, shift, vector_len);
4751     evmovdqul(dst, nds, Assembler::AVX_512bit);
4752   } else {
4753     // use nds as scratch for xmm0
4754     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4755     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4756     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4757     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4758   }
4759 }
4760 
4761 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4762   int dst_enc = dst->encoding();
4763   int nds_enc = nds->encoding();
4764   int shift_enc = shift->encoding();
4765   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4766     Assembler::vpsrlw(dst, nds, shift, vector_len);
4767   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4768     Assembler::vpsrlw(dst, dst, shift, vector_len);
4769   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4770     // use nds_enc as scratch with shift
4771     evmovdqul(nds, shift, Assembler::AVX_512bit);
4772     Assembler::vpsrlw(dst, dst, nds, vector_len);
4773   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4774     // use nds as scratch with dst
4775     evmovdqul(nds, dst, Assembler::AVX_512bit);
4776     Assembler::vpsrlw(nds, nds, shift, vector_len);
4777     evmovdqul(dst, nds, Assembler::AVX_512bit);
4778   } else if (dst_enc < 16) {
4779     // use nds to save a copy of xmm0 and hold shift
4780     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4781     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4782     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4783     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4784   } else if (nds_enc < 16) {
4785     // use nds as dest as temps
4786     evmovdqul(nds, dst, Assembler::AVX_512bit);
4787     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4788     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4789     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4790     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4791     evmovdqul(dst, nds, Assembler::AVX_512bit);
4792   } else {
4793     // worse case scenario, all regs are in the upper bank
4794     subptr(rsp, 64);
4795     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4796     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4797     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4798     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4799     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4800     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4801     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4802     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4803     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4804     addptr(rsp, 64);
4805   }
4806 }
4807 
4808 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4809   int dst_enc = dst->encoding();
4810   int nds_enc = nds->encoding();
4811   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4812     Assembler::vpsrlw(dst, nds, shift, vector_len);
4813   } else if (dst_enc < 16) {
4814     Assembler::vpsrlw(dst, dst, shift, vector_len);
4815   } else if (nds_enc < 16) {
4816     // use nds as scratch
4817     evmovdqul(nds, dst, Assembler::AVX_512bit);
4818     Assembler::vpsrlw(nds, nds, shift, vector_len);
4819     evmovdqul(dst, nds, Assembler::AVX_512bit);
4820   } else {
4821     // use nds as scratch for xmm0
4822     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4823     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4824     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4825     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4826   }
4827 }
4828 
4829 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4830   int dst_enc = dst->encoding();
4831   int nds_enc = nds->encoding();
4832   int shift_enc = shift->encoding();
4833   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4834     Assembler::vpsllw(dst, nds, shift, vector_len);
4835   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4836     Assembler::vpsllw(dst, dst, shift, vector_len);
4837   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4838     // use nds_enc as scratch with shift
4839     evmovdqul(nds, shift, Assembler::AVX_512bit);
4840     Assembler::vpsllw(dst, dst, nds, vector_len);
4841   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4842     // use nds as scratch with dst
4843     evmovdqul(nds, dst, Assembler::AVX_512bit);
4844     Assembler::vpsllw(nds, nds, shift, vector_len);
4845     evmovdqul(dst, nds, Assembler::AVX_512bit);
4846   } else if (dst_enc < 16) {
4847     // use nds to save a copy of xmm0 and hold shift
4848     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4849     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4850     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4851     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4852   } else if (nds_enc < 16) {
4853     // use nds as dest as temps
4854     evmovdqul(nds, dst, Assembler::AVX_512bit);
4855     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4856     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4857     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4858     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4859     evmovdqul(dst, nds, Assembler::AVX_512bit);
4860   } else {
4861     // worse case scenario, all regs are in the upper bank
4862     subptr(rsp, 64);
4863     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4864     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4865     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4866     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4867     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4868     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4869     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4870     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4871     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4872     addptr(rsp, 64);
4873   }
4874 }
4875 
4876 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4877   int dst_enc = dst->encoding();
4878   int nds_enc = nds->encoding();
4879   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4880     Assembler::vpsllw(dst, nds, shift, vector_len);
4881   } else if (dst_enc < 16) {
4882     Assembler::vpsllw(dst, dst, shift, vector_len);
4883   } else if (nds_enc < 16) {
4884     // use nds as scratch
4885     evmovdqul(nds, dst, Assembler::AVX_512bit);
4886     Assembler::vpsllw(nds, nds, shift, vector_len);
4887     evmovdqul(dst, nds, Assembler::AVX_512bit);
4888   } else {
4889     // use nds as scratch for xmm0
4890     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4891     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4892     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4893     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4894   }
4895 }
4896 
4897 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4898   int dst_enc = dst->encoding();
4899   int src_enc = src->encoding();
4900   if ((dst_enc < 16) && (src_enc < 16)) {
4901     Assembler::vptest(dst, src);
4902   } else if (src_enc < 16) {
4903     subptr(rsp, 64);
4904     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4905     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4906     Assembler::vptest(xmm0, src);
4907     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4908     addptr(rsp, 64);
4909   } else if (dst_enc < 16) {
4910     subptr(rsp, 64);
4911     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4912     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4913     Assembler::vptest(dst, xmm0);
4914     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4915     addptr(rsp, 64);
4916   } else {
4917     subptr(rsp, 64);
4918     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4919     subptr(rsp, 64);
4920     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4921     movdqu(xmm0, src);
4922     movdqu(xmm1, dst);
4923     Assembler::vptest(xmm1, xmm0);
4924     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4925     addptr(rsp, 64);
4926     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4927     addptr(rsp, 64);
4928   }
4929 }
4930 
4931 // This instruction exists within macros, ergo we cannot control its input
4932 // when emitted through those patterns.
4933 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4934   if (VM_Version::supports_avx512nobw()) {
4935     int dst_enc = dst->encoding();
4936     int src_enc = src->encoding();
4937     if (dst_enc == src_enc) {
4938       if (dst_enc < 16) {
4939         Assembler::punpcklbw(dst, src);
4940       } else {
4941         subptr(rsp, 64);
4942         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4943         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4944         Assembler::punpcklbw(xmm0, xmm0);
4945         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4946         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4947         addptr(rsp, 64);
4948       }
4949     } else {
4950       if ((src_enc < 16) && (dst_enc < 16)) {
4951         Assembler::punpcklbw(dst, src);
4952       } else if (src_enc < 16) {
4953         subptr(rsp, 64);
4954         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4955         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4956         Assembler::punpcklbw(xmm0, src);
4957         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4958         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4959         addptr(rsp, 64);
4960       } else if (dst_enc < 16) {
4961         subptr(rsp, 64);
4962         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4963         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4964         Assembler::punpcklbw(dst, xmm0);
4965         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4966         addptr(rsp, 64);
4967       } else {
4968         subptr(rsp, 64);
4969         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4970         subptr(rsp, 64);
4971         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4972         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4973         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4974         Assembler::punpcklbw(xmm0, xmm1);
4975         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4976         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4977         addptr(rsp, 64);
4978         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4979         addptr(rsp, 64);
4980       }
4981     }
4982   } else {
4983     Assembler::punpcklbw(dst, src);
4984   }
4985 }
4986 
4987 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
4988   if (VM_Version::supports_avx512vl()) {
4989     Assembler::pshufd(dst, src, mode);
4990   } else {
4991     int dst_enc = dst->encoding();
4992     if (dst_enc < 16) {
4993       Assembler::pshufd(dst, src, mode);
4994     } else {
4995       subptr(rsp, 64);
4996       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4997       Assembler::pshufd(xmm0, src, mode);
4998       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4999       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5000       addptr(rsp, 64);
5001     }
5002   }
5003 }
5004 
5005 // This instruction exists within macros, ergo we cannot control its input
5006 // when emitted through those patterns.
5007 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5008   if (VM_Version::supports_avx512nobw()) {
5009     int dst_enc = dst->encoding();
5010     int src_enc = src->encoding();
5011     if (dst_enc == src_enc) {
5012       if (dst_enc < 16) {
5013         Assembler::pshuflw(dst, src, mode);
5014       } else {
5015         subptr(rsp, 64);
5016         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5017         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5018         Assembler::pshuflw(xmm0, xmm0, mode);
5019         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5020         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5021         addptr(rsp, 64);
5022       }
5023     } else {
5024       if ((src_enc < 16) && (dst_enc < 16)) {
5025         Assembler::pshuflw(dst, src, mode);
5026       } else if (src_enc < 16) {
5027         subptr(rsp, 64);
5028         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5029         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5030         Assembler::pshuflw(xmm0, src, mode);
5031         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5032         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5033         addptr(rsp, 64);
5034       } else if (dst_enc < 16) {
5035         subptr(rsp, 64);
5036         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5037         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5038         Assembler::pshuflw(dst, xmm0, mode);
5039         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5040         addptr(rsp, 64);
5041       } else {
5042         subptr(rsp, 64);
5043         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5044         subptr(rsp, 64);
5045         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5046         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5047         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5048         Assembler::pshuflw(xmm0, xmm1, mode);
5049         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5050         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5051         addptr(rsp, 64);
5052         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5053         addptr(rsp, 64);
5054       }
5055     }
5056   } else {
5057     Assembler::pshuflw(dst, src, mode);
5058   }
5059 }
5060 
5061 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5062   if (reachable(src)) {
5063     vandpd(dst, nds, as_Address(src), vector_len);
5064   } else {
5065     lea(rscratch1, src);
5066     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5067   }
5068 }
5069 
5070 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5071   if (reachable(src)) {
5072     vandps(dst, nds, as_Address(src), vector_len);
5073   } else {
5074     lea(rscratch1, src);
5075     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5076   }
5077 }
5078 
5079 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5080   if (reachable(src)) {
5081     vdivsd(dst, nds, as_Address(src));
5082   } else {
5083     lea(rscratch1, src);
5084     vdivsd(dst, nds, Address(rscratch1, 0));
5085   }
5086 }
5087 
5088 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5089   if (reachable(src)) {
5090     vdivss(dst, nds, as_Address(src));
5091   } else {
5092     lea(rscratch1, src);
5093     vdivss(dst, nds, Address(rscratch1, 0));
5094   }
5095 }
5096 
5097 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5098   if (reachable(src)) {
5099     vmulsd(dst, nds, as_Address(src));
5100   } else {
5101     lea(rscratch1, src);
5102     vmulsd(dst, nds, Address(rscratch1, 0));
5103   }
5104 }
5105 
5106 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5107   if (reachable(src)) {
5108     vmulss(dst, nds, as_Address(src));
5109   } else {
5110     lea(rscratch1, src);
5111     vmulss(dst, nds, Address(rscratch1, 0));
5112   }
5113 }
5114 
5115 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5116   if (reachable(src)) {
5117     vsubsd(dst, nds, as_Address(src));
5118   } else {
5119     lea(rscratch1, src);
5120     vsubsd(dst, nds, Address(rscratch1, 0));
5121   }
5122 }
5123 
5124 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5125   if (reachable(src)) {
5126     vsubss(dst, nds, as_Address(src));
5127   } else {
5128     lea(rscratch1, src);
5129     vsubss(dst, nds, Address(rscratch1, 0));
5130   }
5131 }
5132 
5133 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5134   int nds_enc = nds->encoding();
5135   int dst_enc = dst->encoding();
5136   bool dst_upper_bank = (dst_enc > 15);
5137   bool nds_upper_bank = (nds_enc > 15);
5138   if (VM_Version::supports_avx512novl() &&
5139       (nds_upper_bank || dst_upper_bank)) {
5140     if (dst_upper_bank) {
5141       subptr(rsp, 64);
5142       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5143       movflt(xmm0, nds);
5144       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5145       movflt(dst, xmm0);
5146       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5147       addptr(rsp, 64);
5148     } else {
5149       movflt(dst, nds);
5150       vxorps(dst, dst, src, Assembler::AVX_128bit);
5151     }
5152   } else {
5153     vxorps(dst, nds, src, Assembler::AVX_128bit);
5154   }
5155 }
5156 
5157 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5158   int nds_enc = nds->encoding();
5159   int dst_enc = dst->encoding();
5160   bool dst_upper_bank = (dst_enc > 15);
5161   bool nds_upper_bank = (nds_enc > 15);
5162   if (VM_Version::supports_avx512novl() &&
5163       (nds_upper_bank || dst_upper_bank)) {
5164     if (dst_upper_bank) {
5165       subptr(rsp, 64);
5166       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5167       movdbl(xmm0, nds);
5168       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5169       movdbl(dst, xmm0);
5170       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5171       addptr(rsp, 64);
5172     } else {
5173       movdbl(dst, nds);
5174       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5175     }
5176   } else {
5177     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5178   }
5179 }
5180 
5181 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5182   if (reachable(src)) {
5183     vxorpd(dst, nds, as_Address(src), vector_len);
5184   } else {
5185     lea(rscratch1, src);
5186     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5187   }
5188 }
5189 
5190 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5191   if (reachable(src)) {
5192     vxorps(dst, nds, as_Address(src), vector_len);
5193   } else {
5194     lea(rscratch1, src);
5195     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5196   }
5197 }
5198 
5199 
5200 void MacroAssembler::resolve_jobject(Register value,
5201                                      Register thread,
5202                                      Register tmp) {
5203   assert_different_registers(value, thread, tmp);
5204   Label done, not_weak;
5205   testptr(value, value);
5206   jcc(Assembler::zero, done);                // Use NULL as-is.
5207   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5208   jcc(Assembler::zero, not_weak);
5209   // Resolve jweak.
5210   movptr(value, Address(value, -JNIHandles::weak_tag_value));
5211   verify_oop(value);
5212 #if INCLUDE_ALL_GCS
5213   if (UseG1GC) {
5214     g1_write_barrier_pre(noreg /* obj */,
5215                          value /* pre_val */,
5216                          thread /* thread */,
5217                          tmp /* tmp */,
5218                          true /* tosca_live */,
5219                          true /* expand_call */);
5220   }
5221 #endif // INCLUDE_ALL_GCS
5222   jmp(done);
5223   bind(not_weak);
5224   // Resolve (untagged) jobject.
5225   movptr(value, Address(value, 0));
5226   verify_oop(value);
5227   bind(done);
5228 }
5229 
5230 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5231   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5232   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5233   // The inverted mask is sign-extended
5234   andptr(possibly_jweak, inverted_jweak_mask);
5235 }
5236 
5237 //////////////////////////////////////////////////////////////////////////////////
5238 #if INCLUDE_ALL_GCS
5239 
5240 void MacroAssembler::g1_write_barrier_pre(Register obj,
5241                                           Register pre_val,
5242                                           Register thread,
5243                                           Register tmp,
5244                                           bool tosca_live,
5245                                           bool expand_call) {
5246 
5247   // If expand_call is true then we expand the call_VM_leaf macro
5248   // directly to skip generating the check by
5249   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5250 
5251 #ifdef _LP64
5252   assert(thread == r15_thread, "must be");
5253 #endif // _LP64
5254 
5255   Label done;
5256   Label runtime;
5257 
5258   assert(pre_val != noreg, "check this code");
5259 
5260   if (obj != noreg) {
5261     assert_different_registers(obj, pre_val, tmp);
5262     assert(pre_val != rax, "check this code");
5263   }
5264 
5265   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5266                                        SATBMarkQueue::byte_offset_of_active()));
5267   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5268                                        SATBMarkQueue::byte_offset_of_index()));
5269   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5270                                        SATBMarkQueue::byte_offset_of_buf()));
5271 
5272 
5273   // Is marking active?
5274   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5275     cmpl(in_progress, 0);
5276   } else {
5277     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5278     cmpb(in_progress, 0);
5279   }
5280   jcc(Assembler::equal, done);
5281 
5282   // Do we need to load the previous value?
5283   if (obj != noreg) {
5284     load_heap_oop(pre_val, Address(obj, 0));
5285   }
5286 
5287   // Is the previous value null?
5288   cmpptr(pre_val, (int32_t) NULL_WORD);
5289   jcc(Assembler::equal, done);
5290 
5291   // Can we store original value in the thread's buffer?
5292   // Is index == 0?
5293   // (The index field is typed as size_t.)
5294 
5295   movptr(tmp, index);                   // tmp := *index_adr
5296   cmpptr(tmp, 0);                       // tmp == 0?
5297   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5298 
5299   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5300   movptr(index, tmp);                   // *index_adr := tmp
5301   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5302 
5303   // Record the previous value
5304   movptr(Address(tmp, 0), pre_val);
5305   jmp(done);
5306 
5307   bind(runtime);
5308   // save the live input values
5309   if(tosca_live) push(rax);
5310 
5311   if (obj != noreg && obj != rax)
5312     push(obj);
5313 
5314   if (pre_val != rax)
5315     push(pre_val);
5316 
5317   // Calling the runtime using the regular call_VM_leaf mechanism generates
5318   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5319   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5320   //
5321   // If we care generating the pre-barrier without a frame (e.g. in the
5322   // intrinsified Reference.get() routine) then ebp might be pointing to
5323   // the caller frame and so this check will most likely fail at runtime.
5324   //
5325   // Expanding the call directly bypasses the generation of the check.
5326   // So when we do not have have a full interpreter frame on the stack
5327   // expand_call should be passed true.
5328 
5329   NOT_LP64( push(thread); )
5330 
5331   if (expand_call) {
5332     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5333     pass_arg1(this, thread);
5334     pass_arg0(this, pre_val);
5335     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5336   } else {
5337     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5338   }
5339 
5340   NOT_LP64( pop(thread); )
5341 
5342   // save the live input values
5343   if (pre_val != rax)
5344     pop(pre_val);
5345 
5346   if (obj != noreg && obj != rax)
5347     pop(obj);
5348 
5349   if(tosca_live) pop(rax);
5350 
5351   bind(done);
5352 }
5353 
5354 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5355                                            Register new_val,
5356                                            Register thread,
5357                                            Register tmp,
5358                                            Register tmp2) {
5359 #ifdef _LP64
5360   assert(thread == r15_thread, "must be");
5361 #endif // _LP64
5362 
5363   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5364                                        DirtyCardQueue::byte_offset_of_index()));
5365   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5366                                        DirtyCardQueue::byte_offset_of_buf()));
5367 
5368   CardTableModRefBS* ct =
5369     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5370   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5371 
5372   Label done;
5373   Label runtime;
5374 
5375   // Does store cross heap regions?
5376 
5377   movptr(tmp, store_addr);
5378   xorptr(tmp, new_val);
5379   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5380   jcc(Assembler::equal, done);
5381 
5382   // crosses regions, storing NULL?
5383 
5384   cmpptr(new_val, (int32_t) NULL_WORD);
5385   jcc(Assembler::equal, done);
5386 
5387   // storing region crossing non-NULL, is card already dirty?
5388 
5389   const Register card_addr = tmp;
5390   const Register cardtable = tmp2;
5391 
5392   movptr(card_addr, store_addr);
5393   shrptr(card_addr, CardTableModRefBS::card_shift);
5394   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5395   // a valid address and therefore is not properly handled by the relocation code.
5396   movptr(cardtable, (intptr_t)ct->byte_map_base);
5397   addptr(card_addr, cardtable);
5398 
5399   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5400   jcc(Assembler::equal, done);
5401 
5402   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5403   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5404   jcc(Assembler::equal, done);
5405 
5406 
5407   // storing a region crossing, non-NULL oop, card is clean.
5408   // dirty card and log.
5409 
5410   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5411 
5412   cmpl(queue_index, 0);
5413   jcc(Assembler::equal, runtime);
5414   subl(queue_index, wordSize);
5415   movptr(tmp2, buffer);
5416 #ifdef _LP64
5417   movslq(rscratch1, queue_index);
5418   addq(tmp2, rscratch1);
5419   movq(Address(tmp2, 0), card_addr);
5420 #else
5421   addl(tmp2, queue_index);
5422   movl(Address(tmp2, 0), card_addr);
5423 #endif
5424   jmp(done);
5425 
5426   bind(runtime);
5427   // save the live input values
5428   push(store_addr);
5429   push(new_val);
5430 #ifdef _LP64
5431   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5432 #else
5433   push(thread);
5434   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5435   pop(thread);
5436 #endif
5437   pop(new_val);
5438   pop(store_addr);
5439 
5440   bind(done);
5441 }
5442 




5443 #endif // INCLUDE_ALL_GCS
5444 //////////////////////////////////////////////////////////////////////////////////
5445 
5446 
5447 void MacroAssembler::store_check(Register obj, Address dst) {
5448   store_check(obj);
5449 }
5450 
5451 void MacroAssembler::store_check(Register obj) {
5452   // Does a store check for the oop in register obj. The content of
5453   // register obj is destroyed afterwards.
5454   BarrierSet* bs = Universe::heap()->barrier_set();
5455   assert(bs->kind() == BarrierSet::CardTableForRS ||
5456          bs->kind() == BarrierSet::CardTableExtension,
5457          "Wrong barrier set kind");
5458 
5459   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5460   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5461 
5462   shrptr(obj, CardTableModRefBS::card_shift);
5463 
5464   Address card_addr;
5465 
5466   // The calculation for byte_map_base is as follows:
5467   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5468   // So this essentially converts an address to a displacement and it will
5469   // never need to be relocated. On 64bit however the value may be too
5470   // large for a 32bit displacement.
5471   intptr_t disp = (intptr_t) ct->byte_map_base;
5472   if (is_simm32(disp)) {
5473     card_addr = Address(noreg, obj, Address::times_1, disp);
5474   } else {
5475     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5476     // displacement and done in a single instruction given favorable mapping and a
5477     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5478     // entry and that entry is not properly handled by the relocation code.
5479     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5480     Address index(noreg, obj, Address::times_1);
5481     card_addr = as_Address(ArrayAddress(cardtable, index));
5482   }
5483 
5484   int dirty = CardTableModRefBS::dirty_card_val();
5485   if (UseCondCardMark) {
5486     Label L_already_dirty;
5487     if (UseConcMarkSweepGC) {
5488       membar(Assembler::StoreLoad);
5489     }
5490     cmpb(card_addr, dirty);
5491     jcc(Assembler::equal, L_already_dirty);
5492     movb(card_addr, dirty);
5493     bind(L_already_dirty);
5494   } else {
5495     movb(card_addr, dirty);
5496   }
5497 }
5498 
5499 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5500   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5501 }
5502 
5503 // Force generation of a 4 byte immediate value even if it fits into 8bit
5504 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5505   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5506 }
5507 
5508 void MacroAssembler::subptr(Register dst, Register src) {
5509   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5510 }
5511 
5512 // C++ bool manipulation
5513 void MacroAssembler::testbool(Register dst) {
5514   if(sizeof(bool) == 1)
5515     testb(dst, 0xff);
5516   else if(sizeof(bool) == 2) {
5517     // testw implementation needed for two byte bools
5518     ShouldNotReachHere();
5519   } else if(sizeof(bool) == 4)
5520     testl(dst, dst);
5521   else
5522     // unsupported
5523     ShouldNotReachHere();
5524 }
5525 
5526 void MacroAssembler::testptr(Register dst, Register src) {
5527   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5528 }
5529 
5530 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5531 void MacroAssembler::tlab_allocate(Register obj,
5532                                    Register var_size_in_bytes,
5533                                    int con_size_in_bytes,
5534                                    Register t1,
5535                                    Register t2,
5536                                    Label& slow_case) {
5537   assert_different_registers(obj, t1, t2);
5538   assert_different_registers(obj, var_size_in_bytes, t1);
5539   Register end = t2;
5540   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5541 
5542   verify_tlab();
5543 
5544   NOT_LP64(get_thread(thread));
5545 
5546   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5547   if (var_size_in_bytes == noreg) {
5548     lea(end, Address(obj, con_size_in_bytes));
5549   } else {
5550     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5551   }
5552   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5553   jcc(Assembler::above, slow_case);
5554 
5555   // update the tlab top pointer
5556   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5557 
5558   // recover var_size_in_bytes if necessary
5559   if (var_size_in_bytes == end) {
5560     subptr(var_size_in_bytes, obj);
5561   }
5562   verify_tlab();
5563 }
5564 
5565 // Preserves rbx, and rdx.
5566 Register MacroAssembler::tlab_refill(Label& retry,
5567                                      Label& try_eden,
5568                                      Label& slow_case) {
5569   Register top = rax;
5570   Register t1  = rcx; // object size
5571   Register t2  = rsi;
5572   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5573   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5574   Label do_refill, discard_tlab;
5575 
5576   if (!Universe::heap()->supports_inline_contig_alloc()) {
5577     // No allocation in the shared eden.
5578     jmp(slow_case);
5579   }
5580 
5581   NOT_LP64(get_thread(thread_reg));
5582 
5583   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5584   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5585 
5586   // calculate amount of free space
5587   subptr(t1, top);
5588   shrptr(t1, LogHeapWordSize);
5589 
5590   // Retain tlab and allocate object in shared space if
5591   // the amount free in the tlab is too large to discard.
5592   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5593   jcc(Assembler::lessEqual, discard_tlab);
5594 
5595   // Retain
5596   // %%% yuck as movptr...
5597   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5598   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5599   if (TLABStats) {
5600     // increment number of slow_allocations
5601     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5602   }
5603   jmp(try_eden);
5604 
5605   bind(discard_tlab);
5606   if (TLABStats) {
5607     // increment number of refills
5608     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5609     // accumulate wastage -- t1 is amount free in tlab
5610     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5611   }
5612 
5613   // if tlab is currently allocated (top or end != null) then
5614   // fill [top, end + alignment_reserve) with array object
5615   testptr(top, top);
5616   jcc(Assembler::zero, do_refill);
5617 
5618   // set up the mark word
5619   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5620   // set the length to the remaining space
5621   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5622   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5623   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5624   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5625   // set klass to intArrayKlass
5626   // dubious reloc why not an oop reloc?
5627   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5628   // store klass last.  concurrent gcs assumes klass length is valid if
5629   // klass field is not null.
5630   store_klass(top, t1);
5631 
5632   movptr(t1, top);
5633   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5634   incr_allocated_bytes(thread_reg, t1, 0);
5635 
5636   // refill the tlab with an eden allocation
5637   bind(do_refill);
5638   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5639   shlptr(t1, LogHeapWordSize);
5640   // allocate new tlab, address returned in top
5641   eden_allocate(top, t1, 0, t2, slow_case);
5642 
5643   // Check that t1 was preserved in eden_allocate.
5644 #ifdef ASSERT
5645   if (UseTLAB) {
5646     Label ok;
5647     Register tsize = rsi;
5648     assert_different_registers(tsize, thread_reg, t1);
5649     push(tsize);
5650     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5651     shlptr(tsize, LogHeapWordSize);
5652     cmpptr(t1, tsize);
5653     jcc(Assembler::equal, ok);
5654     STOP("assert(t1 != tlab size)");
5655     should_not_reach_here();
5656 
5657     bind(ok);
5658     pop(tsize);
5659   }
5660 #endif
5661   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5662   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5663   addptr(top, t1);
5664   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5665   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5666 
5667   if (ZeroTLAB) {
5668     // This is a fast TLAB refill, therefore the GC is not notified of it.
5669     // So compiled code must fill the new TLAB with zeroes.
5670     movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5671     zero_memory(top, t1, 0, t2);
5672   }
5673 
5674   verify_tlab();
5675   jmp(retry);
5676 
5677   return thread_reg; // for use by caller
5678 }
5679 
5680 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5681 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5682   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5683   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5684   Label done;
5685 
5686   testptr(length_in_bytes, length_in_bytes);
5687   jcc(Assembler::zero, done);
5688 
5689   // initialize topmost word, divide index by 2, check if odd and test if zero
5690   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5691 #ifdef ASSERT
5692   {
5693     Label L;
5694     testptr(length_in_bytes, BytesPerWord - 1);
5695     jcc(Assembler::zero, L);
5696     stop("length must be a multiple of BytesPerWord");
5697     bind(L);
5698   }
5699 #endif
5700   Register index = length_in_bytes;
5701   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5702   if (UseIncDec) {
5703     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5704   } else {
5705     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5706     shrptr(index, 1);
5707   }
5708 #ifndef _LP64
5709   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5710   {
5711     Label even;
5712     // note: if index was a multiple of 8, then it cannot
5713     //       be 0 now otherwise it must have been 0 before
5714     //       => if it is even, we don't need to check for 0 again
5715     jcc(Assembler::carryClear, even);
5716     // clear topmost word (no jump would be needed if conditional assignment worked here)
5717     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5718     // index could be 0 now, must check again
5719     jcc(Assembler::zero, done);
5720     bind(even);
5721   }
5722 #endif // !_LP64
5723   // initialize remaining object fields: index is a multiple of 2 now
5724   {
5725     Label loop;
5726     bind(loop);
5727     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5728     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5729     decrement(index);
5730     jcc(Assembler::notZero, loop);
5731   }
5732 
5733   bind(done);
5734 }
5735 
5736 void MacroAssembler::incr_allocated_bytes(Register thread,
5737                                           Register var_size_in_bytes,
5738                                           int con_size_in_bytes,
5739                                           Register t1) {
5740   if (!thread->is_valid()) {
5741 #ifdef _LP64
5742     thread = r15_thread;
5743 #else
5744     assert(t1->is_valid(), "need temp reg");
5745     thread = t1;
5746     get_thread(thread);
5747 #endif
5748   }
5749 
5750 #ifdef _LP64
5751   if (var_size_in_bytes->is_valid()) {
5752     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5753   } else {
5754     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5755   }
5756 #else
5757   if (var_size_in_bytes->is_valid()) {
5758     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5759   } else {
5760     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5761   }
5762   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5763 #endif
5764 }
5765 
5766 // Look up the method for a megamorphic invokeinterface call.
5767 // The target method is determined by <intf_klass, itable_index>.
5768 // The receiver klass is in recv_klass.
5769 // On success, the result will be in method_result, and execution falls through.
5770 // On failure, execution transfers to the given label.
5771 void MacroAssembler::lookup_interface_method(Register recv_klass,
5772                                              Register intf_klass,
5773                                              RegisterOrConstant itable_index,
5774                                              Register method_result,
5775                                              Register scan_temp,
5776                                              Label& L_no_such_interface) {
5777   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5778   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5779          "caller must use same register for non-constant itable index as for method");
5780 
5781   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5782   int vtable_base = in_bytes(Klass::vtable_start_offset());
5783   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5784   int scan_step   = itableOffsetEntry::size() * wordSize;
5785   int vte_size    = vtableEntry::size_in_bytes();
5786   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5787   assert(vte_size == wordSize, "else adjust times_vte_scale");
5788 
5789   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5790 
5791   // %%% Could store the aligned, prescaled offset in the klassoop.
5792   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5793 
5794   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5795   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5796   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5797 
5798   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5799   //   if (scan->interface() == intf) {
5800   //     result = (klass + scan->offset() + itable_index);
5801   //   }
5802   // }
5803   Label search, found_method;
5804 
5805   for (int peel = 1; peel >= 0; peel--) {
5806     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5807     cmpptr(intf_klass, method_result);
5808 
5809     if (peel) {
5810       jccb(Assembler::equal, found_method);
5811     } else {
5812       jccb(Assembler::notEqual, search);
5813       // (invert the test to fall through to found_method...)
5814     }
5815 
5816     if (!peel)  break;
5817 
5818     bind(search);
5819 
5820     // Check that the previous entry is non-null.  A null entry means that
5821     // the receiver class doesn't implement the interface, and wasn't the
5822     // same as when the caller was compiled.
5823     testptr(method_result, method_result);
5824     jcc(Assembler::zero, L_no_such_interface);
5825     addptr(scan_temp, scan_step);
5826   }
5827 
5828   bind(found_method);
5829 
5830   // Got a hit.
5831   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5832   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5833 }
5834 
5835 
5836 // virtual method calling
5837 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5838                                            RegisterOrConstant vtable_index,
5839                                            Register method_result) {
5840   const int base = in_bytes(Klass::vtable_start_offset());
5841   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5842   Address vtable_entry_addr(recv_klass,
5843                             vtable_index, Address::times_ptr,
5844                             base + vtableEntry::method_offset_in_bytes());
5845   movptr(method_result, vtable_entry_addr);
5846 }
5847 
5848 
5849 void MacroAssembler::check_klass_subtype(Register sub_klass,
5850                            Register super_klass,
5851                            Register temp_reg,
5852                            Label& L_success) {
5853   Label L_failure;
5854   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5855   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5856   bind(L_failure);
5857 }
5858 
5859 
5860 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5861                                                    Register super_klass,
5862                                                    Register temp_reg,
5863                                                    Label* L_success,
5864                                                    Label* L_failure,
5865                                                    Label* L_slow_path,
5866                                         RegisterOrConstant super_check_offset) {
5867   assert_different_registers(sub_klass, super_klass, temp_reg);
5868   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5869   if (super_check_offset.is_register()) {
5870     assert_different_registers(sub_klass, super_klass,
5871                                super_check_offset.as_register());
5872   } else if (must_load_sco) {
5873     assert(temp_reg != noreg, "supply either a temp or a register offset");
5874   }
5875 
5876   Label L_fallthrough;
5877   int label_nulls = 0;
5878   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5879   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5880   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5881   assert(label_nulls <= 1, "at most one NULL in the batch");
5882 
5883   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5884   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5885   Address super_check_offset_addr(super_klass, sco_offset);
5886 
5887   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5888   // range of a jccb.  If this routine grows larger, reconsider at
5889   // least some of these.
5890 #define local_jcc(assembler_cond, label)                                \
5891   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5892   else                             jcc( assembler_cond, label) /*omit semi*/
5893 
5894   // Hacked jmp, which may only be used just before L_fallthrough.
5895 #define final_jmp(label)                                                \
5896   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5897   else                            jmp(label)                /*omit semi*/
5898 
5899   // If the pointers are equal, we are done (e.g., String[] elements).
5900   // This self-check enables sharing of secondary supertype arrays among
5901   // non-primary types such as array-of-interface.  Otherwise, each such
5902   // type would need its own customized SSA.
5903   // We move this check to the front of the fast path because many
5904   // type checks are in fact trivially successful in this manner,
5905   // so we get a nicely predicted branch right at the start of the check.
5906   cmpptr(sub_klass, super_klass);
5907   local_jcc(Assembler::equal, *L_success);
5908 
5909   // Check the supertype display:
5910   if (must_load_sco) {
5911     // Positive movl does right thing on LP64.
5912     movl(temp_reg, super_check_offset_addr);
5913     super_check_offset = RegisterOrConstant(temp_reg);
5914   }
5915   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5916   cmpptr(super_klass, super_check_addr); // load displayed supertype
5917 
5918   // This check has worked decisively for primary supers.
5919   // Secondary supers are sought in the super_cache ('super_cache_addr').
5920   // (Secondary supers are interfaces and very deeply nested subtypes.)
5921   // This works in the same check above because of a tricky aliasing
5922   // between the super_cache and the primary super display elements.
5923   // (The 'super_check_addr' can address either, as the case requires.)
5924   // Note that the cache is updated below if it does not help us find
5925   // what we need immediately.
5926   // So if it was a primary super, we can just fail immediately.
5927   // Otherwise, it's the slow path for us (no success at this point).
5928 
5929   if (super_check_offset.is_register()) {
5930     local_jcc(Assembler::equal, *L_success);
5931     cmpl(super_check_offset.as_register(), sc_offset);
5932     if (L_failure == &L_fallthrough) {
5933       local_jcc(Assembler::equal, *L_slow_path);
5934     } else {
5935       local_jcc(Assembler::notEqual, *L_failure);
5936       final_jmp(*L_slow_path);
5937     }
5938   } else if (super_check_offset.as_constant() == sc_offset) {
5939     // Need a slow path; fast failure is impossible.
5940     if (L_slow_path == &L_fallthrough) {
5941       local_jcc(Assembler::equal, *L_success);
5942     } else {
5943       local_jcc(Assembler::notEqual, *L_slow_path);
5944       final_jmp(*L_success);
5945     }
5946   } else {
5947     // No slow path; it's a fast decision.
5948     if (L_failure == &L_fallthrough) {
5949       local_jcc(Assembler::equal, *L_success);
5950     } else {
5951       local_jcc(Assembler::notEqual, *L_failure);
5952       final_jmp(*L_success);
5953     }
5954   }
5955 
5956   bind(L_fallthrough);
5957 
5958 #undef local_jcc
5959 #undef final_jmp
5960 }
5961 
5962 
5963 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5964                                                    Register super_klass,
5965                                                    Register temp_reg,
5966                                                    Register temp2_reg,
5967                                                    Label* L_success,
5968                                                    Label* L_failure,
5969                                                    bool set_cond_codes) {
5970   assert_different_registers(sub_klass, super_klass, temp_reg);
5971   if (temp2_reg != noreg)
5972     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5973 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5974 
5975   Label L_fallthrough;
5976   int label_nulls = 0;
5977   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5978   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5979   assert(label_nulls <= 1, "at most one NULL in the batch");
5980 
5981   // a couple of useful fields in sub_klass:
5982   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5983   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5984   Address secondary_supers_addr(sub_klass, ss_offset);
5985   Address super_cache_addr(     sub_klass, sc_offset);
5986 
5987   // Do a linear scan of the secondary super-klass chain.
5988   // This code is rarely used, so simplicity is a virtue here.
5989   // The repne_scan instruction uses fixed registers, which we must spill.
5990   // Don't worry too much about pre-existing connections with the input regs.
5991 
5992   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5993   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5994 
5995   // Get super_klass value into rax (even if it was in rdi or rcx).
5996   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5997   if (super_klass != rax || UseCompressedOops) {
5998     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5999     mov(rax, super_klass);
6000   }
6001   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
6002   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
6003 
6004 #ifndef PRODUCT
6005   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
6006   ExternalAddress pst_counter_addr((address) pst_counter);
6007   NOT_LP64(  incrementl(pst_counter_addr) );
6008   LP64_ONLY( lea(rcx, pst_counter_addr) );
6009   LP64_ONLY( incrementl(Address(rcx, 0)) );
6010 #endif //PRODUCT
6011 
6012   // We will consult the secondary-super array.
6013   movptr(rdi, secondary_supers_addr);
6014   // Load the array length.  (Positive movl does right thing on LP64.)
6015   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6016   // Skip to start of data.
6017   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6018 
6019   // Scan RCX words at [RDI] for an occurrence of RAX.
6020   // Set NZ/Z based on last compare.
6021   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6022   // not change flags (only scas instruction which is repeated sets flags).
6023   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6024 
6025     testptr(rax,rax); // Set Z = 0
6026     repne_scan();
6027 
6028   // Unspill the temp. registers:
6029   if (pushed_rdi)  pop(rdi);
6030   if (pushed_rcx)  pop(rcx);
6031   if (pushed_rax)  pop(rax);
6032 
6033   if (set_cond_codes) {
6034     // Special hack for the AD files:  rdi is guaranteed non-zero.
6035     assert(!pushed_rdi, "rdi must be left non-NULL");
6036     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6037   }
6038 
6039   if (L_failure == &L_fallthrough)
6040         jccb(Assembler::notEqual, *L_failure);
6041   else  jcc(Assembler::notEqual, *L_failure);
6042 
6043   // Success.  Cache the super we found and proceed in triumph.
6044   movptr(super_cache_addr, super_klass);
6045 
6046   if (L_success != &L_fallthrough) {
6047     jmp(*L_success);
6048   }
6049 
6050 #undef IS_A_TEMP
6051 
6052   bind(L_fallthrough);
6053 }
6054 
6055 
6056 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6057   if (VM_Version::supports_cmov()) {
6058     cmovl(cc, dst, src);
6059   } else {
6060     Label L;
6061     jccb(negate_condition(cc), L);
6062     movl(dst, src);
6063     bind(L);
6064   }
6065 }
6066 
6067 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6068   if (VM_Version::supports_cmov()) {
6069     cmovl(cc, dst, src);
6070   } else {
6071     Label L;
6072     jccb(negate_condition(cc), L);
6073     movl(dst, src);
6074     bind(L);
6075   }
6076 }
6077 
6078 void MacroAssembler::verify_oop(Register reg, const char* s) {
6079   if (!VerifyOops) return;
6080 
6081   // Pass register number to verify_oop_subroutine
6082   const char* b = NULL;
6083   {
6084     ResourceMark rm;
6085     stringStream ss;
6086     ss.print("verify_oop: %s: %s", reg->name(), s);
6087     b = code_string(ss.as_string());
6088   }
6089   BLOCK_COMMENT("verify_oop {");
6090 #ifdef _LP64
6091   push(rscratch1);                    // save r10, trashed by movptr()
6092 #endif
6093   push(rax);                          // save rax,
6094   push(reg);                          // pass register argument
6095   ExternalAddress buffer((address) b);
6096   // avoid using pushptr, as it modifies scratch registers
6097   // and our contract is not to modify anything
6098   movptr(rax, buffer.addr());
6099   push(rax);
6100   // call indirectly to solve generation ordering problem
6101   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6102   call(rax);
6103   // Caller pops the arguments (oop, message) and restores rax, r10
6104   BLOCK_COMMENT("} verify_oop");
6105 }
6106 
6107 
6108 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6109                                                       Register tmp,
6110                                                       int offset) {
6111   intptr_t value = *delayed_value_addr;
6112   if (value != 0)
6113     return RegisterOrConstant(value + offset);
6114 
6115   // load indirectly to solve generation ordering problem
6116   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6117 
6118 #ifdef ASSERT
6119   { Label L;
6120     testptr(tmp, tmp);
6121     if (WizardMode) {
6122       const char* buf = NULL;
6123       {
6124         ResourceMark rm;
6125         stringStream ss;
6126         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6127         buf = code_string(ss.as_string());
6128       }
6129       jcc(Assembler::notZero, L);
6130       STOP(buf);
6131     } else {
6132       jccb(Assembler::notZero, L);
6133       hlt();
6134     }
6135     bind(L);
6136   }
6137 #endif
6138 
6139   if (offset != 0)
6140     addptr(tmp, offset);
6141 
6142   return RegisterOrConstant(tmp);
6143 }
6144 
6145 
6146 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6147                                          int extra_slot_offset) {
6148   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6149   int stackElementSize = Interpreter::stackElementSize;
6150   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6151 #ifdef ASSERT
6152   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6153   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6154 #endif
6155   Register             scale_reg    = noreg;
6156   Address::ScaleFactor scale_factor = Address::no_scale;
6157   if (arg_slot.is_constant()) {
6158     offset += arg_slot.as_constant() * stackElementSize;
6159   } else {
6160     scale_reg    = arg_slot.as_register();
6161     scale_factor = Address::times(stackElementSize);
6162   }
6163   offset += wordSize;           // return PC is on stack
6164   return Address(rsp, scale_reg, scale_factor, offset);
6165 }
6166 
6167 
6168 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6169   if (!VerifyOops) return;
6170 
6171   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6172   // Pass register number to verify_oop_subroutine
6173   const char* b = NULL;
6174   {
6175     ResourceMark rm;
6176     stringStream ss;
6177     ss.print("verify_oop_addr: %s", s);
6178     b = code_string(ss.as_string());
6179   }
6180 #ifdef _LP64
6181   push(rscratch1);                    // save r10, trashed by movptr()
6182 #endif
6183   push(rax);                          // save rax,
6184   // addr may contain rsp so we will have to adjust it based on the push
6185   // we just did (and on 64 bit we do two pushes)
6186   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6187   // stores rax into addr which is backwards of what was intended.
6188   if (addr.uses(rsp)) {
6189     lea(rax, addr);
6190     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6191   } else {
6192     pushptr(addr);
6193   }
6194 
6195   ExternalAddress buffer((address) b);
6196   // pass msg argument
6197   // avoid using pushptr, as it modifies scratch registers
6198   // and our contract is not to modify anything
6199   movptr(rax, buffer.addr());
6200   push(rax);
6201 
6202   // call indirectly to solve generation ordering problem
6203   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6204   call(rax);
6205   // Caller pops the arguments (addr, message) and restores rax, r10.
6206 }
6207 
6208 void MacroAssembler::verify_tlab() {
6209 #ifdef ASSERT
6210   if (UseTLAB && VerifyOops) {
6211     Label next, ok;
6212     Register t1 = rsi;
6213     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6214 
6215     push(t1);
6216     NOT_LP64(push(thread_reg));
6217     NOT_LP64(get_thread(thread_reg));
6218 
6219     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6220     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6221     jcc(Assembler::aboveEqual, next);
6222     STOP("assert(top >= start)");
6223     should_not_reach_here();
6224 
6225     bind(next);
6226     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6227     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6228     jcc(Assembler::aboveEqual, ok);
6229     STOP("assert(top <= end)");
6230     should_not_reach_here();
6231 
6232     bind(ok);
6233     NOT_LP64(pop(thread_reg));
6234     pop(t1);
6235   }
6236 #endif
6237 }
6238 
6239 class ControlWord {
6240  public:
6241   int32_t _value;
6242 
6243   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6244   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6245   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6246   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6247   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6248   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6249   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6250   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6251 
6252   void print() const {
6253     // rounding control
6254     const char* rc;
6255     switch (rounding_control()) {
6256       case 0: rc = "round near"; break;
6257       case 1: rc = "round down"; break;
6258       case 2: rc = "round up  "; break;
6259       case 3: rc = "chop      "; break;
6260     };
6261     // precision control
6262     const char* pc;
6263     switch (precision_control()) {
6264       case 0: pc = "24 bits "; break;
6265       case 1: pc = "reserved"; break;
6266       case 2: pc = "53 bits "; break;
6267       case 3: pc = "64 bits "; break;
6268     };
6269     // flags
6270     char f[9];
6271     f[0] = ' ';
6272     f[1] = ' ';
6273     f[2] = (precision   ()) ? 'P' : 'p';
6274     f[3] = (underflow   ()) ? 'U' : 'u';
6275     f[4] = (overflow    ()) ? 'O' : 'o';
6276     f[5] = (zero_divide ()) ? 'Z' : 'z';
6277     f[6] = (denormalized()) ? 'D' : 'd';
6278     f[7] = (invalid     ()) ? 'I' : 'i';
6279     f[8] = '\x0';
6280     // output
6281     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6282   }
6283 
6284 };
6285 
6286 class StatusWord {
6287  public:
6288   int32_t _value;
6289 
6290   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6291   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6292   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6293   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6294   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6295   int  top() const                     { return  (_value >> 11) & 7      ; }
6296   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6297   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6298   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6299   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6300   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6301   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6302   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6303   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6304 
6305   void print() const {
6306     // condition codes
6307     char c[5];
6308     c[0] = (C3()) ? '3' : '-';
6309     c[1] = (C2()) ? '2' : '-';
6310     c[2] = (C1()) ? '1' : '-';
6311     c[3] = (C0()) ? '0' : '-';
6312     c[4] = '\x0';
6313     // flags
6314     char f[9];
6315     f[0] = (error_status()) ? 'E' : '-';
6316     f[1] = (stack_fault ()) ? 'S' : '-';
6317     f[2] = (precision   ()) ? 'P' : '-';
6318     f[3] = (underflow   ()) ? 'U' : '-';
6319     f[4] = (overflow    ()) ? 'O' : '-';
6320     f[5] = (zero_divide ()) ? 'Z' : '-';
6321     f[6] = (denormalized()) ? 'D' : '-';
6322     f[7] = (invalid     ()) ? 'I' : '-';
6323     f[8] = '\x0';
6324     // output
6325     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6326   }
6327 
6328 };
6329 
6330 class TagWord {
6331  public:
6332   int32_t _value;
6333 
6334   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6335 
6336   void print() const {
6337     printf("%04x", _value & 0xFFFF);
6338   }
6339 
6340 };
6341 
6342 class FPU_Register {
6343  public:
6344   int32_t _m0;
6345   int32_t _m1;
6346   int16_t _ex;
6347 
6348   bool is_indefinite() const           {
6349     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6350   }
6351 
6352   void print() const {
6353     char  sign = (_ex < 0) ? '-' : '+';
6354     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6355     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6356   };
6357 
6358 };
6359 
6360 class FPU_State {
6361  public:
6362   enum {
6363     register_size       = 10,
6364     number_of_registers =  8,
6365     register_mask       =  7
6366   };
6367 
6368   ControlWord  _control_word;
6369   StatusWord   _status_word;
6370   TagWord      _tag_word;
6371   int32_t      _error_offset;
6372   int32_t      _error_selector;
6373   int32_t      _data_offset;
6374   int32_t      _data_selector;
6375   int8_t       _register[register_size * number_of_registers];
6376 
6377   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6378   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6379 
6380   const char* tag_as_string(int tag) const {
6381     switch (tag) {
6382       case 0: return "valid";
6383       case 1: return "zero";
6384       case 2: return "special";
6385       case 3: return "empty";
6386     }
6387     ShouldNotReachHere();
6388     return NULL;
6389   }
6390 
6391   void print() const {
6392     // print computation registers
6393     { int t = _status_word.top();
6394       for (int i = 0; i < number_of_registers; i++) {
6395         int j = (i - t) & register_mask;
6396         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6397         st(j)->print();
6398         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6399       }
6400     }
6401     printf("\n");
6402     // print control registers
6403     printf("ctrl = "); _control_word.print(); printf("\n");
6404     printf("stat = "); _status_word .print(); printf("\n");
6405     printf("tags = "); _tag_word    .print(); printf("\n");
6406   }
6407 
6408 };
6409 
6410 class Flag_Register {
6411  public:
6412   int32_t _value;
6413 
6414   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6415   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6416   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6417   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6418   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6419   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6420   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6421 
6422   void print() const {
6423     // flags
6424     char f[8];
6425     f[0] = (overflow       ()) ? 'O' : '-';
6426     f[1] = (direction      ()) ? 'D' : '-';
6427     f[2] = (sign           ()) ? 'S' : '-';
6428     f[3] = (zero           ()) ? 'Z' : '-';
6429     f[4] = (auxiliary_carry()) ? 'A' : '-';
6430     f[5] = (parity         ()) ? 'P' : '-';
6431     f[6] = (carry          ()) ? 'C' : '-';
6432     f[7] = '\x0';
6433     // output
6434     printf("%08x  flags = %s", _value, f);
6435   }
6436 
6437 };
6438 
6439 class IU_Register {
6440  public:
6441   int32_t _value;
6442 
6443   void print() const {
6444     printf("%08x  %11d", _value, _value);
6445   }
6446 
6447 };
6448 
6449 class IU_State {
6450  public:
6451   Flag_Register _eflags;
6452   IU_Register   _rdi;
6453   IU_Register   _rsi;
6454   IU_Register   _rbp;
6455   IU_Register   _rsp;
6456   IU_Register   _rbx;
6457   IU_Register   _rdx;
6458   IU_Register   _rcx;
6459   IU_Register   _rax;
6460 
6461   void print() const {
6462     // computation registers
6463     printf("rax,  = "); _rax.print(); printf("\n");
6464     printf("rbx,  = "); _rbx.print(); printf("\n");
6465     printf("rcx  = "); _rcx.print(); printf("\n");
6466     printf("rdx  = "); _rdx.print(); printf("\n");
6467     printf("rdi  = "); _rdi.print(); printf("\n");
6468     printf("rsi  = "); _rsi.print(); printf("\n");
6469     printf("rbp,  = "); _rbp.print(); printf("\n");
6470     printf("rsp  = "); _rsp.print(); printf("\n");
6471     printf("\n");
6472     // control registers
6473     printf("flgs = "); _eflags.print(); printf("\n");
6474   }
6475 };
6476 
6477 
6478 class CPU_State {
6479  public:
6480   FPU_State _fpu_state;
6481   IU_State  _iu_state;
6482 
6483   void print() const {
6484     printf("--------------------------------------------------\n");
6485     _iu_state .print();
6486     printf("\n");
6487     _fpu_state.print();
6488     printf("--------------------------------------------------\n");
6489   }
6490 
6491 };
6492 
6493 
6494 static void _print_CPU_state(CPU_State* state) {
6495   state->print();
6496 };
6497 
6498 
6499 void MacroAssembler::print_CPU_state() {
6500   push_CPU_state();
6501   push(rsp);                // pass CPU state
6502   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6503   addptr(rsp, wordSize);       // discard argument
6504   pop_CPU_state();
6505 }
6506 
6507 
6508 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6509   static int counter = 0;
6510   FPU_State* fs = &state->_fpu_state;
6511   counter++;
6512   // For leaf calls, only verify that the top few elements remain empty.
6513   // We only need 1 empty at the top for C2 code.
6514   if( stack_depth < 0 ) {
6515     if( fs->tag_for_st(7) != 3 ) {
6516       printf("FPR7 not empty\n");
6517       state->print();
6518       assert(false, "error");
6519       return false;
6520     }
6521     return true;                // All other stack states do not matter
6522   }
6523 
6524   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6525          "bad FPU control word");
6526 
6527   // compute stack depth
6528   int i = 0;
6529   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6530   int d = i;
6531   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6532   // verify findings
6533   if (i != FPU_State::number_of_registers) {
6534     // stack not contiguous
6535     printf("%s: stack not contiguous at ST%d\n", s, i);
6536     state->print();
6537     assert(false, "error");
6538     return false;
6539   }
6540   // check if computed stack depth corresponds to expected stack depth
6541   if (stack_depth < 0) {
6542     // expected stack depth is -stack_depth or less
6543     if (d > -stack_depth) {
6544       // too many elements on the stack
6545       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6546       state->print();
6547       assert(false, "error");
6548       return false;
6549     }
6550   } else {
6551     // expected stack depth is stack_depth
6552     if (d != stack_depth) {
6553       // wrong stack depth
6554       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6555       state->print();
6556       assert(false, "error");
6557       return false;
6558     }
6559   }
6560   // everything is cool
6561   return true;
6562 }
6563 
6564 
6565 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6566   if (!VerifyFPU) return;
6567   push_CPU_state();
6568   push(rsp);                // pass CPU state
6569   ExternalAddress msg((address) s);
6570   // pass message string s
6571   pushptr(msg.addr());
6572   push(stack_depth);        // pass stack depth
6573   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6574   addptr(rsp, 3 * wordSize);   // discard arguments
6575   // check for error
6576   { Label L;
6577     testl(rax, rax);
6578     jcc(Assembler::notZero, L);
6579     int3();                  // break if error condition
6580     bind(L);
6581   }
6582   pop_CPU_state();
6583 }
6584 
6585 void MacroAssembler::restore_cpu_control_state_after_jni() {
6586   // Either restore the MXCSR register after returning from the JNI Call
6587   // or verify that it wasn't changed (with -Xcheck:jni flag).
6588   if (VM_Version::supports_sse()) {
6589     if (RestoreMXCSROnJNICalls) {
6590       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6591     } else if (CheckJNICalls) {
6592       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6593     }
6594   }
6595   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6596   vzeroupper();
6597 
6598 #ifndef _LP64
6599   // Either restore the x87 floating pointer control word after returning
6600   // from the JNI call or verify that it wasn't changed.
6601   if (CheckJNICalls) {
6602     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6603   }
6604 #endif // _LP64
6605 }
6606 
6607 // ((OopHandle)result).resolve();
6608 void MacroAssembler::resolve_oop_handle(Register result) {
6609   // OopHandle::resolve is an indirection.
6610   movptr(result, Address(result, 0));
6611 }
6612 
6613 void MacroAssembler::load_mirror(Register mirror, Register method) {
6614   // get mirror
6615   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6616   movptr(mirror, Address(method, Method::const_offset()));
6617   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6618   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6619   movptr(mirror, Address(mirror, mirror_offset));
6620   resolve_oop_handle(mirror);
6621 }
6622 
6623 void MacroAssembler::load_klass(Register dst, Register src) {
6624 #ifdef _LP64
6625   if (UseCompressedClassPointers) {
6626     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6627     decode_klass_not_null(dst);
6628   } else
6629 #endif
6630     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6631 }
6632 
6633 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6634   load_klass(dst, src);
6635   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6636 }
6637 
6638 void MacroAssembler::store_klass(Register dst, Register src) {
6639 #ifdef _LP64
6640   if (UseCompressedClassPointers) {
6641     encode_klass_not_null(src);
6642     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6643   } else
6644 #endif
6645     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6646 }
6647 
6648 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6649 #ifdef _LP64
6650   // FIXME: Must change all places where we try to load the klass.
6651   if (UseCompressedOops) {
6652     movl(dst, src);
6653     decode_heap_oop(dst);
6654   } else
6655 #endif
6656     movptr(dst, src);
6657 }
6658 
6659 // Doesn't do verfication, generates fixed size code
6660 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6661 #ifdef _LP64
6662   if (UseCompressedOops) {
6663     movl(dst, src);
6664     decode_heap_oop_not_null(dst);
6665   } else
6666 #endif
6667     movptr(dst, src);
6668 }
6669 
6670 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6671 #ifdef _LP64
6672   if (UseCompressedOops) {
6673     assert(!dst.uses(src), "not enough registers");
6674     encode_heap_oop(src);
6675     movl(dst, src);
6676   } else
6677 #endif
6678     movptr(dst, src);
6679 }
6680 
6681 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6682   assert_different_registers(src1, tmp);
6683 #ifdef _LP64
6684   if (UseCompressedOops) {
6685     bool did_push = false;
6686     if (tmp == noreg) {
6687       tmp = rax;
6688       push(tmp);
6689       did_push = true;
6690       assert(!src2.uses(rsp), "can't push");
6691     }
6692     load_heap_oop(tmp, src2);
6693     cmpptr(src1, tmp);
6694     if (did_push)  pop(tmp);
6695   } else
6696 #endif
6697     cmpptr(src1, src2);
6698 }
6699 
6700 // Used for storing NULLs.
6701 void MacroAssembler::store_heap_oop_null(Address dst) {
6702 #ifdef _LP64
6703   if (UseCompressedOops) {
6704     movl(dst, (int32_t)NULL_WORD);
6705   } else {
6706     movslq(dst, (int32_t)NULL_WORD);
6707   }
6708 #else
6709   movl(dst, (int32_t)NULL_WORD);
6710 #endif
6711 }
6712 
6713 #ifdef _LP64
6714 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6715   if (UseCompressedClassPointers) {
6716     // Store to klass gap in destination
6717     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6718   }
6719 }
6720 
6721 #ifdef ASSERT
6722 void MacroAssembler::verify_heapbase(const char* msg) {
6723   assert (UseCompressedOops, "should be compressed");
6724   assert (Universe::heap() != NULL, "java heap should be initialized");
6725   if (CheckCompressedOops) {
6726     Label ok;
6727     push(rscratch1); // cmpptr trashes rscratch1
6728     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6729     jcc(Assembler::equal, ok);
6730     STOP(msg);
6731     bind(ok);
6732     pop(rscratch1);
6733   }
6734 }
6735 #endif
6736 
6737 // Algorithm must match oop.inline.hpp encode_heap_oop.
6738 void MacroAssembler::encode_heap_oop(Register r) {
6739 #ifdef ASSERT
6740   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6741 #endif
6742   verify_oop(r, "broken oop in encode_heap_oop");
6743   if (Universe::narrow_oop_base() == NULL) {
6744     if (Universe::narrow_oop_shift() != 0) {
6745       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6746       shrq(r, LogMinObjAlignmentInBytes);
6747     }
6748     return;
6749   }
6750   testq(r, r);
6751   cmovq(Assembler::equal, r, r12_heapbase);
6752   subq(r, r12_heapbase);
6753   shrq(r, LogMinObjAlignmentInBytes);
6754 }
6755 
6756 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6757 #ifdef ASSERT
6758   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6759   if (CheckCompressedOops) {
6760     Label ok;
6761     testq(r, r);
6762     jcc(Assembler::notEqual, ok);
6763     STOP("null oop passed to encode_heap_oop_not_null");
6764     bind(ok);
6765   }
6766 #endif
6767   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6768   if (Universe::narrow_oop_base() != NULL) {
6769     subq(r, r12_heapbase);
6770   }
6771   if (Universe::narrow_oop_shift() != 0) {
6772     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6773     shrq(r, LogMinObjAlignmentInBytes);
6774   }
6775 }
6776 
6777 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6778 #ifdef ASSERT
6779   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6780   if (CheckCompressedOops) {
6781     Label ok;
6782     testq(src, src);
6783     jcc(Assembler::notEqual, ok);
6784     STOP("null oop passed to encode_heap_oop_not_null2");
6785     bind(ok);
6786   }
6787 #endif
6788   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6789   if (dst != src) {
6790     movq(dst, src);
6791   }
6792   if (Universe::narrow_oop_base() != NULL) {
6793     subq(dst, r12_heapbase);
6794   }
6795   if (Universe::narrow_oop_shift() != 0) {
6796     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6797     shrq(dst, LogMinObjAlignmentInBytes);
6798   }
6799 }
6800 
6801 void  MacroAssembler::decode_heap_oop(Register r) {
6802 #ifdef ASSERT
6803   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6804 #endif
6805   if (Universe::narrow_oop_base() == NULL) {
6806     if (Universe::narrow_oop_shift() != 0) {
6807       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6808       shlq(r, LogMinObjAlignmentInBytes);
6809     }
6810   } else {
6811     Label done;
6812     shlq(r, LogMinObjAlignmentInBytes);
6813     jccb(Assembler::equal, done);
6814     addq(r, r12_heapbase);
6815     bind(done);
6816   }
6817   verify_oop(r, "broken oop in decode_heap_oop");
6818 }
6819 
6820 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6821   // Note: it will change flags
6822   assert (UseCompressedOops, "should only be used for compressed headers");
6823   assert (Universe::heap() != NULL, "java heap should be initialized");
6824   // Cannot assert, unverified entry point counts instructions (see .ad file)
6825   // vtableStubs also counts instructions in pd_code_size_limit.
6826   // Also do not verify_oop as this is called by verify_oop.
6827   if (Universe::narrow_oop_shift() != 0) {
6828     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6829     shlq(r, LogMinObjAlignmentInBytes);
6830     if (Universe::narrow_oop_base() != NULL) {
6831       addq(r, r12_heapbase);
6832     }
6833   } else {
6834     assert (Universe::narrow_oop_base() == NULL, "sanity");
6835   }
6836 }
6837 
6838 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6839   // Note: it will change flags
6840   assert (UseCompressedOops, "should only be used for compressed headers");
6841   assert (Universe::heap() != NULL, "java heap should be initialized");
6842   // Cannot assert, unverified entry point counts instructions (see .ad file)
6843   // vtableStubs also counts instructions in pd_code_size_limit.
6844   // Also do not verify_oop as this is called by verify_oop.
6845   if (Universe::narrow_oop_shift() != 0) {
6846     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6847     if (LogMinObjAlignmentInBytes == Address::times_8) {
6848       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6849     } else {
6850       if (dst != src) {
6851         movq(dst, src);
6852       }
6853       shlq(dst, LogMinObjAlignmentInBytes);
6854       if (Universe::narrow_oop_base() != NULL) {
6855         addq(dst, r12_heapbase);
6856       }
6857     }
6858   } else {
6859     assert (Universe::narrow_oop_base() == NULL, "sanity");
6860     if (dst != src) {
6861       movq(dst, src);
6862     }
6863   }
6864 }
6865 
6866 void MacroAssembler::encode_klass_not_null(Register r) {
6867   if (Universe::narrow_klass_base() != NULL) {
6868     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6869     assert(r != r12_heapbase, "Encoding a klass in r12");
6870     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6871     subq(r, r12_heapbase);
6872   }
6873   if (Universe::narrow_klass_shift() != 0) {
6874     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6875     shrq(r, LogKlassAlignmentInBytes);
6876   }
6877   if (Universe::narrow_klass_base() != NULL) {
6878     reinit_heapbase();
6879   }
6880 }
6881 
6882 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6883   if (dst == src) {
6884     encode_klass_not_null(src);
6885   } else {
6886     if (Universe::narrow_klass_base() != NULL) {
6887       mov64(dst, (int64_t)Universe::narrow_klass_base());
6888       negq(dst);
6889       addq(dst, src);
6890     } else {
6891       movptr(dst, src);
6892     }
6893     if (Universe::narrow_klass_shift() != 0) {
6894       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6895       shrq(dst, LogKlassAlignmentInBytes);
6896     }
6897   }
6898 }
6899 
6900 // Function instr_size_for_decode_klass_not_null() counts the instructions
6901 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6902 // when (Universe::heap() != NULL).  Hence, if the instructions they
6903 // generate change, then this method needs to be updated.
6904 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6905   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6906   if (Universe::narrow_klass_base() != NULL) {
6907     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6908     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6909   } else {
6910     // longest load decode klass function, mov64, leaq
6911     return 16;
6912   }
6913 }
6914 
6915 // !!! If the instructions that get generated here change then function
6916 // instr_size_for_decode_klass_not_null() needs to get updated.
6917 void  MacroAssembler::decode_klass_not_null(Register r) {
6918   // Note: it will change flags
6919   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6920   assert(r != r12_heapbase, "Decoding a klass in r12");
6921   // Cannot assert, unverified entry point counts instructions (see .ad file)
6922   // vtableStubs also counts instructions in pd_code_size_limit.
6923   // Also do not verify_oop as this is called by verify_oop.
6924   if (Universe::narrow_klass_shift() != 0) {
6925     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6926     shlq(r, LogKlassAlignmentInBytes);
6927   }
6928   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6929   if (Universe::narrow_klass_base() != NULL) {
6930     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6931     addq(r, r12_heapbase);
6932     reinit_heapbase();
6933   }
6934 }
6935 
6936 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6937   // Note: it will change flags
6938   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6939   if (dst == src) {
6940     decode_klass_not_null(dst);
6941   } else {
6942     // Cannot assert, unverified entry point counts instructions (see .ad file)
6943     // vtableStubs also counts instructions in pd_code_size_limit.
6944     // Also do not verify_oop as this is called by verify_oop.
6945     mov64(dst, (int64_t)Universe::narrow_klass_base());
6946     if (Universe::narrow_klass_shift() != 0) {
6947       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6948       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6949       leaq(dst, Address(dst, src, Address::times_8, 0));
6950     } else {
6951       addq(dst, src);
6952     }
6953   }
6954 }
6955 
6956 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6957   assert (UseCompressedOops, "should only be used for compressed headers");
6958   assert (Universe::heap() != NULL, "java heap should be initialized");
6959   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6960   int oop_index = oop_recorder()->find_index(obj);
6961   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6962   mov_narrow_oop(dst, oop_index, rspec);
6963 }
6964 
6965 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6966   assert (UseCompressedOops, "should only be used for compressed headers");
6967   assert (Universe::heap() != NULL, "java heap should be initialized");
6968   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6969   int oop_index = oop_recorder()->find_index(obj);
6970   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6971   mov_narrow_oop(dst, oop_index, rspec);
6972 }
6973 
6974 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6975   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6976   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6977   int klass_index = oop_recorder()->find_index(k);
6978   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6979   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6980 }
6981 
6982 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
6983   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6984   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6985   int klass_index = oop_recorder()->find_index(k);
6986   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6987   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6988 }
6989 
6990 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
6991   assert (UseCompressedOops, "should only be used for compressed headers");
6992   assert (Universe::heap() != NULL, "java heap should be initialized");
6993   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6994   int oop_index = oop_recorder()->find_index(obj);
6995   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6996   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6997 }
6998 
6999 void  MacroAssembler::cmp_narrow_oop(Address 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   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7006 }
7007 
7008 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7009   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7010   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7011   int klass_index = oop_recorder()->find_index(k);
7012   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7013   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7014 }
7015 
7016 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7017   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7018   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7019   int klass_index = oop_recorder()->find_index(k);
7020   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7021   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7022 }
7023 
7024 void MacroAssembler::reinit_heapbase() {
7025   if (UseCompressedOops || UseCompressedClassPointers) {
7026     if (Universe::heap() != NULL) {
7027       if (Universe::narrow_oop_base() == NULL) {
7028         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7029       } else {
7030         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7031       }
7032     } else {
7033       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7034     }
7035   }
7036 }
7037 
7038 #endif // _LP64
7039 
7040 // C2 compiled method's prolog code.
7041 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7042 
7043   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7044   // NativeJump::patch_verified_entry will be able to patch out the entry
7045   // code safely. The push to verify stack depth is ok at 5 bytes,
7046   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7047   // stack bang then we must use the 6 byte frame allocation even if
7048   // we have no frame. :-(
7049   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7050 
7051   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7052   // Remove word for return addr
7053   framesize -= wordSize;
7054   stack_bang_size -= wordSize;
7055 
7056   // Calls to C2R adapters often do not accept exceptional returns.
7057   // We require that their callers must bang for them.  But be careful, because
7058   // some VM calls (such as call site linkage) can use several kilobytes of
7059   // stack.  But the stack safety zone should account for that.
7060   // See bugs 4446381, 4468289, 4497237.
7061   if (stack_bang_size > 0) {
7062     generate_stack_overflow_check(stack_bang_size);
7063 
7064     // We always push rbp, so that on return to interpreter rbp, will be
7065     // restored correctly and we can correct the stack.
7066     push(rbp);
7067     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7068     if (PreserveFramePointer) {
7069       mov(rbp, rsp);
7070     }
7071     // Remove word for ebp
7072     framesize -= wordSize;
7073 
7074     // Create frame
7075     if (framesize) {
7076       subptr(rsp, framesize);
7077     }
7078   } else {
7079     // Create frame (force generation of a 4 byte immediate value)
7080     subptr_imm32(rsp, framesize);
7081 
7082     // Save RBP register now.
7083     framesize -= wordSize;
7084     movptr(Address(rsp, framesize), rbp);
7085     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7086     if (PreserveFramePointer) {
7087       movptr(rbp, rsp);
7088       if (framesize > 0) {
7089         addptr(rbp, framesize);
7090       }
7091     }
7092   }
7093 
7094   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7095     framesize -= wordSize;
7096     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7097   }
7098 
7099 #ifndef _LP64
7100   // If method sets FPU control word do it now
7101   if (fp_mode_24b) {
7102     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7103   }
7104   if (UseSSE >= 2 && VerifyFPU) {
7105     verify_FPU(0, "FPU stack must be clean on entry");
7106   }
7107 #endif
7108 
7109 #ifdef ASSERT
7110   if (VerifyStackAtCalls) {
7111     Label L;
7112     push(rax);
7113     mov(rax, rsp);
7114     andptr(rax, StackAlignmentInBytes-1);
7115     cmpptr(rax, StackAlignmentInBytes-wordSize);
7116     pop(rax);
7117     jcc(Assembler::equal, L);
7118     STOP("Stack is not properly aligned!");
7119     bind(L);
7120   }
7121 #endif
7122 
7123 }
7124 
7125 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
7126   // cnt - number of qwords (8-byte words).
7127   // base - start address, qword aligned.
7128   // is_large - if optimizers know cnt is larger than InitArrayShortSize
7129   assert(base==rdi, "base register must be edi for rep stos");
7130   assert(tmp==rax,   "tmp register must be eax for rep stos");
7131   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7132   assert(InitArrayShortSize % BytesPerLong == 0,
7133     "InitArrayShortSize should be the multiple of BytesPerLong");
7134 
7135   Label DONE;
7136 
7137   xorptr(tmp, tmp);
7138 
7139   if (!is_large) {
7140     Label LOOP, LONG;
7141     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7142     jccb(Assembler::greater, LONG);
7143 
7144     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7145 
7146     decrement(cnt);
7147     jccb(Assembler::negative, DONE); // Zero length
7148 
7149     // Use individual pointer-sized stores for small counts:
7150     BIND(LOOP);
7151     movptr(Address(base, cnt, Address::times_ptr), tmp);
7152     decrement(cnt);
7153     jccb(Assembler::greaterEqual, LOOP);
7154     jmpb(DONE);
7155 
7156     BIND(LONG);
7157   }
7158 
7159   // Use longer rep-prefixed ops for non-small counts:
7160   if (UseFastStosb) {
7161     shlptr(cnt, 3); // convert to number of bytes
7162     rep_stosb();
7163   } else {
7164     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7165     rep_stos();
7166   }
7167 
7168   BIND(DONE);
7169 }
7170 
7171 #ifdef COMPILER2
7172 
7173 // IndexOf for constant substrings with size >= 8 chars
7174 // which don't need to be loaded through stack.
7175 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7176                                       Register cnt1, Register cnt2,
7177                                       int int_cnt2,  Register result,
7178                                       XMMRegister vec, Register tmp,
7179                                       int ae) {
7180   ShortBranchVerifier sbv(this);
7181   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7182   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7183 
7184   // This method uses the pcmpestri instruction with bound registers
7185   //   inputs:
7186   //     xmm - substring
7187   //     rax - substring length (elements count)
7188   //     mem - scanned string
7189   //     rdx - string length (elements count)
7190   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7191   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7192   //   outputs:
7193   //     rcx - matched index in string
7194   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7195   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7196   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7197   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7198   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7199 
7200   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7201         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7202         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7203 
7204   // Note, inline_string_indexOf() generates checks:
7205   // if (substr.count > string.count) return -1;
7206   // if (substr.count == 0) return 0;
7207   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7208 
7209   // Load substring.
7210   if (ae == StrIntrinsicNode::UL) {
7211     pmovzxbw(vec, Address(str2, 0));
7212   } else {
7213     movdqu(vec, Address(str2, 0));
7214   }
7215   movl(cnt2, int_cnt2);
7216   movptr(result, str1); // string addr
7217 
7218   if (int_cnt2 > stride) {
7219     jmpb(SCAN_TO_SUBSTR);
7220 
7221     // Reload substr for rescan, this code
7222     // is executed only for large substrings (> 8 chars)
7223     bind(RELOAD_SUBSTR);
7224     if (ae == StrIntrinsicNode::UL) {
7225       pmovzxbw(vec, Address(str2, 0));
7226     } else {
7227       movdqu(vec, Address(str2, 0));
7228     }
7229     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7230 
7231     bind(RELOAD_STR);
7232     // We came here after the beginning of the substring was
7233     // matched but the rest of it was not so we need to search
7234     // again. Start from the next element after the previous match.
7235 
7236     // cnt2 is number of substring reminding elements and
7237     // cnt1 is number of string reminding elements when cmp failed.
7238     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7239     subl(cnt1, cnt2);
7240     addl(cnt1, int_cnt2);
7241     movl(cnt2, int_cnt2); // Now restore cnt2
7242 
7243     decrementl(cnt1);     // Shift to next element
7244     cmpl(cnt1, cnt2);
7245     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7246 
7247     addptr(result, (1<<scale1));
7248 
7249   } // (int_cnt2 > 8)
7250 
7251   // Scan string for start of substr in 16-byte vectors
7252   bind(SCAN_TO_SUBSTR);
7253   pcmpestri(vec, Address(result, 0), mode);
7254   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7255   subl(cnt1, stride);
7256   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7257   cmpl(cnt1, cnt2);
7258   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7259   addptr(result, 16);
7260   jmpb(SCAN_TO_SUBSTR);
7261 
7262   // Found a potential substr
7263   bind(FOUND_CANDIDATE);
7264   // Matched whole vector if first element matched (tmp(rcx) == 0).
7265   if (int_cnt2 == stride) {
7266     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7267   } else { // int_cnt2 > 8
7268     jccb(Assembler::overflow, FOUND_SUBSTR);
7269   }
7270   // After pcmpestri tmp(rcx) contains matched element index
7271   // Compute start addr of substr
7272   lea(result, Address(result, tmp, scale1));
7273 
7274   // Make sure string is still long enough
7275   subl(cnt1, tmp);
7276   cmpl(cnt1, cnt2);
7277   if (int_cnt2 == stride) {
7278     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7279   } else { // int_cnt2 > 8
7280     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7281   }
7282   // Left less then substring.
7283 
7284   bind(RET_NOT_FOUND);
7285   movl(result, -1);
7286   jmp(EXIT);
7287 
7288   if (int_cnt2 > stride) {
7289     // This code is optimized for the case when whole substring
7290     // is matched if its head is matched.
7291     bind(MATCH_SUBSTR_HEAD);
7292     pcmpestri(vec, Address(result, 0), mode);
7293     // Reload only string if does not match
7294     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7295 
7296     Label CONT_SCAN_SUBSTR;
7297     // Compare the rest of substring (> 8 chars).
7298     bind(FOUND_SUBSTR);
7299     // First 8 chars are already matched.
7300     negptr(cnt2);
7301     addptr(cnt2, stride);
7302 
7303     bind(SCAN_SUBSTR);
7304     subl(cnt1, stride);
7305     cmpl(cnt2, -stride); // Do not read beyond substring
7306     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7307     // Back-up strings to avoid reading beyond substring:
7308     // cnt1 = cnt1 - cnt2 + 8
7309     addl(cnt1, cnt2); // cnt2 is negative
7310     addl(cnt1, stride);
7311     movl(cnt2, stride); negptr(cnt2);
7312     bind(CONT_SCAN_SUBSTR);
7313     if (int_cnt2 < (int)G) {
7314       int tail_off1 = int_cnt2<<scale1;
7315       int tail_off2 = int_cnt2<<scale2;
7316       if (ae == StrIntrinsicNode::UL) {
7317         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7318       } else {
7319         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7320       }
7321       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7322     } else {
7323       // calculate index in register to avoid integer overflow (int_cnt2*2)
7324       movl(tmp, int_cnt2);
7325       addptr(tmp, cnt2);
7326       if (ae == StrIntrinsicNode::UL) {
7327         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7328       } else {
7329         movdqu(vec, Address(str2, tmp, scale2, 0));
7330       }
7331       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7332     }
7333     // Need to reload strings pointers if not matched whole vector
7334     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7335     addptr(cnt2, stride);
7336     jcc(Assembler::negative, SCAN_SUBSTR);
7337     // Fall through if found full substring
7338 
7339   } // (int_cnt2 > 8)
7340 
7341   bind(RET_FOUND);
7342   // Found result if we matched full small substring.
7343   // Compute substr offset
7344   subptr(result, str1);
7345   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7346     shrl(result, 1); // index
7347   }
7348   bind(EXIT);
7349 
7350 } // string_indexofC8
7351 
7352 // Small strings are loaded through stack if they cross page boundary.
7353 void MacroAssembler::string_indexof(Register str1, Register str2,
7354                                     Register cnt1, Register cnt2,
7355                                     int int_cnt2,  Register result,
7356                                     XMMRegister vec, Register tmp,
7357                                     int ae) {
7358   ShortBranchVerifier sbv(this);
7359   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7360   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7361 
7362   //
7363   // int_cnt2 is length of small (< 8 chars) constant substring
7364   // or (-1) for non constant substring in which case its length
7365   // is in cnt2 register.
7366   //
7367   // Note, inline_string_indexOf() generates checks:
7368   // if (substr.count > string.count) return -1;
7369   // if (substr.count == 0) return 0;
7370   //
7371   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7372   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7373   // This method uses the pcmpestri instruction with bound registers
7374   //   inputs:
7375   //     xmm - substring
7376   //     rax - substring length (elements count)
7377   //     mem - scanned string
7378   //     rdx - string length (elements count)
7379   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7380   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7381   //   outputs:
7382   //     rcx - matched index in string
7383   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7384   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7385   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7386   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7387 
7388   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7389         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7390         FOUND_CANDIDATE;
7391 
7392   { //========================================================
7393     // We don't know where these strings are located
7394     // and we can't read beyond them. Load them through stack.
7395     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7396 
7397     movptr(tmp, rsp); // save old SP
7398 
7399     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7400       if (int_cnt2 == (1>>scale2)) { // One byte
7401         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7402         load_unsigned_byte(result, Address(str2, 0));
7403         movdl(vec, result); // move 32 bits
7404       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7405         // Not enough header space in 32-bit VM: 12+3 = 15.
7406         movl(result, Address(str2, -1));
7407         shrl(result, 8);
7408         movdl(vec, result); // move 32 bits
7409       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7410         load_unsigned_short(result, Address(str2, 0));
7411         movdl(vec, result); // move 32 bits
7412       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7413         movdl(vec, Address(str2, 0)); // move 32 bits
7414       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7415         movq(vec, Address(str2, 0));  // move 64 bits
7416       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7417         // Array header size is 12 bytes in 32-bit VM
7418         // + 6 bytes for 3 chars == 18 bytes,
7419         // enough space to load vec and shift.
7420         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7421         if (ae == StrIntrinsicNode::UL) {
7422           int tail_off = int_cnt2-8;
7423           pmovzxbw(vec, Address(str2, tail_off));
7424           psrldq(vec, -2*tail_off);
7425         }
7426         else {
7427           int tail_off = int_cnt2*(1<<scale2);
7428           movdqu(vec, Address(str2, tail_off-16));
7429           psrldq(vec, 16-tail_off);
7430         }
7431       }
7432     } else { // not constant substring
7433       cmpl(cnt2, stride);
7434       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7435 
7436       // We can read beyond string if srt+16 does not cross page boundary
7437       // since heaps are aligned and mapped by pages.
7438       assert(os::vm_page_size() < (int)G, "default page should be small");
7439       movl(result, str2); // We need only low 32 bits
7440       andl(result, (os::vm_page_size()-1));
7441       cmpl(result, (os::vm_page_size()-16));
7442       jccb(Assembler::belowEqual, CHECK_STR);
7443 
7444       // Move small strings to stack to allow load 16 bytes into vec.
7445       subptr(rsp, 16);
7446       int stk_offset = wordSize-(1<<scale2);
7447       push(cnt2);
7448 
7449       bind(COPY_SUBSTR);
7450       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7451         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7452         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7453       } else if (ae == StrIntrinsicNode::UU) {
7454         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7455         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7456       }
7457       decrement(cnt2);
7458       jccb(Assembler::notZero, COPY_SUBSTR);
7459 
7460       pop(cnt2);
7461       movptr(str2, rsp);  // New substring address
7462     } // non constant
7463 
7464     bind(CHECK_STR);
7465     cmpl(cnt1, stride);
7466     jccb(Assembler::aboveEqual, BIG_STRINGS);
7467 
7468     // Check cross page boundary.
7469     movl(result, str1); // We need only low 32 bits
7470     andl(result, (os::vm_page_size()-1));
7471     cmpl(result, (os::vm_page_size()-16));
7472     jccb(Assembler::belowEqual, BIG_STRINGS);
7473 
7474     subptr(rsp, 16);
7475     int stk_offset = -(1<<scale1);
7476     if (int_cnt2 < 0) { // not constant
7477       push(cnt2);
7478       stk_offset += wordSize;
7479     }
7480     movl(cnt2, cnt1);
7481 
7482     bind(COPY_STR);
7483     if (ae == StrIntrinsicNode::LL) {
7484       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7485       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7486     } else {
7487       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7488       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7489     }
7490     decrement(cnt2);
7491     jccb(Assembler::notZero, COPY_STR);
7492 
7493     if (int_cnt2 < 0) { // not constant
7494       pop(cnt2);
7495     }
7496     movptr(str1, rsp);  // New string address
7497 
7498     bind(BIG_STRINGS);
7499     // Load substring.
7500     if (int_cnt2 < 0) { // -1
7501       if (ae == StrIntrinsicNode::UL) {
7502         pmovzxbw(vec, Address(str2, 0));
7503       } else {
7504         movdqu(vec, Address(str2, 0));
7505       }
7506       push(cnt2);       // substr count
7507       push(str2);       // substr addr
7508       push(str1);       // string addr
7509     } else {
7510       // Small (< 8 chars) constant substrings are loaded already.
7511       movl(cnt2, int_cnt2);
7512     }
7513     push(tmp);  // original SP
7514 
7515   } // Finished loading
7516 
7517   //========================================================
7518   // Start search
7519   //
7520 
7521   movptr(result, str1); // string addr
7522 
7523   if (int_cnt2  < 0) {  // Only for non constant substring
7524     jmpb(SCAN_TO_SUBSTR);
7525 
7526     // SP saved at sp+0
7527     // String saved at sp+1*wordSize
7528     // Substr saved at sp+2*wordSize
7529     // Substr count saved at sp+3*wordSize
7530 
7531     // Reload substr for rescan, this code
7532     // is executed only for large substrings (> 8 chars)
7533     bind(RELOAD_SUBSTR);
7534     movptr(str2, Address(rsp, 2*wordSize));
7535     movl(cnt2, Address(rsp, 3*wordSize));
7536     if (ae == StrIntrinsicNode::UL) {
7537       pmovzxbw(vec, Address(str2, 0));
7538     } else {
7539       movdqu(vec, Address(str2, 0));
7540     }
7541     // We came here after the beginning of the substring was
7542     // matched but the rest of it was not so we need to search
7543     // again. Start from the next element after the previous match.
7544     subptr(str1, result); // Restore counter
7545     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7546       shrl(str1, 1);
7547     }
7548     addl(cnt1, str1);
7549     decrementl(cnt1);   // Shift to next element
7550     cmpl(cnt1, cnt2);
7551     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7552 
7553     addptr(result, (1<<scale1));
7554   } // non constant
7555 
7556   // Scan string for start of substr in 16-byte vectors
7557   bind(SCAN_TO_SUBSTR);
7558   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7559   pcmpestri(vec, Address(result, 0), mode);
7560   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7561   subl(cnt1, stride);
7562   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7563   cmpl(cnt1, cnt2);
7564   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7565   addptr(result, 16);
7566 
7567   bind(ADJUST_STR);
7568   cmpl(cnt1, stride); // Do not read beyond string
7569   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7570   // Back-up string to avoid reading beyond string.
7571   lea(result, Address(result, cnt1, scale1, -16));
7572   movl(cnt1, stride);
7573   jmpb(SCAN_TO_SUBSTR);
7574 
7575   // Found a potential substr
7576   bind(FOUND_CANDIDATE);
7577   // After pcmpestri tmp(rcx) contains matched element index
7578 
7579   // Make sure string is still long enough
7580   subl(cnt1, tmp);
7581   cmpl(cnt1, cnt2);
7582   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7583   // Left less then substring.
7584 
7585   bind(RET_NOT_FOUND);
7586   movl(result, -1);
7587   jmpb(CLEANUP);
7588 
7589   bind(FOUND_SUBSTR);
7590   // Compute start addr of substr
7591   lea(result, Address(result, tmp, scale1));
7592   if (int_cnt2 > 0) { // Constant substring
7593     // Repeat search for small substring (< 8 chars)
7594     // from new point without reloading substring.
7595     // Have to check that we don't read beyond string.
7596     cmpl(tmp, stride-int_cnt2);
7597     jccb(Assembler::greater, ADJUST_STR);
7598     // Fall through if matched whole substring.
7599   } else { // non constant
7600     assert(int_cnt2 == -1, "should be != 0");
7601 
7602     addl(tmp, cnt2);
7603     // Found result if we matched whole substring.
7604     cmpl(tmp, stride);
7605     jccb(Assembler::lessEqual, RET_FOUND);
7606 
7607     // Repeat search for small substring (<= 8 chars)
7608     // from new point 'str1' without reloading substring.
7609     cmpl(cnt2, stride);
7610     // Have to check that we don't read beyond string.
7611     jccb(Assembler::lessEqual, ADJUST_STR);
7612 
7613     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7614     // Compare the rest of substring (> 8 chars).
7615     movptr(str1, result);
7616 
7617     cmpl(tmp, cnt2);
7618     // First 8 chars are already matched.
7619     jccb(Assembler::equal, CHECK_NEXT);
7620 
7621     bind(SCAN_SUBSTR);
7622     pcmpestri(vec, Address(str1, 0), mode);
7623     // Need to reload strings pointers if not matched whole vector
7624     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7625 
7626     bind(CHECK_NEXT);
7627     subl(cnt2, stride);
7628     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7629     addptr(str1, 16);
7630     if (ae == StrIntrinsicNode::UL) {
7631       addptr(str2, 8);
7632     } else {
7633       addptr(str2, 16);
7634     }
7635     subl(cnt1, stride);
7636     cmpl(cnt2, stride); // Do not read beyond substring
7637     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7638     // Back-up strings to avoid reading beyond substring.
7639 
7640     if (ae == StrIntrinsicNode::UL) {
7641       lea(str2, Address(str2, cnt2, scale2, -8));
7642       lea(str1, Address(str1, cnt2, scale1, -16));
7643     } else {
7644       lea(str2, Address(str2, cnt2, scale2, -16));
7645       lea(str1, Address(str1, cnt2, scale1, -16));
7646     }
7647     subl(cnt1, cnt2);
7648     movl(cnt2, stride);
7649     addl(cnt1, stride);
7650     bind(CONT_SCAN_SUBSTR);
7651     if (ae == StrIntrinsicNode::UL) {
7652       pmovzxbw(vec, Address(str2, 0));
7653     } else {
7654       movdqu(vec, Address(str2, 0));
7655     }
7656     jmp(SCAN_SUBSTR);
7657 
7658     bind(RET_FOUND_LONG);
7659     movptr(str1, Address(rsp, wordSize));
7660   } // non constant
7661 
7662   bind(RET_FOUND);
7663   // Compute substr offset
7664   subptr(result, str1);
7665   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7666     shrl(result, 1); // index
7667   }
7668   bind(CLEANUP);
7669   pop(rsp); // restore SP
7670 
7671 } // string_indexof
7672 
7673 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7674                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7675   ShortBranchVerifier sbv(this);
7676   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7677 
7678   int stride = 8;
7679 
7680   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7681         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7682         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7683         FOUND_SEQ_CHAR, DONE_LABEL;
7684 
7685   movptr(result, str1);
7686   if (UseAVX >= 2) {
7687     cmpl(cnt1, stride);
7688     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7689     cmpl(cnt1, 2*stride);
7690     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7691     movdl(vec1, ch);
7692     vpbroadcastw(vec1, vec1);
7693     vpxor(vec2, vec2);
7694     movl(tmp, cnt1);
7695     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7696     andl(cnt1,0x0000000F);  //tail count (in chars)
7697 
7698     bind(SCAN_TO_16_CHAR_LOOP);
7699     vmovdqu(vec3, Address(result, 0));
7700     vpcmpeqw(vec3, vec3, vec1, 1);
7701     vptest(vec2, vec3);
7702     jcc(Assembler::carryClear, FOUND_CHAR);
7703     addptr(result, 32);
7704     subl(tmp, 2*stride);
7705     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7706     jmp(SCAN_TO_8_CHAR);
7707     bind(SCAN_TO_8_CHAR_INIT);
7708     movdl(vec1, ch);
7709     pshuflw(vec1, vec1, 0x00);
7710     pshufd(vec1, vec1, 0);
7711     pxor(vec2, vec2);
7712   }
7713   bind(SCAN_TO_8_CHAR);
7714   cmpl(cnt1, stride);
7715   if (UseAVX >= 2) {
7716     jcc(Assembler::less, SCAN_TO_CHAR);
7717   } else {
7718     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7719     movdl(vec1, ch);
7720     pshuflw(vec1, vec1, 0x00);
7721     pshufd(vec1, vec1, 0);
7722     pxor(vec2, vec2);
7723   }
7724   movl(tmp, cnt1);
7725   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7726   andl(cnt1,0x00000007);  //tail count (in chars)
7727 
7728   bind(SCAN_TO_8_CHAR_LOOP);
7729   movdqu(vec3, Address(result, 0));
7730   pcmpeqw(vec3, vec1);
7731   ptest(vec2, vec3);
7732   jcc(Assembler::carryClear, FOUND_CHAR);
7733   addptr(result, 16);
7734   subl(tmp, stride);
7735   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7736   bind(SCAN_TO_CHAR);
7737   testl(cnt1, cnt1);
7738   jcc(Assembler::zero, RET_NOT_FOUND);
7739   bind(SCAN_TO_CHAR_LOOP);
7740   load_unsigned_short(tmp, Address(result, 0));
7741   cmpl(ch, tmp);
7742   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7743   addptr(result, 2);
7744   subl(cnt1, 1);
7745   jccb(Assembler::zero, RET_NOT_FOUND);
7746   jmp(SCAN_TO_CHAR_LOOP);
7747 
7748   bind(RET_NOT_FOUND);
7749   movl(result, -1);
7750   jmpb(DONE_LABEL);
7751 
7752   bind(FOUND_CHAR);
7753   if (UseAVX >= 2) {
7754     vpmovmskb(tmp, vec3);
7755   } else {
7756     pmovmskb(tmp, vec3);
7757   }
7758   bsfl(ch, tmp);
7759   addl(result, ch);
7760 
7761   bind(FOUND_SEQ_CHAR);
7762   subptr(result, str1);
7763   shrl(result, 1);
7764 
7765   bind(DONE_LABEL);
7766 } // string_indexof_char
7767 
7768 // helper function for string_compare
7769 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7770                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7771                                         Address::ScaleFactor scale2, Register index, int ae) {
7772   if (ae == StrIntrinsicNode::LL) {
7773     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7774     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7775   } else if (ae == StrIntrinsicNode::UU) {
7776     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7777     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7778   } else {
7779     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7780     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7781   }
7782 }
7783 
7784 // Compare strings, used for char[] and byte[].
7785 void MacroAssembler::string_compare(Register str1, Register str2,
7786                                     Register cnt1, Register cnt2, Register result,
7787                                     XMMRegister vec1, int ae) {
7788   ShortBranchVerifier sbv(this);
7789   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7790   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7791   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7792   int stride2x2 = 0x40;
7793   Address::ScaleFactor scale = Address::no_scale;
7794   Address::ScaleFactor scale1 = Address::no_scale;
7795   Address::ScaleFactor scale2 = Address::no_scale;
7796 
7797   if (ae != StrIntrinsicNode::LL) {
7798     stride2x2 = 0x20;
7799   }
7800 
7801   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7802     shrl(cnt2, 1);
7803   }
7804   // Compute the minimum of the string lengths and the
7805   // difference of the string lengths (stack).
7806   // Do the conditional move stuff
7807   movl(result, cnt1);
7808   subl(cnt1, cnt2);
7809   push(cnt1);
7810   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7811 
7812   // Is the minimum length zero?
7813   testl(cnt2, cnt2);
7814   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7815   if (ae == StrIntrinsicNode::LL) {
7816     // Load first bytes
7817     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7818     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7819   } else if (ae == StrIntrinsicNode::UU) {
7820     // Load first characters
7821     load_unsigned_short(result, Address(str1, 0));
7822     load_unsigned_short(cnt1, Address(str2, 0));
7823   } else {
7824     load_unsigned_byte(result, Address(str1, 0));
7825     load_unsigned_short(cnt1, Address(str2, 0));
7826   }
7827   subl(result, cnt1);
7828   jcc(Assembler::notZero,  POP_LABEL);
7829 
7830   if (ae == StrIntrinsicNode::UU) {
7831     // Divide length by 2 to get number of chars
7832     shrl(cnt2, 1);
7833   }
7834   cmpl(cnt2, 1);
7835   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7836 
7837   // Check if the strings start at the same location and setup scale and stride
7838   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7839     cmpptr(str1, str2);
7840     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7841     if (ae == StrIntrinsicNode::LL) {
7842       scale = Address::times_1;
7843       stride = 16;
7844     } else {
7845       scale = Address::times_2;
7846       stride = 8;
7847     }
7848   } else {
7849     scale1 = Address::times_1;
7850     scale2 = Address::times_2;
7851     // scale not used
7852     stride = 8;
7853   }
7854 
7855   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7856     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7857     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7858     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7859     Label COMPARE_TAIL_LONG;
7860     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7861 
7862     int pcmpmask = 0x19;
7863     if (ae == StrIntrinsicNode::LL) {
7864       pcmpmask &= ~0x01;
7865     }
7866 
7867     // Setup to compare 16-chars (32-bytes) vectors,
7868     // start from first character again because it has aligned address.
7869     if (ae == StrIntrinsicNode::LL) {
7870       stride2 = 32;
7871     } else {
7872       stride2 = 16;
7873     }
7874     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7875       adr_stride = stride << scale;
7876     } else {
7877       adr_stride1 = 8;  //stride << scale1;
7878       adr_stride2 = 16; //stride << scale2;
7879     }
7880 
7881     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7882     // rax and rdx are used by pcmpestri as elements counters
7883     movl(result, cnt2);
7884     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7885     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7886 
7887     // fast path : compare first 2 8-char vectors.
7888     bind(COMPARE_16_CHARS);
7889     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7890       movdqu(vec1, Address(str1, 0));
7891     } else {
7892       pmovzxbw(vec1, Address(str1, 0));
7893     }
7894     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7895     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7896 
7897     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7898       movdqu(vec1, Address(str1, adr_stride));
7899       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7900     } else {
7901       pmovzxbw(vec1, Address(str1, adr_stride1));
7902       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7903     }
7904     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7905     addl(cnt1, stride);
7906 
7907     // Compare the characters at index in cnt1
7908     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7909     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7910     subl(result, cnt2);
7911     jmp(POP_LABEL);
7912 
7913     // Setup the registers to start vector comparison loop
7914     bind(COMPARE_WIDE_VECTORS);
7915     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7916       lea(str1, Address(str1, result, scale));
7917       lea(str2, Address(str2, result, scale));
7918     } else {
7919       lea(str1, Address(str1, result, scale1));
7920       lea(str2, Address(str2, result, scale2));
7921     }
7922     subl(result, stride2);
7923     subl(cnt2, stride2);
7924     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7925     negptr(result);
7926 
7927     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7928     bind(COMPARE_WIDE_VECTORS_LOOP);
7929 
7930 #ifdef _LP64
7931     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7932       cmpl(cnt2, stride2x2);
7933       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7934       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7935       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7936 
7937       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7938       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7939         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7940         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7941       } else {
7942         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7943         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7944       }
7945       kortestql(k7, k7);
7946       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7947       addptr(result, stride2x2);  // update since we already compared at this addr
7948       subl(cnt2, stride2x2);      // and sub the size too
7949       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7950 
7951       vpxor(vec1, vec1);
7952       jmpb(COMPARE_WIDE_TAIL);
7953     }//if (VM_Version::supports_avx512vlbw())
7954 #endif // _LP64
7955 
7956 
7957     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7958     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7959       vmovdqu(vec1, Address(str1, result, scale));
7960       vpxor(vec1, Address(str2, result, scale));
7961     } else {
7962       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7963       vpxor(vec1, Address(str2, result, scale2));
7964     }
7965     vptest(vec1, vec1);
7966     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7967     addptr(result, stride2);
7968     subl(cnt2, stride2);
7969     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7970     // clean upper bits of YMM registers
7971     vpxor(vec1, vec1);
7972 
7973     // compare wide vectors tail
7974     bind(COMPARE_WIDE_TAIL);
7975     testptr(result, result);
7976     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7977 
7978     movl(result, stride2);
7979     movl(cnt2, result);
7980     negptr(result);
7981     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7982 
7983     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7984     bind(VECTOR_NOT_EQUAL);
7985     // clean upper bits of YMM registers
7986     vpxor(vec1, vec1);
7987     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7988       lea(str1, Address(str1, result, scale));
7989       lea(str2, Address(str2, result, scale));
7990     } else {
7991       lea(str1, Address(str1, result, scale1));
7992       lea(str2, Address(str2, result, scale2));
7993     }
7994     jmp(COMPARE_16_CHARS);
7995 
7996     // Compare tail chars, length between 1 to 15 chars
7997     bind(COMPARE_TAIL_LONG);
7998     movl(cnt2, result);
7999     cmpl(cnt2, stride);
8000     jcc(Assembler::less, COMPARE_SMALL_STR);
8001 
8002     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8003       movdqu(vec1, Address(str1, 0));
8004     } else {
8005       pmovzxbw(vec1, Address(str1, 0));
8006     }
8007     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8008     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8009     subptr(cnt2, stride);
8010     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8011     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8012       lea(str1, Address(str1, result, scale));
8013       lea(str2, Address(str2, result, scale));
8014     } else {
8015       lea(str1, Address(str1, result, scale1));
8016       lea(str2, Address(str2, result, scale2));
8017     }
8018     negptr(cnt2);
8019     jmpb(WHILE_HEAD_LABEL);
8020 
8021     bind(COMPARE_SMALL_STR);
8022   } else if (UseSSE42Intrinsics) {
8023     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8024     int pcmpmask = 0x19;
8025     // Setup to compare 8-char (16-byte) vectors,
8026     // start from first character again because it has aligned address.
8027     movl(result, cnt2);
8028     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8029     if (ae == StrIntrinsicNode::LL) {
8030       pcmpmask &= ~0x01;
8031     }
8032     jcc(Assembler::zero, COMPARE_TAIL);
8033     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8034       lea(str1, Address(str1, result, scale));
8035       lea(str2, Address(str2, result, scale));
8036     } else {
8037       lea(str1, Address(str1, result, scale1));
8038       lea(str2, Address(str2, result, scale2));
8039     }
8040     negptr(result);
8041 
8042     // pcmpestri
8043     //   inputs:
8044     //     vec1- substring
8045     //     rax - negative string length (elements count)
8046     //     mem - scanned string
8047     //     rdx - string length (elements count)
8048     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8049     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8050     //   outputs:
8051     //     rcx - first mismatched element index
8052     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8053 
8054     bind(COMPARE_WIDE_VECTORS);
8055     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8056       movdqu(vec1, Address(str1, result, scale));
8057       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8058     } else {
8059       pmovzxbw(vec1, Address(str1, result, scale1));
8060       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8061     }
8062     // After pcmpestri cnt1(rcx) contains mismatched element index
8063 
8064     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8065     addptr(result, stride);
8066     subptr(cnt2, stride);
8067     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8068 
8069     // compare wide vectors tail
8070     testptr(result, result);
8071     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8072 
8073     movl(cnt2, stride);
8074     movl(result, stride);
8075     negptr(result);
8076     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8077       movdqu(vec1, Address(str1, result, scale));
8078       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8079     } else {
8080       pmovzxbw(vec1, Address(str1, result, scale1));
8081       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8082     }
8083     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8084 
8085     // Mismatched characters in the vectors
8086     bind(VECTOR_NOT_EQUAL);
8087     addptr(cnt1, result);
8088     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8089     subl(result, cnt2);
8090     jmpb(POP_LABEL);
8091 
8092     bind(COMPARE_TAIL); // limit is zero
8093     movl(cnt2, result);
8094     // Fallthru to tail compare
8095   }
8096   // Shift str2 and str1 to the end of the arrays, negate min
8097   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8098     lea(str1, Address(str1, cnt2, scale));
8099     lea(str2, Address(str2, cnt2, scale));
8100   } else {
8101     lea(str1, Address(str1, cnt2, scale1));
8102     lea(str2, Address(str2, cnt2, scale2));
8103   }
8104   decrementl(cnt2);  // first character was compared already
8105   negptr(cnt2);
8106 
8107   // Compare the rest of the elements
8108   bind(WHILE_HEAD_LABEL);
8109   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8110   subl(result, cnt1);
8111   jccb(Assembler::notZero, POP_LABEL);
8112   increment(cnt2);
8113   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8114 
8115   // Strings are equal up to min length.  Return the length difference.
8116   bind(LENGTH_DIFF_LABEL);
8117   pop(result);
8118   if (ae == StrIntrinsicNode::UU) {
8119     // Divide diff by 2 to get number of chars
8120     sarl(result, 1);
8121   }
8122   jmpb(DONE_LABEL);
8123 
8124 #ifdef _LP64
8125   if (VM_Version::supports_avx512vlbw()) {
8126 
8127     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8128 
8129     kmovql(cnt1, k7);
8130     notq(cnt1);
8131     bsfq(cnt2, cnt1);
8132     if (ae != StrIntrinsicNode::LL) {
8133       // Divide diff by 2 to get number of chars
8134       sarl(cnt2, 1);
8135     }
8136     addq(result, cnt2);
8137     if (ae == StrIntrinsicNode::LL) {
8138       load_unsigned_byte(cnt1, Address(str2, result));
8139       load_unsigned_byte(result, Address(str1, result));
8140     } else if (ae == StrIntrinsicNode::UU) {
8141       load_unsigned_short(cnt1, Address(str2, result, scale));
8142       load_unsigned_short(result, Address(str1, result, scale));
8143     } else {
8144       load_unsigned_short(cnt1, Address(str2, result, scale2));
8145       load_unsigned_byte(result, Address(str1, result, scale1));
8146     }
8147     subl(result, cnt1);
8148     jmpb(POP_LABEL);
8149   }//if (VM_Version::supports_avx512vlbw())
8150 #endif // _LP64
8151 
8152   // Discard the stored length difference
8153   bind(POP_LABEL);
8154   pop(cnt1);
8155 
8156   // That's it
8157   bind(DONE_LABEL);
8158   if(ae == StrIntrinsicNode::UL) {
8159     negl(result);
8160   }
8161 
8162 }
8163 
8164 // Search for Non-ASCII character (Negative byte value) in a byte array,
8165 // return true if it has any and false otherwise.
8166 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
8167 //   @HotSpotIntrinsicCandidate
8168 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
8169 //     for (int i = off; i < off + len; i++) {
8170 //       if (ba[i] < 0) {
8171 //         return true;
8172 //       }
8173 //     }
8174 //     return false;
8175 //   }
8176 void MacroAssembler::has_negatives(Register ary1, Register len,
8177   Register result, Register tmp1,
8178   XMMRegister vec1, XMMRegister vec2) {
8179   // rsi: byte array
8180   // rcx: len
8181   // rax: result
8182   ShortBranchVerifier sbv(this);
8183   assert_different_registers(ary1, len, result, tmp1);
8184   assert_different_registers(vec1, vec2);
8185   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8186 
8187   // len == 0
8188   testl(len, len);
8189   jcc(Assembler::zero, FALSE_LABEL);
8190 
8191   if ((UseAVX > 2) && // AVX512
8192     VM_Version::supports_avx512vlbw() &&
8193     VM_Version::supports_bmi2()) {
8194 
8195     set_vector_masking();  // opening of the stub context for programming mask registers
8196 
8197     Label test_64_loop, test_tail;
8198     Register tmp3_aliased = len;
8199 
8200     movl(tmp1, len);
8201     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
8202 
8203     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
8204     andl(len, ~(64 - 1));    // vector count (in chars)
8205     jccb(Assembler::zero, test_tail);
8206 
8207     lea(ary1, Address(ary1, len, Address::times_1));
8208     negptr(len);
8209 
8210     bind(test_64_loop);
8211     // Check whether our 64 elements of size byte contain negatives
8212     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
8213     kortestql(k2, k2);
8214     jcc(Assembler::notZero, TRUE_LABEL);
8215 
8216     addptr(len, 64);
8217     jccb(Assembler::notZero, test_64_loop);
8218 
8219 
8220     bind(test_tail);
8221     // bail out when there is nothing to be done
8222     testl(tmp1, -1);
8223     jcc(Assembler::zero, FALSE_LABEL);
8224 
8225     // Save k1
8226     kmovql(k3, k1);
8227 
8228     // ~(~0 << len) applied up to two times (for 32-bit scenario)
8229 #ifdef _LP64
8230     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
8231     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
8232     notq(tmp3_aliased);
8233     kmovql(k1, tmp3_aliased);
8234 #else
8235     Label k_init;
8236     jmp(k_init);
8237 
8238     // We could not read 64-bits from a general purpose register thus we move
8239     // data required to compose 64 1's to the instruction stream
8240     // We emit 64 byte wide series of elements from 0..63 which later on would
8241     // be used as a compare targets with tail count contained in tmp1 register.
8242     // Result would be a k1 register having tmp1 consecutive number or 1
8243     // counting from least significant bit.
8244     address tmp = pc();
8245     emit_int64(0x0706050403020100);
8246     emit_int64(0x0F0E0D0C0B0A0908);
8247     emit_int64(0x1716151413121110);
8248     emit_int64(0x1F1E1D1C1B1A1918);
8249     emit_int64(0x2726252423222120);
8250     emit_int64(0x2F2E2D2C2B2A2928);
8251     emit_int64(0x3736353433323130);
8252     emit_int64(0x3F3E3D3C3B3A3938);
8253 
8254     bind(k_init);
8255     lea(len, InternalAddress(tmp));
8256     // create mask to test for negative byte inside a vector
8257     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
8258     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
8259 
8260 #endif
8261     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
8262     ktestq(k2, k1);
8263     // Restore k1
8264     kmovql(k1, k3);
8265     jcc(Assembler::notZero, TRUE_LABEL);
8266 
8267     jmp(FALSE_LABEL);
8268 
8269     clear_vector_masking();   // closing of the stub context for programming mask registers
8270   } else {
8271     movl(result, len); // copy
8272 
8273     if (UseAVX == 2 && UseSSE >= 2) {
8274       // With AVX2, use 32-byte vector compare
8275       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8276 
8277       // Compare 32-byte vectors
8278       andl(result, 0x0000001f);  //   tail count (in bytes)
8279       andl(len, 0xffffffe0);   // vector count (in bytes)
8280       jccb(Assembler::zero, COMPARE_TAIL);
8281 
8282       lea(ary1, Address(ary1, len, Address::times_1));
8283       negptr(len);
8284 
8285       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8286       movdl(vec2, tmp1);
8287       vpbroadcastd(vec2, vec2);
8288 
8289       bind(COMPARE_WIDE_VECTORS);
8290       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8291       vptest(vec1, vec2);
8292       jccb(Assembler::notZero, TRUE_LABEL);
8293       addptr(len, 32);
8294       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8295 
8296       testl(result, result);
8297       jccb(Assembler::zero, FALSE_LABEL);
8298 
8299       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8300       vptest(vec1, vec2);
8301       jccb(Assembler::notZero, TRUE_LABEL);
8302       jmpb(FALSE_LABEL);
8303 
8304       bind(COMPARE_TAIL); // len is zero
8305       movl(len, result);
8306       // Fallthru to tail compare
8307     } else if (UseSSE42Intrinsics) {
8308       // With SSE4.2, use double quad vector compare
8309       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8310 
8311       // Compare 16-byte vectors
8312       andl(result, 0x0000000f);  //   tail count (in bytes)
8313       andl(len, 0xfffffff0);   // vector count (in bytes)
8314       jccb(Assembler::zero, COMPARE_TAIL);
8315 
8316       lea(ary1, Address(ary1, len, Address::times_1));
8317       negptr(len);
8318 
8319       movl(tmp1, 0x80808080);
8320       movdl(vec2, tmp1);
8321       pshufd(vec2, vec2, 0);
8322 
8323       bind(COMPARE_WIDE_VECTORS);
8324       movdqu(vec1, Address(ary1, len, Address::times_1));
8325       ptest(vec1, vec2);
8326       jccb(Assembler::notZero, TRUE_LABEL);
8327       addptr(len, 16);
8328       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8329 
8330       testl(result, result);
8331       jccb(Assembler::zero, FALSE_LABEL);
8332 
8333       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8334       ptest(vec1, vec2);
8335       jccb(Assembler::notZero, TRUE_LABEL);
8336       jmpb(FALSE_LABEL);
8337 
8338       bind(COMPARE_TAIL); // len is zero
8339       movl(len, result);
8340       // Fallthru to tail compare
8341     }
8342   }
8343   // Compare 4-byte vectors
8344   andl(len, 0xfffffffc); // vector count (in bytes)
8345   jccb(Assembler::zero, COMPARE_CHAR);
8346 
8347   lea(ary1, Address(ary1, len, Address::times_1));
8348   negptr(len);
8349 
8350   bind(COMPARE_VECTORS);
8351   movl(tmp1, Address(ary1, len, Address::times_1));
8352   andl(tmp1, 0x80808080);
8353   jccb(Assembler::notZero, TRUE_LABEL);
8354   addptr(len, 4);
8355   jcc(Assembler::notZero, COMPARE_VECTORS);
8356 
8357   // Compare trailing char (final 2 bytes), if any
8358   bind(COMPARE_CHAR);
8359   testl(result, 0x2);   // tail  char
8360   jccb(Assembler::zero, COMPARE_BYTE);
8361   load_unsigned_short(tmp1, Address(ary1, 0));
8362   andl(tmp1, 0x00008080);
8363   jccb(Assembler::notZero, TRUE_LABEL);
8364   subptr(result, 2);
8365   lea(ary1, Address(ary1, 2));
8366 
8367   bind(COMPARE_BYTE);
8368   testl(result, 0x1);   // tail  byte
8369   jccb(Assembler::zero, FALSE_LABEL);
8370   load_unsigned_byte(tmp1, Address(ary1, 0));
8371   andl(tmp1, 0x00000080);
8372   jccb(Assembler::notEqual, TRUE_LABEL);
8373   jmpb(FALSE_LABEL);
8374 
8375   bind(TRUE_LABEL);
8376   movl(result, 1);   // return true
8377   jmpb(DONE);
8378 
8379   bind(FALSE_LABEL);
8380   xorl(result, result); // return false
8381 
8382   // That's it
8383   bind(DONE);
8384   if (UseAVX >= 2 && UseSSE >= 2) {
8385     // clean upper bits of YMM registers
8386     vpxor(vec1, vec1);
8387     vpxor(vec2, vec2);
8388   }
8389 }
8390 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8391 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8392                                    Register limit, Register result, Register chr,
8393                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8394   ShortBranchVerifier sbv(this);
8395   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8396 
8397   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8398   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8399 
8400   if (is_array_equ) {
8401     // Check the input args
8402     cmpptr(ary1, ary2);
8403     jcc(Assembler::equal, TRUE_LABEL);
8404 
8405     // Need additional checks for arrays_equals.
8406     testptr(ary1, ary1);
8407     jcc(Assembler::zero, FALSE_LABEL);
8408     testptr(ary2, ary2);
8409     jcc(Assembler::zero, FALSE_LABEL);
8410 
8411     // Check the lengths
8412     movl(limit, Address(ary1, length_offset));
8413     cmpl(limit, Address(ary2, length_offset));
8414     jcc(Assembler::notEqual, FALSE_LABEL);
8415   }
8416 
8417   // count == 0
8418   testl(limit, limit);
8419   jcc(Assembler::zero, TRUE_LABEL);
8420 
8421   if (is_array_equ) {
8422     // Load array address
8423     lea(ary1, Address(ary1, base_offset));
8424     lea(ary2, Address(ary2, base_offset));
8425   }
8426 
8427   if (is_array_equ && is_char) {
8428     // arrays_equals when used for char[].
8429     shll(limit, 1);      // byte count != 0
8430   }
8431   movl(result, limit); // copy
8432 
8433   if (UseAVX >= 2) {
8434     // With AVX2, use 32-byte vector compare
8435     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8436 
8437     // Compare 32-byte vectors
8438     andl(result, 0x0000001f);  //   tail count (in bytes)
8439     andl(limit, 0xffffffe0);   // vector count (in bytes)
8440     jcc(Assembler::zero, COMPARE_TAIL);
8441 
8442     lea(ary1, Address(ary1, limit, Address::times_1));
8443     lea(ary2, Address(ary2, limit, Address::times_1));
8444     negptr(limit);
8445 
8446     bind(COMPARE_WIDE_VECTORS);
8447 
8448 #ifdef _LP64
8449     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8450       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8451 
8452       cmpl(limit, -64);
8453       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8454 
8455       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8456 
8457       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8458       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8459       kortestql(k7, k7);
8460       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8461       addptr(limit, 64);  // update since we already compared at this addr
8462       cmpl(limit, -64);
8463       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8464 
8465       // At this point we may still need to compare -limit+result bytes.
8466       // We could execute the next two instruction and just continue via non-wide path:
8467       //  cmpl(limit, 0);
8468       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8469       // But since we stopped at the points ary{1,2}+limit which are
8470       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8471       // (|limit| <= 32 and result < 32),
8472       // we may just compare the last 64 bytes.
8473       //
8474       addptr(result, -64);   // it is safe, bc we just came from this area
8475       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8476       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8477       kortestql(k7, k7);
8478       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8479 
8480       jmp(TRUE_LABEL);
8481 
8482       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8483 
8484     }//if (VM_Version::supports_avx512vlbw())
8485 #endif //_LP64
8486 
8487     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8488     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8489     vpxor(vec1, vec2);
8490 
8491     vptest(vec1, vec1);
8492     jcc(Assembler::notZero, FALSE_LABEL);
8493     addptr(limit, 32);
8494     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8495 
8496     testl(result, result);
8497     jcc(Assembler::zero, TRUE_LABEL);
8498 
8499     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8500     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8501     vpxor(vec1, vec2);
8502 
8503     vptest(vec1, vec1);
8504     jccb(Assembler::notZero, FALSE_LABEL);
8505     jmpb(TRUE_LABEL);
8506 
8507     bind(COMPARE_TAIL); // limit is zero
8508     movl(limit, result);
8509     // Fallthru to tail compare
8510   } else if (UseSSE42Intrinsics) {
8511     // With SSE4.2, use double quad vector compare
8512     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8513 
8514     // Compare 16-byte vectors
8515     andl(result, 0x0000000f);  //   tail count (in bytes)
8516     andl(limit, 0xfffffff0);   // vector count (in bytes)
8517     jcc(Assembler::zero, COMPARE_TAIL);
8518 
8519     lea(ary1, Address(ary1, limit, Address::times_1));
8520     lea(ary2, Address(ary2, limit, Address::times_1));
8521     negptr(limit);
8522 
8523     bind(COMPARE_WIDE_VECTORS);
8524     movdqu(vec1, Address(ary1, limit, Address::times_1));
8525     movdqu(vec2, Address(ary2, limit, Address::times_1));
8526     pxor(vec1, vec2);
8527 
8528     ptest(vec1, vec1);
8529     jcc(Assembler::notZero, FALSE_LABEL);
8530     addptr(limit, 16);
8531     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8532 
8533     testl(result, result);
8534     jcc(Assembler::zero, TRUE_LABEL);
8535 
8536     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8537     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8538     pxor(vec1, vec2);
8539 
8540     ptest(vec1, vec1);
8541     jccb(Assembler::notZero, FALSE_LABEL);
8542     jmpb(TRUE_LABEL);
8543 
8544     bind(COMPARE_TAIL); // limit is zero
8545     movl(limit, result);
8546     // Fallthru to tail compare
8547   }
8548 
8549   // Compare 4-byte vectors
8550   andl(limit, 0xfffffffc); // vector count (in bytes)
8551   jccb(Assembler::zero, COMPARE_CHAR);
8552 
8553   lea(ary1, Address(ary1, limit, Address::times_1));
8554   lea(ary2, Address(ary2, limit, Address::times_1));
8555   negptr(limit);
8556 
8557   bind(COMPARE_VECTORS);
8558   movl(chr, Address(ary1, limit, Address::times_1));
8559   cmpl(chr, Address(ary2, limit, Address::times_1));
8560   jccb(Assembler::notEqual, FALSE_LABEL);
8561   addptr(limit, 4);
8562   jcc(Assembler::notZero, COMPARE_VECTORS);
8563 
8564   // Compare trailing char (final 2 bytes), if any
8565   bind(COMPARE_CHAR);
8566   testl(result, 0x2);   // tail  char
8567   jccb(Assembler::zero, COMPARE_BYTE);
8568   load_unsigned_short(chr, Address(ary1, 0));
8569   load_unsigned_short(limit, Address(ary2, 0));
8570   cmpl(chr, limit);
8571   jccb(Assembler::notEqual, FALSE_LABEL);
8572 
8573   if (is_array_equ && is_char) {
8574     bind(COMPARE_BYTE);
8575   } else {
8576     lea(ary1, Address(ary1, 2));
8577     lea(ary2, Address(ary2, 2));
8578 
8579     bind(COMPARE_BYTE);
8580     testl(result, 0x1);   // tail  byte
8581     jccb(Assembler::zero, TRUE_LABEL);
8582     load_unsigned_byte(chr, Address(ary1, 0));
8583     load_unsigned_byte(limit, Address(ary2, 0));
8584     cmpl(chr, limit);
8585     jccb(Assembler::notEqual, FALSE_LABEL);
8586   }
8587   bind(TRUE_LABEL);
8588   movl(result, 1);   // return true
8589   jmpb(DONE);
8590 
8591   bind(FALSE_LABEL);
8592   xorl(result, result); // return false
8593 
8594   // That's it
8595   bind(DONE);
8596   if (UseAVX >= 2) {
8597     // clean upper bits of YMM registers
8598     vpxor(vec1, vec1);
8599     vpxor(vec2, vec2);
8600   }
8601 }
8602 
8603 #endif
8604 
8605 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8606                                    Register to, Register value, Register count,
8607                                    Register rtmp, XMMRegister xtmp) {
8608   ShortBranchVerifier sbv(this);
8609   assert_different_registers(to, value, count, rtmp);
8610   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8611   Label L_fill_2_bytes, L_fill_4_bytes;
8612 
8613   int shift = -1;
8614   switch (t) {
8615     case T_BYTE:
8616       shift = 2;
8617       break;
8618     case T_SHORT:
8619       shift = 1;
8620       break;
8621     case T_INT:
8622       shift = 0;
8623       break;
8624     default: ShouldNotReachHere();
8625   }
8626 
8627   if (t == T_BYTE) {
8628     andl(value, 0xff);
8629     movl(rtmp, value);
8630     shll(rtmp, 8);
8631     orl(value, rtmp);
8632   }
8633   if (t == T_SHORT) {
8634     andl(value, 0xffff);
8635   }
8636   if (t == T_BYTE || t == T_SHORT) {
8637     movl(rtmp, value);
8638     shll(rtmp, 16);
8639     orl(value, rtmp);
8640   }
8641 
8642   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8643   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8644   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8645     // align source address at 4 bytes address boundary
8646     if (t == T_BYTE) {
8647       // One byte misalignment happens only for byte arrays
8648       testptr(to, 1);
8649       jccb(Assembler::zero, L_skip_align1);
8650       movb(Address(to, 0), value);
8651       increment(to);
8652       decrement(count);
8653       BIND(L_skip_align1);
8654     }
8655     // Two bytes misalignment happens only for byte and short (char) arrays
8656     testptr(to, 2);
8657     jccb(Assembler::zero, L_skip_align2);
8658     movw(Address(to, 0), value);
8659     addptr(to, 2);
8660     subl(count, 1<<(shift-1));
8661     BIND(L_skip_align2);
8662   }
8663   if (UseSSE < 2) {
8664     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8665     // Fill 32-byte chunks
8666     subl(count, 8 << shift);
8667     jcc(Assembler::less, L_check_fill_8_bytes);
8668     align(16);
8669 
8670     BIND(L_fill_32_bytes_loop);
8671 
8672     for (int i = 0; i < 32; i += 4) {
8673       movl(Address(to, i), value);
8674     }
8675 
8676     addptr(to, 32);
8677     subl(count, 8 << shift);
8678     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8679     BIND(L_check_fill_8_bytes);
8680     addl(count, 8 << shift);
8681     jccb(Assembler::zero, L_exit);
8682     jmpb(L_fill_8_bytes);
8683 
8684     //
8685     // length is too short, just fill qwords
8686     //
8687     BIND(L_fill_8_bytes_loop);
8688     movl(Address(to, 0), value);
8689     movl(Address(to, 4), value);
8690     addptr(to, 8);
8691     BIND(L_fill_8_bytes);
8692     subl(count, 1 << (shift + 1));
8693     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8694     // fall through to fill 4 bytes
8695   } else {
8696     Label L_fill_32_bytes;
8697     if (!UseUnalignedLoadStores) {
8698       // align to 8 bytes, we know we are 4 byte aligned to start
8699       testptr(to, 4);
8700       jccb(Assembler::zero, L_fill_32_bytes);
8701       movl(Address(to, 0), value);
8702       addptr(to, 4);
8703       subl(count, 1<<shift);
8704     }
8705     BIND(L_fill_32_bytes);
8706     {
8707       assert( UseSSE >= 2, "supported cpu only" );
8708       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8709       if (UseAVX > 2) {
8710         movl(rtmp, 0xffff);
8711         kmovwl(k1, rtmp);
8712       }
8713       movdl(xtmp, value);
8714       if (UseAVX > 2 && UseUnalignedLoadStores) {
8715         // Fill 64-byte chunks
8716         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8717         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8718 
8719         subl(count, 16 << shift);
8720         jcc(Assembler::less, L_check_fill_32_bytes);
8721         align(16);
8722 
8723         BIND(L_fill_64_bytes_loop);
8724         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8725         addptr(to, 64);
8726         subl(count, 16 << shift);
8727         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8728 
8729         BIND(L_check_fill_32_bytes);
8730         addl(count, 8 << shift);
8731         jccb(Assembler::less, L_check_fill_8_bytes);
8732         vmovdqu(Address(to, 0), xtmp);
8733         addptr(to, 32);
8734         subl(count, 8 << shift);
8735 
8736         BIND(L_check_fill_8_bytes);
8737       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8738         // Fill 64-byte chunks
8739         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8740         vpbroadcastd(xtmp, xtmp);
8741 
8742         subl(count, 16 << shift);
8743         jcc(Assembler::less, L_check_fill_32_bytes);
8744         align(16);
8745 
8746         BIND(L_fill_64_bytes_loop);
8747         vmovdqu(Address(to, 0), xtmp);
8748         vmovdqu(Address(to, 32), xtmp);
8749         addptr(to, 64);
8750         subl(count, 16 << shift);
8751         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8752 
8753         BIND(L_check_fill_32_bytes);
8754         addl(count, 8 << shift);
8755         jccb(Assembler::less, L_check_fill_8_bytes);
8756         vmovdqu(Address(to, 0), xtmp);
8757         addptr(to, 32);
8758         subl(count, 8 << shift);
8759 
8760         BIND(L_check_fill_8_bytes);
8761         // clean upper bits of YMM registers
8762         movdl(xtmp, value);
8763         pshufd(xtmp, xtmp, 0);
8764       } else {
8765         // Fill 32-byte chunks
8766         pshufd(xtmp, xtmp, 0);
8767 
8768         subl(count, 8 << shift);
8769         jcc(Assembler::less, L_check_fill_8_bytes);
8770         align(16);
8771 
8772         BIND(L_fill_32_bytes_loop);
8773 
8774         if (UseUnalignedLoadStores) {
8775           movdqu(Address(to, 0), xtmp);
8776           movdqu(Address(to, 16), xtmp);
8777         } else {
8778           movq(Address(to, 0), xtmp);
8779           movq(Address(to, 8), xtmp);
8780           movq(Address(to, 16), xtmp);
8781           movq(Address(to, 24), xtmp);
8782         }
8783 
8784         addptr(to, 32);
8785         subl(count, 8 << shift);
8786         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8787 
8788         BIND(L_check_fill_8_bytes);
8789       }
8790       addl(count, 8 << shift);
8791       jccb(Assembler::zero, L_exit);
8792       jmpb(L_fill_8_bytes);
8793 
8794       //
8795       // length is too short, just fill qwords
8796       //
8797       BIND(L_fill_8_bytes_loop);
8798       movq(Address(to, 0), xtmp);
8799       addptr(to, 8);
8800       BIND(L_fill_8_bytes);
8801       subl(count, 1 << (shift + 1));
8802       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8803     }
8804   }
8805   // fill trailing 4 bytes
8806   BIND(L_fill_4_bytes);
8807   testl(count, 1<<shift);
8808   jccb(Assembler::zero, L_fill_2_bytes);
8809   movl(Address(to, 0), value);
8810   if (t == T_BYTE || t == T_SHORT) {
8811     addptr(to, 4);
8812     BIND(L_fill_2_bytes);
8813     // fill trailing 2 bytes
8814     testl(count, 1<<(shift-1));
8815     jccb(Assembler::zero, L_fill_byte);
8816     movw(Address(to, 0), value);
8817     if (t == T_BYTE) {
8818       addptr(to, 2);
8819       BIND(L_fill_byte);
8820       // fill trailing byte
8821       testl(count, 1);
8822       jccb(Assembler::zero, L_exit);
8823       movb(Address(to, 0), value);
8824     } else {
8825       BIND(L_fill_byte);
8826     }
8827   } else {
8828     BIND(L_fill_2_bytes);
8829   }
8830   BIND(L_exit);
8831 }
8832 
8833 // encode char[] to byte[] in ISO_8859_1
8834    //@HotSpotIntrinsicCandidate
8835    //private static int implEncodeISOArray(byte[] sa, int sp,
8836    //byte[] da, int dp, int len) {
8837    //  int i = 0;
8838    //  for (; i < len; i++) {
8839    //    char c = StringUTF16.getChar(sa, sp++);
8840    //    if (c > '\u00FF')
8841    //      break;
8842    //    da[dp++] = (byte)c;
8843    //  }
8844    //  return i;
8845    //}
8846 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8847   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8848   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8849   Register tmp5, Register result) {
8850 
8851   // rsi: src
8852   // rdi: dst
8853   // rdx: len
8854   // rcx: tmp5
8855   // rax: result
8856   ShortBranchVerifier sbv(this);
8857   assert_different_registers(src, dst, len, tmp5, result);
8858   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8859 
8860   // set result
8861   xorl(result, result);
8862   // check for zero length
8863   testl(len, len);
8864   jcc(Assembler::zero, L_done);
8865 
8866   movl(result, len);
8867 
8868   // Setup pointers
8869   lea(src, Address(src, len, Address::times_2)); // char[]
8870   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8871   negptr(len);
8872 
8873   if (UseSSE42Intrinsics || UseAVX >= 2) {
8874     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8875     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8876 
8877     if (UseAVX >= 2) {
8878       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8879       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8880       movdl(tmp1Reg, tmp5);
8881       vpbroadcastd(tmp1Reg, tmp1Reg);
8882       jmp(L_chars_32_check);
8883 
8884       bind(L_copy_32_chars);
8885       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8886       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8887       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8888       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8889       jccb(Assembler::notZero, L_copy_32_chars_exit);
8890       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8891       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8892       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8893 
8894       bind(L_chars_32_check);
8895       addptr(len, 32);
8896       jcc(Assembler::lessEqual, L_copy_32_chars);
8897 
8898       bind(L_copy_32_chars_exit);
8899       subptr(len, 16);
8900       jccb(Assembler::greater, L_copy_16_chars_exit);
8901 
8902     } else if (UseSSE42Intrinsics) {
8903       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8904       movdl(tmp1Reg, tmp5);
8905       pshufd(tmp1Reg, tmp1Reg, 0);
8906       jmpb(L_chars_16_check);
8907     }
8908 
8909     bind(L_copy_16_chars);
8910     if (UseAVX >= 2) {
8911       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8912       vptest(tmp2Reg, tmp1Reg);
8913       jcc(Assembler::notZero, L_copy_16_chars_exit);
8914       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8915       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8916     } else {
8917       if (UseAVX > 0) {
8918         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8919         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8920         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8921       } else {
8922         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8923         por(tmp2Reg, tmp3Reg);
8924         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8925         por(tmp2Reg, tmp4Reg);
8926       }
8927       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8928       jccb(Assembler::notZero, L_copy_16_chars_exit);
8929       packuswb(tmp3Reg, tmp4Reg);
8930     }
8931     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8932 
8933     bind(L_chars_16_check);
8934     addptr(len, 16);
8935     jcc(Assembler::lessEqual, L_copy_16_chars);
8936 
8937     bind(L_copy_16_chars_exit);
8938     if (UseAVX >= 2) {
8939       // clean upper bits of YMM registers
8940       vpxor(tmp2Reg, tmp2Reg);
8941       vpxor(tmp3Reg, tmp3Reg);
8942       vpxor(tmp4Reg, tmp4Reg);
8943       movdl(tmp1Reg, tmp5);
8944       pshufd(tmp1Reg, tmp1Reg, 0);
8945     }
8946     subptr(len, 8);
8947     jccb(Assembler::greater, L_copy_8_chars_exit);
8948 
8949     bind(L_copy_8_chars);
8950     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8951     ptest(tmp3Reg, tmp1Reg);
8952     jccb(Assembler::notZero, L_copy_8_chars_exit);
8953     packuswb(tmp3Reg, tmp1Reg);
8954     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8955     addptr(len, 8);
8956     jccb(Assembler::lessEqual, L_copy_8_chars);
8957 
8958     bind(L_copy_8_chars_exit);
8959     subptr(len, 8);
8960     jccb(Assembler::zero, L_done);
8961   }
8962 
8963   bind(L_copy_1_char);
8964   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8965   testl(tmp5, 0xff00);      // check if Unicode char
8966   jccb(Assembler::notZero, L_copy_1_char_exit);
8967   movb(Address(dst, len, Address::times_1, 0), tmp5);
8968   addptr(len, 1);
8969   jccb(Assembler::less, L_copy_1_char);
8970 
8971   bind(L_copy_1_char_exit);
8972   addptr(result, len); // len is negative count of not processed elements
8973 
8974   bind(L_done);
8975 }
8976 
8977 #ifdef _LP64
8978 /**
8979  * Helper for multiply_to_len().
8980  */
8981 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8982   addq(dest_lo, src1);
8983   adcq(dest_hi, 0);
8984   addq(dest_lo, src2);
8985   adcq(dest_hi, 0);
8986 }
8987 
8988 /**
8989  * Multiply 64 bit by 64 bit first loop.
8990  */
8991 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8992                                            Register y, Register y_idx, Register z,
8993                                            Register carry, Register product,
8994                                            Register idx, Register kdx) {
8995   //
8996   //  jlong carry, x[], y[], z[];
8997   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8998   //    huge_128 product = y[idx] * x[xstart] + carry;
8999   //    z[kdx] = (jlong)product;
9000   //    carry  = (jlong)(product >>> 64);
9001   //  }
9002   //  z[xstart] = carry;
9003   //
9004 
9005   Label L_first_loop, L_first_loop_exit;
9006   Label L_one_x, L_one_y, L_multiply;
9007 
9008   decrementl(xstart);
9009   jcc(Assembler::negative, L_one_x);
9010 
9011   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9012   rorq(x_xstart, 32); // convert big-endian to little-endian
9013 
9014   bind(L_first_loop);
9015   decrementl(idx);
9016   jcc(Assembler::negative, L_first_loop_exit);
9017   decrementl(idx);
9018   jcc(Assembler::negative, L_one_y);
9019   movq(y_idx, Address(y, idx, Address::times_4,  0));
9020   rorq(y_idx, 32); // convert big-endian to little-endian
9021   bind(L_multiply);
9022   movq(product, x_xstart);
9023   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9024   addq(product, carry);
9025   adcq(rdx, 0);
9026   subl(kdx, 2);
9027   movl(Address(z, kdx, Address::times_4,  4), product);
9028   shrq(product, 32);
9029   movl(Address(z, kdx, Address::times_4,  0), product);
9030   movq(carry, rdx);
9031   jmp(L_first_loop);
9032 
9033   bind(L_one_y);
9034   movl(y_idx, Address(y,  0));
9035   jmp(L_multiply);
9036 
9037   bind(L_one_x);
9038   movl(x_xstart, Address(x,  0));
9039   jmp(L_first_loop);
9040 
9041   bind(L_first_loop_exit);
9042 }
9043 
9044 /**
9045  * Multiply 64 bit by 64 bit and add 128 bit.
9046  */
9047 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9048                                             Register yz_idx, Register idx,
9049                                             Register carry, Register product, int offset) {
9050   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9051   //     z[kdx] = (jlong)product;
9052 
9053   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9054   rorq(yz_idx, 32); // convert big-endian to little-endian
9055   movq(product, x_xstart);
9056   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9057   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9058   rorq(yz_idx, 32); // convert big-endian to little-endian
9059 
9060   add2_with_carry(rdx, product, carry, yz_idx);
9061 
9062   movl(Address(z, idx, Address::times_4,  offset+4), product);
9063   shrq(product, 32);
9064   movl(Address(z, idx, Address::times_4,  offset), product);
9065 
9066 }
9067 
9068 /**
9069  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9070  */
9071 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9072                                              Register yz_idx, Register idx, Register jdx,
9073                                              Register carry, Register product,
9074                                              Register carry2) {
9075   //   jlong carry, x[], y[], z[];
9076   //   int kdx = ystart+1;
9077   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9078   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9079   //     z[kdx+idx+1] = (jlong)product;
9080   //     jlong carry2  = (jlong)(product >>> 64);
9081   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9082   //     z[kdx+idx] = (jlong)product;
9083   //     carry  = (jlong)(product >>> 64);
9084   //   }
9085   //   idx += 2;
9086   //   if (idx > 0) {
9087   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9088   //     z[kdx+idx] = (jlong)product;
9089   //     carry  = (jlong)(product >>> 64);
9090   //   }
9091   //
9092 
9093   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9094 
9095   movl(jdx, idx);
9096   andl(jdx, 0xFFFFFFFC);
9097   shrl(jdx, 2);
9098 
9099   bind(L_third_loop);
9100   subl(jdx, 1);
9101   jcc(Assembler::negative, L_third_loop_exit);
9102   subl(idx, 4);
9103 
9104   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9105   movq(carry2, rdx);
9106 
9107   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9108   movq(carry, rdx);
9109   jmp(L_third_loop);
9110 
9111   bind (L_third_loop_exit);
9112 
9113   andl (idx, 0x3);
9114   jcc(Assembler::zero, L_post_third_loop_done);
9115 
9116   Label L_check_1;
9117   subl(idx, 2);
9118   jcc(Assembler::negative, L_check_1);
9119 
9120   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9121   movq(carry, rdx);
9122 
9123   bind (L_check_1);
9124   addl (idx, 0x2);
9125   andl (idx, 0x1);
9126   subl(idx, 1);
9127   jcc(Assembler::negative, L_post_third_loop_done);
9128 
9129   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9130   movq(product, x_xstart);
9131   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9132   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9133 
9134   add2_with_carry(rdx, product, yz_idx, carry);
9135 
9136   movl(Address(z, idx, Address::times_4,  0), product);
9137   shrq(product, 32);
9138 
9139   shlq(rdx, 32);
9140   orq(product, rdx);
9141   movq(carry, product);
9142 
9143   bind(L_post_third_loop_done);
9144 }
9145 
9146 /**
9147  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9148  *
9149  */
9150 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9151                                                   Register carry, Register carry2,
9152                                                   Register idx, Register jdx,
9153                                                   Register yz_idx1, Register yz_idx2,
9154                                                   Register tmp, Register tmp3, Register tmp4) {
9155   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9156 
9157   //   jlong carry, x[], y[], z[];
9158   //   int kdx = ystart+1;
9159   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9160   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9161   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9162   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9163   //     carry  = (jlong)(tmp4 >>> 64);
9164   //     z[kdx+idx+1] = (jlong)tmp3;
9165   //     z[kdx+idx] = (jlong)tmp4;
9166   //   }
9167   //   idx += 2;
9168   //   if (idx > 0) {
9169   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9170   //     z[kdx+idx] = (jlong)yz_idx1;
9171   //     carry  = (jlong)(yz_idx1 >>> 64);
9172   //   }
9173   //
9174 
9175   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9176 
9177   movl(jdx, idx);
9178   andl(jdx, 0xFFFFFFFC);
9179   shrl(jdx, 2);
9180 
9181   bind(L_third_loop);
9182   subl(jdx, 1);
9183   jcc(Assembler::negative, L_third_loop_exit);
9184   subl(idx, 4);
9185 
9186   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9187   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9188   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9189   rorxq(yz_idx2, yz_idx2, 32);
9190 
9191   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9192   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9193 
9194   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9195   rorxq(yz_idx1, yz_idx1, 32);
9196   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9197   rorxq(yz_idx2, yz_idx2, 32);
9198 
9199   if (VM_Version::supports_adx()) {
9200     adcxq(tmp3, carry);
9201     adoxq(tmp3, yz_idx1);
9202 
9203     adcxq(tmp4, tmp);
9204     adoxq(tmp4, yz_idx2);
9205 
9206     movl(carry, 0); // does not affect flags
9207     adcxq(carry2, carry);
9208     adoxq(carry2, carry);
9209   } else {
9210     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9211     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9212   }
9213   movq(carry, carry2);
9214 
9215   movl(Address(z, idx, Address::times_4, 12), tmp3);
9216   shrq(tmp3, 32);
9217   movl(Address(z, idx, Address::times_4,  8), tmp3);
9218 
9219   movl(Address(z, idx, Address::times_4,  4), tmp4);
9220   shrq(tmp4, 32);
9221   movl(Address(z, idx, Address::times_4,  0), tmp4);
9222 
9223   jmp(L_third_loop);
9224 
9225   bind (L_third_loop_exit);
9226 
9227   andl (idx, 0x3);
9228   jcc(Assembler::zero, L_post_third_loop_done);
9229 
9230   Label L_check_1;
9231   subl(idx, 2);
9232   jcc(Assembler::negative, L_check_1);
9233 
9234   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9235   rorxq(yz_idx1, yz_idx1, 32);
9236   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9237   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9238   rorxq(yz_idx2, yz_idx2, 32);
9239 
9240   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9241 
9242   movl(Address(z, idx, Address::times_4,  4), tmp3);
9243   shrq(tmp3, 32);
9244   movl(Address(z, idx, Address::times_4,  0), tmp3);
9245   movq(carry, tmp4);
9246 
9247   bind (L_check_1);
9248   addl (idx, 0x2);
9249   andl (idx, 0x1);
9250   subl(idx, 1);
9251   jcc(Assembler::negative, L_post_third_loop_done);
9252   movl(tmp4, Address(y, idx, Address::times_4,  0));
9253   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9254   movl(tmp4, Address(z, idx, Address::times_4,  0));
9255 
9256   add2_with_carry(carry2, tmp3, tmp4, carry);
9257 
9258   movl(Address(z, idx, Address::times_4,  0), tmp3);
9259   shrq(tmp3, 32);
9260 
9261   shlq(carry2, 32);
9262   orq(tmp3, carry2);
9263   movq(carry, tmp3);
9264 
9265   bind(L_post_third_loop_done);
9266 }
9267 
9268 /**
9269  * Code for BigInteger::multiplyToLen() instrinsic.
9270  *
9271  * rdi: x
9272  * rax: xlen
9273  * rsi: y
9274  * rcx: ylen
9275  * r8:  z
9276  * r11: zlen
9277  * r12: tmp1
9278  * r13: tmp2
9279  * r14: tmp3
9280  * r15: tmp4
9281  * rbx: tmp5
9282  *
9283  */
9284 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9285                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9286   ShortBranchVerifier sbv(this);
9287   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9288 
9289   push(tmp1);
9290   push(tmp2);
9291   push(tmp3);
9292   push(tmp4);
9293   push(tmp5);
9294 
9295   push(xlen);
9296   push(zlen);
9297 
9298   const Register idx = tmp1;
9299   const Register kdx = tmp2;
9300   const Register xstart = tmp3;
9301 
9302   const Register y_idx = tmp4;
9303   const Register carry = tmp5;
9304   const Register product  = xlen;
9305   const Register x_xstart = zlen;  // reuse register
9306 
9307   // First Loop.
9308   //
9309   //  final static long LONG_MASK = 0xffffffffL;
9310   //  int xstart = xlen - 1;
9311   //  int ystart = ylen - 1;
9312   //  long carry = 0;
9313   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9314   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9315   //    z[kdx] = (int)product;
9316   //    carry = product >>> 32;
9317   //  }
9318   //  z[xstart] = (int)carry;
9319   //
9320 
9321   movl(idx, ylen);      // idx = ylen;
9322   movl(kdx, zlen);      // kdx = xlen+ylen;
9323   xorq(carry, carry);   // carry = 0;
9324 
9325   Label L_done;
9326 
9327   movl(xstart, xlen);
9328   decrementl(xstart);
9329   jcc(Assembler::negative, L_done);
9330 
9331   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9332 
9333   Label L_second_loop;
9334   testl(kdx, kdx);
9335   jcc(Assembler::zero, L_second_loop);
9336 
9337   Label L_carry;
9338   subl(kdx, 1);
9339   jcc(Assembler::zero, L_carry);
9340 
9341   movl(Address(z, kdx, Address::times_4,  0), carry);
9342   shrq(carry, 32);
9343   subl(kdx, 1);
9344 
9345   bind(L_carry);
9346   movl(Address(z, kdx, Address::times_4,  0), carry);
9347 
9348   // Second and third (nested) loops.
9349   //
9350   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9351   //   carry = 0;
9352   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9353   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9354   //                    (z[k] & LONG_MASK) + carry;
9355   //     z[k] = (int)product;
9356   //     carry = product >>> 32;
9357   //   }
9358   //   z[i] = (int)carry;
9359   // }
9360   //
9361   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9362 
9363   const Register jdx = tmp1;
9364 
9365   bind(L_second_loop);
9366   xorl(carry, carry);    // carry = 0;
9367   movl(jdx, ylen);       // j = ystart+1
9368 
9369   subl(xstart, 1);       // i = xstart-1;
9370   jcc(Assembler::negative, L_done);
9371 
9372   push (z);
9373 
9374   Label L_last_x;
9375   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9376   subl(xstart, 1);       // i = xstart-1;
9377   jcc(Assembler::negative, L_last_x);
9378 
9379   if (UseBMI2Instructions) {
9380     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9381     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9382   } else {
9383     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9384     rorq(x_xstart, 32);  // convert big-endian to little-endian
9385   }
9386 
9387   Label L_third_loop_prologue;
9388   bind(L_third_loop_prologue);
9389 
9390   push (x);
9391   push (xstart);
9392   push (ylen);
9393 
9394 
9395   if (UseBMI2Instructions) {
9396     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9397   } else { // !UseBMI2Instructions
9398     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9399   }
9400 
9401   pop(ylen);
9402   pop(xlen);
9403   pop(x);
9404   pop(z);
9405 
9406   movl(tmp3, xlen);
9407   addl(tmp3, 1);
9408   movl(Address(z, tmp3, Address::times_4,  0), carry);
9409   subl(tmp3, 1);
9410   jccb(Assembler::negative, L_done);
9411 
9412   shrq(carry, 32);
9413   movl(Address(z, tmp3, Address::times_4,  0), carry);
9414   jmp(L_second_loop);
9415 
9416   // Next infrequent code is moved outside loops.
9417   bind(L_last_x);
9418   if (UseBMI2Instructions) {
9419     movl(rdx, Address(x,  0));
9420   } else {
9421     movl(x_xstart, Address(x,  0));
9422   }
9423   jmp(L_third_loop_prologue);
9424 
9425   bind(L_done);
9426 
9427   pop(zlen);
9428   pop(xlen);
9429 
9430   pop(tmp5);
9431   pop(tmp4);
9432   pop(tmp3);
9433   pop(tmp2);
9434   pop(tmp1);
9435 }
9436 
9437 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9438   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9439   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9440   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9441   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9442   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9443   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9444   Label SAME_TILL_END, DONE;
9445   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9446 
9447   //scale is in rcx in both Win64 and Unix
9448   ShortBranchVerifier sbv(this);
9449 
9450   shlq(length);
9451   xorq(result, result);
9452 
9453   if ((UseAVX > 2) &&
9454       VM_Version::supports_avx512vlbw()) {
9455     set_vector_masking();  // opening of the stub context for programming mask registers
9456     cmpq(length, 64);
9457     jcc(Assembler::less, VECTOR32_TAIL);
9458     movq(tmp1, length);
9459     andq(tmp1, 0x3F);      // tail count
9460     andq(length, ~(0x3F)); //vector count
9461 
9462     bind(VECTOR64_LOOP);
9463     // AVX512 code to compare 64 byte vectors.
9464     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9465     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9466     kortestql(k7, k7);
9467     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9468     addq(result, 64);
9469     subq(length, 64);
9470     jccb(Assembler::notZero, VECTOR64_LOOP);
9471 
9472     //bind(VECTOR64_TAIL);
9473     testq(tmp1, tmp1);
9474     jcc(Assembler::zero, SAME_TILL_END);
9475 
9476     bind(VECTOR64_TAIL);
9477     // AVX512 code to compare upto 63 byte vectors.
9478     // Save k1
9479     kmovql(k3, k1);
9480     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9481     shlxq(tmp2, tmp2, tmp1);
9482     notq(tmp2);
9483     kmovql(k1, tmp2);
9484 
9485     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9486     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9487 
9488     ktestql(k7, k1);
9489     // Restore k1
9490     kmovql(k1, k3);
9491     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9492 
9493     bind(VECTOR64_NOT_EQUAL);
9494     kmovql(tmp1, k7);
9495     notq(tmp1);
9496     tzcntq(tmp1, tmp1);
9497     addq(result, tmp1);
9498     shrq(result);
9499     jmp(DONE);
9500     bind(VECTOR32_TAIL);
9501     clear_vector_masking();   // closing of the stub context for programming mask registers
9502   }
9503 
9504   cmpq(length, 8);
9505   jcc(Assembler::equal, VECTOR8_LOOP);
9506   jcc(Assembler::less, VECTOR4_TAIL);
9507 
9508   if (UseAVX >= 2) {
9509 
9510     cmpq(length, 16);
9511     jcc(Assembler::equal, VECTOR16_LOOP);
9512     jcc(Assembler::less, VECTOR8_LOOP);
9513 
9514     cmpq(length, 32);
9515     jccb(Assembler::less, VECTOR16_TAIL);
9516 
9517     subq(length, 32);
9518     bind(VECTOR32_LOOP);
9519     vmovdqu(rymm0, Address(obja, result));
9520     vmovdqu(rymm1, Address(objb, result));
9521     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9522     vptest(rymm2, rymm2);
9523     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9524     addq(result, 32);
9525     subq(length, 32);
9526     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9527     addq(length, 32);
9528     jcc(Assembler::equal, SAME_TILL_END);
9529     //falling through if less than 32 bytes left //close the branch here.
9530 
9531     bind(VECTOR16_TAIL);
9532     cmpq(length, 16);
9533     jccb(Assembler::less, VECTOR8_TAIL);
9534     bind(VECTOR16_LOOP);
9535     movdqu(rymm0, Address(obja, result));
9536     movdqu(rymm1, Address(objb, result));
9537     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9538     ptest(rymm2, rymm2);
9539     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9540     addq(result, 16);
9541     subq(length, 16);
9542     jcc(Assembler::equal, SAME_TILL_END);
9543     //falling through if less than 16 bytes left
9544   } else {//regular intrinsics
9545 
9546     cmpq(length, 16);
9547     jccb(Assembler::less, VECTOR8_TAIL);
9548 
9549     subq(length, 16);
9550     bind(VECTOR16_LOOP);
9551     movdqu(rymm0, Address(obja, result));
9552     movdqu(rymm1, Address(objb, result));
9553     pxor(rymm0, rymm1);
9554     ptest(rymm0, rymm0);
9555     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9556     addq(result, 16);
9557     subq(length, 16);
9558     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9559     addq(length, 16);
9560     jcc(Assembler::equal, SAME_TILL_END);
9561     //falling through if less than 16 bytes left
9562   }
9563 
9564   bind(VECTOR8_TAIL);
9565   cmpq(length, 8);
9566   jccb(Assembler::less, VECTOR4_TAIL);
9567   bind(VECTOR8_LOOP);
9568   movq(tmp1, Address(obja, result));
9569   movq(tmp2, Address(objb, result));
9570   xorq(tmp1, tmp2);
9571   testq(tmp1, tmp1);
9572   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9573   addq(result, 8);
9574   subq(length, 8);
9575   jcc(Assembler::equal, SAME_TILL_END);
9576   //falling through if less than 8 bytes left
9577 
9578   bind(VECTOR4_TAIL);
9579   cmpq(length, 4);
9580   jccb(Assembler::less, BYTES_TAIL);
9581   bind(VECTOR4_LOOP);
9582   movl(tmp1, Address(obja, result));
9583   xorl(tmp1, Address(objb, result));
9584   testl(tmp1, tmp1);
9585   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9586   addq(result, 4);
9587   subq(length, 4);
9588   jcc(Assembler::equal, SAME_TILL_END);
9589   //falling through if less than 4 bytes left
9590 
9591   bind(BYTES_TAIL);
9592   bind(BYTES_LOOP);
9593   load_unsigned_byte(tmp1, Address(obja, result));
9594   load_unsigned_byte(tmp2, Address(objb, result));
9595   xorl(tmp1, tmp2);
9596   testl(tmp1, tmp1);
9597   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9598   decq(length);
9599   jccb(Assembler::zero, SAME_TILL_END);
9600   incq(result);
9601   load_unsigned_byte(tmp1, Address(obja, result));
9602   load_unsigned_byte(tmp2, Address(objb, result));
9603   xorl(tmp1, tmp2);
9604   testl(tmp1, tmp1);
9605   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9606   decq(length);
9607   jccb(Assembler::zero, SAME_TILL_END);
9608   incq(result);
9609   load_unsigned_byte(tmp1, Address(obja, result));
9610   load_unsigned_byte(tmp2, Address(objb, result));
9611   xorl(tmp1, tmp2);
9612   testl(tmp1, tmp1);
9613   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9614   jmpb(SAME_TILL_END);
9615 
9616   if (UseAVX >= 2) {
9617     bind(VECTOR32_NOT_EQUAL);
9618     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9619     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9620     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9621     vpmovmskb(tmp1, rymm0);
9622     bsfq(tmp1, tmp1);
9623     addq(result, tmp1);
9624     shrq(result);
9625     jmpb(DONE);
9626   }
9627 
9628   bind(VECTOR16_NOT_EQUAL);
9629   if (UseAVX >= 2) {
9630     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9631     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9632     pxor(rymm0, rymm2);
9633   } else {
9634     pcmpeqb(rymm2, rymm2);
9635     pxor(rymm0, rymm1);
9636     pcmpeqb(rymm0, rymm1);
9637     pxor(rymm0, rymm2);
9638   }
9639   pmovmskb(tmp1, rymm0);
9640   bsfq(tmp1, tmp1);
9641   addq(result, tmp1);
9642   shrq(result);
9643   jmpb(DONE);
9644 
9645   bind(VECTOR8_NOT_EQUAL);
9646   bind(VECTOR4_NOT_EQUAL);
9647   bsfq(tmp1, tmp1);
9648   shrq(tmp1, 3);
9649   addq(result, tmp1);
9650   bind(BYTES_NOT_EQUAL);
9651   shrq(result);
9652   jmpb(DONE);
9653 
9654   bind(SAME_TILL_END);
9655   mov64(result, -1);
9656 
9657   bind(DONE);
9658 }
9659 
9660 //Helper functions for square_to_len()
9661 
9662 /**
9663  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9664  * Preserves x and z and modifies rest of the registers.
9665  */
9666 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9667   // Perform square and right shift by 1
9668   // Handle odd xlen case first, then for even xlen do the following
9669   // jlong carry = 0;
9670   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9671   //     huge_128 product = x[j:j+1] * x[j:j+1];
9672   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9673   //     z[i+2:i+3] = (jlong)(product >>> 1);
9674   //     carry = (jlong)product;
9675   // }
9676 
9677   xorq(tmp5, tmp5);     // carry
9678   xorq(rdxReg, rdxReg);
9679   xorl(tmp1, tmp1);     // index for x
9680   xorl(tmp4, tmp4);     // index for z
9681 
9682   Label L_first_loop, L_first_loop_exit;
9683 
9684   testl(xlen, 1);
9685   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9686 
9687   // Square and right shift by 1 the odd element using 32 bit multiply
9688   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9689   imulq(raxReg, raxReg);
9690   shrq(raxReg, 1);
9691   adcq(tmp5, 0);
9692   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9693   incrementl(tmp1);
9694   addl(tmp4, 2);
9695 
9696   // Square and  right shift by 1 the rest using 64 bit multiply
9697   bind(L_first_loop);
9698   cmpptr(tmp1, xlen);
9699   jccb(Assembler::equal, L_first_loop_exit);
9700 
9701   // Square
9702   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9703   rorq(raxReg, 32);    // convert big-endian to little-endian
9704   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9705 
9706   // Right shift by 1 and save carry
9707   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9708   rcrq(rdxReg, 1);
9709   rcrq(raxReg, 1);
9710   adcq(tmp5, 0);
9711 
9712   // Store result in z
9713   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9714   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9715 
9716   // Update indices for x and z
9717   addl(tmp1, 2);
9718   addl(tmp4, 4);
9719   jmp(L_first_loop);
9720 
9721   bind(L_first_loop_exit);
9722 }
9723 
9724 
9725 /**
9726  * Perform the following multiply add operation using BMI2 instructions
9727  * carry:sum = sum + op1*op2 + carry
9728  * op2 should be in rdx
9729  * op2 is preserved, all other registers are modified
9730  */
9731 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9732   // assert op2 is rdx
9733   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9734   addq(sum, carry);
9735   adcq(tmp2, 0);
9736   addq(sum, op1);
9737   adcq(tmp2, 0);
9738   movq(carry, tmp2);
9739 }
9740 
9741 /**
9742  * Perform the following multiply add operation:
9743  * carry:sum = sum + op1*op2 + carry
9744  * Preserves op1, op2 and modifies rest of registers
9745  */
9746 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9747   // rdx:rax = op1 * op2
9748   movq(raxReg, op2);
9749   mulq(op1);
9750 
9751   //  rdx:rax = sum + carry + rdx:rax
9752   addq(sum, carry);
9753   adcq(rdxReg, 0);
9754   addq(sum, raxReg);
9755   adcq(rdxReg, 0);
9756 
9757   // carry:sum = rdx:sum
9758   movq(carry, rdxReg);
9759 }
9760 
9761 /**
9762  * Add 64 bit long carry into z[] with carry propogation.
9763  * Preserves z and carry register values and modifies rest of registers.
9764  *
9765  */
9766 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9767   Label L_fourth_loop, L_fourth_loop_exit;
9768 
9769   movl(tmp1, 1);
9770   subl(zlen, 2);
9771   addq(Address(z, zlen, Address::times_4, 0), carry);
9772 
9773   bind(L_fourth_loop);
9774   jccb(Assembler::carryClear, L_fourth_loop_exit);
9775   subl(zlen, 2);
9776   jccb(Assembler::negative, L_fourth_loop_exit);
9777   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9778   jmp(L_fourth_loop);
9779   bind(L_fourth_loop_exit);
9780 }
9781 
9782 /**
9783  * Shift z[] left by 1 bit.
9784  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9785  *
9786  */
9787 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9788 
9789   Label L_fifth_loop, L_fifth_loop_exit;
9790 
9791   // Fifth loop
9792   // Perform primitiveLeftShift(z, zlen, 1)
9793 
9794   const Register prev_carry = tmp1;
9795   const Register new_carry = tmp4;
9796   const Register value = tmp2;
9797   const Register zidx = tmp3;
9798 
9799   // int zidx, carry;
9800   // long value;
9801   // carry = 0;
9802   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9803   //    (carry:value)  = (z[i] << 1) | carry ;
9804   //    z[i] = value;
9805   // }
9806 
9807   movl(zidx, zlen);
9808   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9809 
9810   bind(L_fifth_loop);
9811   decl(zidx);  // Use decl to preserve carry flag
9812   decl(zidx);
9813   jccb(Assembler::negative, L_fifth_loop_exit);
9814 
9815   if (UseBMI2Instructions) {
9816      movq(value, Address(z, zidx, Address::times_4, 0));
9817      rclq(value, 1);
9818      rorxq(value, value, 32);
9819      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9820   }
9821   else {
9822     // clear new_carry
9823     xorl(new_carry, new_carry);
9824 
9825     // Shift z[i] by 1, or in previous carry and save new carry
9826     movq(value, Address(z, zidx, Address::times_4, 0));
9827     shlq(value, 1);
9828     adcl(new_carry, 0);
9829 
9830     orq(value, prev_carry);
9831     rorq(value, 0x20);
9832     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9833 
9834     // Set previous carry = new carry
9835     movl(prev_carry, new_carry);
9836   }
9837   jmp(L_fifth_loop);
9838 
9839   bind(L_fifth_loop_exit);
9840 }
9841 
9842 
9843 /**
9844  * Code for BigInteger::squareToLen() intrinsic
9845  *
9846  * rdi: x
9847  * rsi: len
9848  * r8:  z
9849  * rcx: zlen
9850  * r12: tmp1
9851  * r13: tmp2
9852  * r14: tmp3
9853  * r15: tmp4
9854  * rbx: tmp5
9855  *
9856  */
9857 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) {
9858 
9859   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;
9860   push(tmp1);
9861   push(tmp2);
9862   push(tmp3);
9863   push(tmp4);
9864   push(tmp5);
9865 
9866   // First loop
9867   // Store the squares, right shifted one bit (i.e., divided by 2).
9868   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9869 
9870   // Add in off-diagonal sums.
9871   //
9872   // Second, third (nested) and fourth loops.
9873   // zlen +=2;
9874   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9875   //    carry = 0;
9876   //    long op2 = x[xidx:xidx+1];
9877   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9878   //       k -= 2;
9879   //       long op1 = x[j:j+1];
9880   //       long sum = z[k:k+1];
9881   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9882   //       z[k:k+1] = sum;
9883   //    }
9884   //    add_one_64(z, k, carry, tmp_regs);
9885   // }
9886 
9887   const Register carry = tmp5;
9888   const Register sum = tmp3;
9889   const Register op1 = tmp4;
9890   Register op2 = tmp2;
9891 
9892   push(zlen);
9893   push(len);
9894   addl(zlen,2);
9895   bind(L_second_loop);
9896   xorq(carry, carry);
9897   subl(zlen, 4);
9898   subl(len, 2);
9899   push(zlen);
9900   push(len);
9901   cmpl(len, 0);
9902   jccb(Assembler::lessEqual, L_second_loop_exit);
9903 
9904   // Multiply an array by one 64 bit long.
9905   if (UseBMI2Instructions) {
9906     op2 = rdxReg;
9907     movq(op2, Address(x, len, Address::times_4,  0));
9908     rorxq(op2, op2, 32);
9909   }
9910   else {
9911     movq(op2, Address(x, len, Address::times_4,  0));
9912     rorq(op2, 32);
9913   }
9914 
9915   bind(L_third_loop);
9916   decrementl(len);
9917   jccb(Assembler::negative, L_third_loop_exit);
9918   decrementl(len);
9919   jccb(Assembler::negative, L_last_x);
9920 
9921   movq(op1, Address(x, len, Address::times_4,  0));
9922   rorq(op1, 32);
9923 
9924   bind(L_multiply);
9925   subl(zlen, 2);
9926   movq(sum, Address(z, zlen, Address::times_4,  0));
9927 
9928   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9929   if (UseBMI2Instructions) {
9930     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9931   }
9932   else {
9933     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9934   }
9935 
9936   movq(Address(z, zlen, Address::times_4, 0), sum);
9937 
9938   jmp(L_third_loop);
9939   bind(L_third_loop_exit);
9940 
9941   // Fourth loop
9942   // Add 64 bit long carry into z with carry propogation.
9943   // Uses offsetted zlen.
9944   add_one_64(z, zlen, carry, tmp1);
9945 
9946   pop(len);
9947   pop(zlen);
9948   jmp(L_second_loop);
9949 
9950   // Next infrequent code is moved outside loops.
9951   bind(L_last_x);
9952   movl(op1, Address(x, 0));
9953   jmp(L_multiply);
9954 
9955   bind(L_second_loop_exit);
9956   pop(len);
9957   pop(zlen);
9958   pop(len);
9959   pop(zlen);
9960 
9961   // Fifth loop
9962   // Shift z left 1 bit.
9963   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9964 
9965   // z[zlen-1] |= x[len-1] & 1;
9966   movl(tmp3, Address(x, len, Address::times_4, -4));
9967   andl(tmp3, 1);
9968   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9969 
9970   pop(tmp5);
9971   pop(tmp4);
9972   pop(tmp3);
9973   pop(tmp2);
9974   pop(tmp1);
9975 }
9976 
9977 /**
9978  * Helper function for mul_add()
9979  * Multiply the in[] by int k and add to out[] starting at offset offs using
9980  * 128 bit by 32 bit multiply and return the carry in tmp5.
9981  * Only quad int aligned length of in[] is operated on in this function.
9982  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9983  * This function preserves out, in and k registers.
9984  * len and offset point to the appropriate index in "in" & "out" correspondingly
9985  * tmp5 has the carry.
9986  * other registers are temporary and are modified.
9987  *
9988  */
9989 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9990   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9991   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9992 
9993   Label L_first_loop, L_first_loop_exit;
9994 
9995   movl(tmp1, len);
9996   shrl(tmp1, 2);
9997 
9998   bind(L_first_loop);
9999   subl(tmp1, 1);
10000   jccb(Assembler::negative, L_first_loop_exit);
10001 
10002   subl(len, 4);
10003   subl(offset, 4);
10004 
10005   Register op2 = tmp2;
10006   const Register sum = tmp3;
10007   const Register op1 = tmp4;
10008   const Register carry = tmp5;
10009 
10010   if (UseBMI2Instructions) {
10011     op2 = rdxReg;
10012   }
10013 
10014   movq(op1, Address(in, len, Address::times_4,  8));
10015   rorq(op1, 32);
10016   movq(sum, Address(out, offset, Address::times_4,  8));
10017   rorq(sum, 32);
10018   if (UseBMI2Instructions) {
10019     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10020   }
10021   else {
10022     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10023   }
10024   // Store back in big endian from little endian
10025   rorq(sum, 0x20);
10026   movq(Address(out, offset, Address::times_4,  8), sum);
10027 
10028   movq(op1, Address(in, len, Address::times_4,  0));
10029   rorq(op1, 32);
10030   movq(sum, Address(out, offset, Address::times_4,  0));
10031   rorq(sum, 32);
10032   if (UseBMI2Instructions) {
10033     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10034   }
10035   else {
10036     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10037   }
10038   // Store back in big endian from little endian
10039   rorq(sum, 0x20);
10040   movq(Address(out, offset, Address::times_4,  0), sum);
10041 
10042   jmp(L_first_loop);
10043   bind(L_first_loop_exit);
10044 }
10045 
10046 /**
10047  * Code for BigInteger::mulAdd() intrinsic
10048  *
10049  * rdi: out
10050  * rsi: in
10051  * r11: offs (out.length - offset)
10052  * rcx: len
10053  * r8:  k
10054  * r12: tmp1
10055  * r13: tmp2
10056  * r14: tmp3
10057  * r15: tmp4
10058  * rbx: tmp5
10059  * Multiply the in[] by word k and add to out[], return the carry in rax
10060  */
10061 void MacroAssembler::mul_add(Register out, Register in, Register offs,
10062    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
10063    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10064 
10065   Label L_carry, L_last_in, L_done;
10066 
10067 // carry = 0;
10068 // for (int j=len-1; j >= 0; j--) {
10069 //    long product = (in[j] & LONG_MASK) * kLong +
10070 //                   (out[offs] & LONG_MASK) + carry;
10071 //    out[offs--] = (int)product;
10072 //    carry = product >>> 32;
10073 // }
10074 //
10075   push(tmp1);
10076   push(tmp2);
10077   push(tmp3);
10078   push(tmp4);
10079   push(tmp5);
10080 
10081   Register op2 = tmp2;
10082   const Register sum = tmp3;
10083   const Register op1 = tmp4;
10084   const Register carry =  tmp5;
10085 
10086   if (UseBMI2Instructions) {
10087     op2 = rdxReg;
10088     movl(op2, k);
10089   }
10090   else {
10091     movl(op2, k);
10092   }
10093 
10094   xorq(carry, carry);
10095 
10096   //First loop
10097 
10098   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
10099   //The carry is in tmp5
10100   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
10101 
10102   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
10103   decrementl(len);
10104   jccb(Assembler::negative, L_carry);
10105   decrementl(len);
10106   jccb(Assembler::negative, L_last_in);
10107 
10108   movq(op1, Address(in, len, Address::times_4,  0));
10109   rorq(op1, 32);
10110 
10111   subl(offs, 2);
10112   movq(sum, Address(out, offs, Address::times_4,  0));
10113   rorq(sum, 32);
10114 
10115   if (UseBMI2Instructions) {
10116     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10117   }
10118   else {
10119     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10120   }
10121 
10122   // Store back in big endian from little endian
10123   rorq(sum, 0x20);
10124   movq(Address(out, offs, Address::times_4,  0), sum);
10125 
10126   testl(len, len);
10127   jccb(Assembler::zero, L_carry);
10128 
10129   //Multiply the last in[] entry, if any
10130   bind(L_last_in);
10131   movl(op1, Address(in, 0));
10132   movl(sum, Address(out, offs, Address::times_4,  -4));
10133 
10134   movl(raxReg, k);
10135   mull(op1); //tmp4 * eax -> edx:eax
10136   addl(sum, carry);
10137   adcl(rdxReg, 0);
10138   addl(sum, raxReg);
10139   adcl(rdxReg, 0);
10140   movl(carry, rdxReg);
10141 
10142   movl(Address(out, offs, Address::times_4,  -4), sum);
10143 
10144   bind(L_carry);
10145   //return tmp5/carry as carry in rax
10146   movl(rax, carry);
10147 
10148   bind(L_done);
10149   pop(tmp5);
10150   pop(tmp4);
10151   pop(tmp3);
10152   pop(tmp2);
10153   pop(tmp1);
10154 }
10155 #endif
10156 
10157 /**
10158  * Emits code to update CRC-32 with a byte value according to constants in table
10159  *
10160  * @param [in,out]crc   Register containing the crc.
10161  * @param [in]val       Register containing the byte to fold into the CRC.
10162  * @param [in]table     Register containing the table of crc constants.
10163  *
10164  * uint32_t crc;
10165  * val = crc_table[(val ^ crc) & 0xFF];
10166  * crc = val ^ (crc >> 8);
10167  *
10168  */
10169 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10170   xorl(val, crc);
10171   andl(val, 0xFF);
10172   shrl(crc, 8); // unsigned shift
10173   xorl(crc, Address(table, val, Address::times_4, 0));
10174 }
10175 
10176 /**
10177  * Fold 128-bit data chunk
10178  */
10179 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10180   if (UseAVX > 0) {
10181     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10182     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10183     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10184     pxor(xcrc, xtmp);
10185   } else {
10186     movdqa(xtmp, xcrc);
10187     pclmulhdq(xtmp, xK);   // [123:64]
10188     pclmulldq(xcrc, xK);   // [63:0]
10189     pxor(xcrc, xtmp);
10190     movdqu(xtmp, Address(buf, offset));
10191     pxor(xcrc, xtmp);
10192   }
10193 }
10194 
10195 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10196   if (UseAVX > 0) {
10197     vpclmulhdq(xtmp, xK, xcrc);
10198     vpclmulldq(xcrc, xK, xcrc);
10199     pxor(xcrc, xbuf);
10200     pxor(xcrc, xtmp);
10201   } else {
10202     movdqa(xtmp, xcrc);
10203     pclmulhdq(xtmp, xK);
10204     pclmulldq(xcrc, xK);
10205     pxor(xcrc, xbuf);
10206     pxor(xcrc, xtmp);
10207   }
10208 }
10209 
10210 /**
10211  * 8-bit folds to compute 32-bit CRC
10212  *
10213  * uint64_t xcrc;
10214  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10215  */
10216 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10217   movdl(tmp, xcrc);
10218   andl(tmp, 0xFF);
10219   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10220   psrldq(xcrc, 1); // unsigned shift one byte
10221   pxor(xcrc, xtmp);
10222 }
10223 
10224 /**
10225  * uint32_t crc;
10226  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10227  */
10228 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10229   movl(tmp, crc);
10230   andl(tmp, 0xFF);
10231   shrl(crc, 8);
10232   xorl(crc, Address(table, tmp, Address::times_4, 0));
10233 }
10234 
10235 /**
10236  * @param crc   register containing existing CRC (32-bit)
10237  * @param buf   register pointing to input byte buffer (byte*)
10238  * @param len   register containing number of bytes
10239  * @param table register that will contain address of CRC table
10240  * @param tmp   scratch register
10241  */
10242 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10243   assert_different_registers(crc, buf, len, table, tmp, rax);
10244 
10245   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10246   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10247 
10248   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10249   // context for the registers used, where all instructions below are using 128-bit mode
10250   // On EVEX without VL and BW, these instructions will all be AVX.
10251   if (VM_Version::supports_avx512vlbw()) {
10252     movl(tmp, 0xffff);
10253     kmovwl(k1, tmp);
10254   }
10255 
10256   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10257   notl(crc); // ~crc
10258   cmpl(len, 16);
10259   jcc(Assembler::less, L_tail);
10260 
10261   // Align buffer to 16 bytes
10262   movl(tmp, buf);
10263   andl(tmp, 0xF);
10264   jccb(Assembler::zero, L_aligned);
10265   subl(tmp,  16);
10266   addl(len, tmp);
10267 
10268   align(4);
10269   BIND(L_align_loop);
10270   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10271   update_byte_crc32(crc, rax, table);
10272   increment(buf);
10273   incrementl(tmp);
10274   jccb(Assembler::less, L_align_loop);
10275 
10276   BIND(L_aligned);
10277   movl(tmp, len); // save
10278   shrl(len, 4);
10279   jcc(Assembler::zero, L_tail_restore);
10280 
10281   // Fold crc into first bytes of vector
10282   movdqa(xmm1, Address(buf, 0));
10283   movdl(rax, xmm1);
10284   xorl(crc, rax);
10285   if (VM_Version::supports_sse4_1()) {
10286     pinsrd(xmm1, crc, 0);
10287   } else {
10288     pinsrw(xmm1, crc, 0);
10289     shrl(crc, 16);
10290     pinsrw(xmm1, crc, 1);
10291   }
10292   addptr(buf, 16);
10293   subl(len, 4); // len > 0
10294   jcc(Assembler::less, L_fold_tail);
10295 
10296   movdqa(xmm2, Address(buf,  0));
10297   movdqa(xmm3, Address(buf, 16));
10298   movdqa(xmm4, Address(buf, 32));
10299   addptr(buf, 48);
10300   subl(len, 3);
10301   jcc(Assembler::lessEqual, L_fold_512b);
10302 
10303   // Fold total 512 bits of polynomial on each iteration,
10304   // 128 bits per each of 4 parallel streams.
10305   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10306 
10307   align(32);
10308   BIND(L_fold_512b_loop);
10309   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10310   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10311   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10312   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10313   addptr(buf, 64);
10314   subl(len, 4);
10315   jcc(Assembler::greater, L_fold_512b_loop);
10316 
10317   // Fold 512 bits to 128 bits.
10318   BIND(L_fold_512b);
10319   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10320   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10321   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10322   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10323 
10324   // Fold the rest of 128 bits data chunks
10325   BIND(L_fold_tail);
10326   addl(len, 3);
10327   jccb(Assembler::lessEqual, L_fold_128b);
10328   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10329 
10330   BIND(L_fold_tail_loop);
10331   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10332   addptr(buf, 16);
10333   decrementl(len);
10334   jccb(Assembler::greater, L_fold_tail_loop);
10335 
10336   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10337   BIND(L_fold_128b);
10338   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10339   if (UseAVX > 0) {
10340     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10341     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10342     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10343   } else {
10344     movdqa(xmm2, xmm0);
10345     pclmulqdq(xmm2, xmm1, 0x1);
10346     movdqa(xmm3, xmm0);
10347     pand(xmm3, xmm2);
10348     pclmulqdq(xmm0, xmm3, 0x1);
10349   }
10350   psrldq(xmm1, 8);
10351   psrldq(xmm2, 4);
10352   pxor(xmm0, xmm1);
10353   pxor(xmm0, xmm2);
10354 
10355   // 8 8-bit folds to compute 32-bit CRC.
10356   for (int j = 0; j < 4; j++) {
10357     fold_8bit_crc32(xmm0, table, xmm1, rax);
10358   }
10359   movdl(crc, xmm0); // mov 32 bits to general register
10360   for (int j = 0; j < 4; j++) {
10361     fold_8bit_crc32(crc, table, rax);
10362   }
10363 
10364   BIND(L_tail_restore);
10365   movl(len, tmp); // restore
10366   BIND(L_tail);
10367   andl(len, 0xf);
10368   jccb(Assembler::zero, L_exit);
10369 
10370   // Fold the rest of bytes
10371   align(4);
10372   BIND(L_tail_loop);
10373   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10374   update_byte_crc32(crc, rax, table);
10375   increment(buf);
10376   decrementl(len);
10377   jccb(Assembler::greater, L_tail_loop);
10378 
10379   BIND(L_exit);
10380   notl(crc); // ~c
10381 }
10382 
10383 #ifdef _LP64
10384 // S. Gueron / Information Processing Letters 112 (2012) 184
10385 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10386 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10387 // Output: the 64-bit carry-less product of B * CONST
10388 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10389                                      Register tmp1, Register tmp2, Register tmp3) {
10390   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10391   if (n > 0) {
10392     addq(tmp3, n * 256 * 8);
10393   }
10394   //    Q1 = TABLEExt[n][B & 0xFF];
10395   movl(tmp1, in);
10396   andl(tmp1, 0x000000FF);
10397   shll(tmp1, 3);
10398   addq(tmp1, tmp3);
10399   movq(tmp1, Address(tmp1, 0));
10400 
10401   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10402   movl(tmp2, in);
10403   shrl(tmp2, 8);
10404   andl(tmp2, 0x000000FF);
10405   shll(tmp2, 3);
10406   addq(tmp2, tmp3);
10407   movq(tmp2, Address(tmp2, 0));
10408 
10409   shlq(tmp2, 8);
10410   xorq(tmp1, tmp2);
10411 
10412   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10413   movl(tmp2, in);
10414   shrl(tmp2, 16);
10415   andl(tmp2, 0x000000FF);
10416   shll(tmp2, 3);
10417   addq(tmp2, tmp3);
10418   movq(tmp2, Address(tmp2, 0));
10419 
10420   shlq(tmp2, 16);
10421   xorq(tmp1, tmp2);
10422 
10423   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10424   shrl(in, 24);
10425   andl(in, 0x000000FF);
10426   shll(in, 3);
10427   addq(in, tmp3);
10428   movq(in, Address(in, 0));
10429 
10430   shlq(in, 24);
10431   xorq(in, tmp1);
10432   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10433 }
10434 
10435 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10436                                       Register in_out,
10437                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10438                                       XMMRegister w_xtmp2,
10439                                       Register tmp1,
10440                                       Register n_tmp2, Register n_tmp3) {
10441   if (is_pclmulqdq_supported) {
10442     movdl(w_xtmp1, in_out); // modified blindly
10443 
10444     movl(tmp1, const_or_pre_comp_const_index);
10445     movdl(w_xtmp2, tmp1);
10446     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10447 
10448     movdq(in_out, w_xtmp1);
10449   } else {
10450     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10451   }
10452 }
10453 
10454 // Recombination Alternative 2: No bit-reflections
10455 // T1 = (CRC_A * U1) << 1
10456 // T2 = (CRC_B * U2) << 1
10457 // C1 = T1 >> 32
10458 // C2 = T2 >> 32
10459 // T1 = T1 & 0xFFFFFFFF
10460 // T2 = T2 & 0xFFFFFFFF
10461 // T1 = CRC32(0, T1)
10462 // T2 = CRC32(0, T2)
10463 // C1 = C1 ^ T1
10464 // C2 = C2 ^ T2
10465 // CRC = C1 ^ C2 ^ CRC_C
10466 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,
10467                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10468                                      Register tmp1, Register tmp2,
10469                                      Register n_tmp3) {
10470   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10471   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10472   shlq(in_out, 1);
10473   movl(tmp1, in_out);
10474   shrq(in_out, 32);
10475   xorl(tmp2, tmp2);
10476   crc32(tmp2, tmp1, 4);
10477   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10478   shlq(in1, 1);
10479   movl(tmp1, in1);
10480   shrq(in1, 32);
10481   xorl(tmp2, tmp2);
10482   crc32(tmp2, tmp1, 4);
10483   xorl(in1, tmp2);
10484   xorl(in_out, in1);
10485   xorl(in_out, in2);
10486 }
10487 
10488 // Set N to predefined value
10489 // Subtract from a lenght of a buffer
10490 // execute in a loop:
10491 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10492 // for i = 1 to N do
10493 //  CRC_A = CRC32(CRC_A, A[i])
10494 //  CRC_B = CRC32(CRC_B, B[i])
10495 //  CRC_C = CRC32(CRC_C, C[i])
10496 // end for
10497 // Recombine
10498 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,
10499                                        Register in_out1, Register in_out2, Register in_out3,
10500                                        Register tmp1, Register tmp2, Register tmp3,
10501                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10502                                        Register tmp4, Register tmp5,
10503                                        Register n_tmp6) {
10504   Label L_processPartitions;
10505   Label L_processPartition;
10506   Label L_exit;
10507 
10508   bind(L_processPartitions);
10509   cmpl(in_out1, 3 * size);
10510   jcc(Assembler::less, L_exit);
10511     xorl(tmp1, tmp1);
10512     xorl(tmp2, tmp2);
10513     movq(tmp3, in_out2);
10514     addq(tmp3, size);
10515 
10516     bind(L_processPartition);
10517       crc32(in_out3, Address(in_out2, 0), 8);
10518       crc32(tmp1, Address(in_out2, size), 8);
10519       crc32(tmp2, Address(in_out2, size * 2), 8);
10520       addq(in_out2, 8);
10521       cmpq(in_out2, tmp3);
10522       jcc(Assembler::less, L_processPartition);
10523     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10524             w_xtmp1, w_xtmp2, w_xtmp3,
10525             tmp4, tmp5,
10526             n_tmp6);
10527     addq(in_out2, 2 * size);
10528     subl(in_out1, 3 * size);
10529     jmp(L_processPartitions);
10530 
10531   bind(L_exit);
10532 }
10533 #else
10534 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10535                                      Register tmp1, Register tmp2, Register tmp3,
10536                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10537   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10538   if (n > 0) {
10539     addl(tmp3, n * 256 * 8);
10540   }
10541   //    Q1 = TABLEExt[n][B & 0xFF];
10542   movl(tmp1, in_out);
10543   andl(tmp1, 0x000000FF);
10544   shll(tmp1, 3);
10545   addl(tmp1, tmp3);
10546   movq(xtmp1, Address(tmp1, 0));
10547 
10548   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10549   movl(tmp2, in_out);
10550   shrl(tmp2, 8);
10551   andl(tmp2, 0x000000FF);
10552   shll(tmp2, 3);
10553   addl(tmp2, tmp3);
10554   movq(xtmp2, Address(tmp2, 0));
10555 
10556   psllq(xtmp2, 8);
10557   pxor(xtmp1, xtmp2);
10558 
10559   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10560   movl(tmp2, in_out);
10561   shrl(tmp2, 16);
10562   andl(tmp2, 0x000000FF);
10563   shll(tmp2, 3);
10564   addl(tmp2, tmp3);
10565   movq(xtmp2, Address(tmp2, 0));
10566 
10567   psllq(xtmp2, 16);
10568   pxor(xtmp1, xtmp2);
10569 
10570   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10571   shrl(in_out, 24);
10572   andl(in_out, 0x000000FF);
10573   shll(in_out, 3);
10574   addl(in_out, tmp3);
10575   movq(xtmp2, Address(in_out, 0));
10576 
10577   psllq(xtmp2, 24);
10578   pxor(xtmp1, xtmp2); // Result in CXMM
10579   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10580 }
10581 
10582 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10583                                       Register in_out,
10584                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10585                                       XMMRegister w_xtmp2,
10586                                       Register tmp1,
10587                                       Register n_tmp2, Register n_tmp3) {
10588   if (is_pclmulqdq_supported) {
10589     movdl(w_xtmp1, in_out);
10590 
10591     movl(tmp1, const_or_pre_comp_const_index);
10592     movdl(w_xtmp2, tmp1);
10593     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10594     // Keep result in XMM since GPR is 32 bit in length
10595   } else {
10596     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10597   }
10598 }
10599 
10600 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,
10601                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10602                                      Register tmp1, Register tmp2,
10603                                      Register n_tmp3) {
10604   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10605   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10606 
10607   psllq(w_xtmp1, 1);
10608   movdl(tmp1, w_xtmp1);
10609   psrlq(w_xtmp1, 32);
10610   movdl(in_out, w_xtmp1);
10611 
10612   xorl(tmp2, tmp2);
10613   crc32(tmp2, tmp1, 4);
10614   xorl(in_out, tmp2);
10615 
10616   psllq(w_xtmp2, 1);
10617   movdl(tmp1, w_xtmp2);
10618   psrlq(w_xtmp2, 32);
10619   movdl(in1, w_xtmp2);
10620 
10621   xorl(tmp2, tmp2);
10622   crc32(tmp2, tmp1, 4);
10623   xorl(in1, tmp2);
10624   xorl(in_out, in1);
10625   xorl(in_out, in2);
10626 }
10627 
10628 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,
10629                                        Register in_out1, Register in_out2, Register in_out3,
10630                                        Register tmp1, Register tmp2, Register tmp3,
10631                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10632                                        Register tmp4, Register tmp5,
10633                                        Register n_tmp6) {
10634   Label L_processPartitions;
10635   Label L_processPartition;
10636   Label L_exit;
10637 
10638   bind(L_processPartitions);
10639   cmpl(in_out1, 3 * size);
10640   jcc(Assembler::less, L_exit);
10641     xorl(tmp1, tmp1);
10642     xorl(tmp2, tmp2);
10643     movl(tmp3, in_out2);
10644     addl(tmp3, size);
10645 
10646     bind(L_processPartition);
10647       crc32(in_out3, Address(in_out2, 0), 4);
10648       crc32(tmp1, Address(in_out2, size), 4);
10649       crc32(tmp2, Address(in_out2, size*2), 4);
10650       crc32(in_out3, Address(in_out2, 0+4), 4);
10651       crc32(tmp1, Address(in_out2, size+4), 4);
10652       crc32(tmp2, Address(in_out2, size*2+4), 4);
10653       addl(in_out2, 8);
10654       cmpl(in_out2, tmp3);
10655       jcc(Assembler::less, L_processPartition);
10656 
10657         push(tmp3);
10658         push(in_out1);
10659         push(in_out2);
10660         tmp4 = tmp3;
10661         tmp5 = in_out1;
10662         n_tmp6 = in_out2;
10663 
10664       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10665             w_xtmp1, w_xtmp2, w_xtmp3,
10666             tmp4, tmp5,
10667             n_tmp6);
10668 
10669         pop(in_out2);
10670         pop(in_out1);
10671         pop(tmp3);
10672 
10673     addl(in_out2, 2 * size);
10674     subl(in_out1, 3 * size);
10675     jmp(L_processPartitions);
10676 
10677   bind(L_exit);
10678 }
10679 #endif //LP64
10680 
10681 #ifdef _LP64
10682 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10683 // Input: A buffer I of L bytes.
10684 // Output: the CRC32C value of the buffer.
10685 // Notations:
10686 // Write L = 24N + r, with N = floor (L/24).
10687 // r = L mod 24 (0 <= r < 24).
10688 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10689 // N quadwords, and R consists of r bytes.
10690 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10691 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10692 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10693 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10694 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10695                                           Register tmp1, Register tmp2, Register tmp3,
10696                                           Register tmp4, Register tmp5, Register tmp6,
10697                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10698                                           bool is_pclmulqdq_supported) {
10699   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10700   Label L_wordByWord;
10701   Label L_byteByByteProlog;
10702   Label L_byteByByte;
10703   Label L_exit;
10704 
10705   if (is_pclmulqdq_supported ) {
10706     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10707     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10708 
10709     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10710     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10711 
10712     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10713     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10714     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10715   } else {
10716     const_or_pre_comp_const_index[0] = 1;
10717     const_or_pre_comp_const_index[1] = 0;
10718 
10719     const_or_pre_comp_const_index[2] = 3;
10720     const_or_pre_comp_const_index[3] = 2;
10721 
10722     const_or_pre_comp_const_index[4] = 5;
10723     const_or_pre_comp_const_index[5] = 4;
10724    }
10725   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10726                     in2, in1, in_out,
10727                     tmp1, tmp2, tmp3,
10728                     w_xtmp1, w_xtmp2, w_xtmp3,
10729                     tmp4, tmp5,
10730                     tmp6);
10731   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10732                     in2, in1, in_out,
10733                     tmp1, tmp2, tmp3,
10734                     w_xtmp1, w_xtmp2, w_xtmp3,
10735                     tmp4, tmp5,
10736                     tmp6);
10737   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10738                     in2, in1, in_out,
10739                     tmp1, tmp2, tmp3,
10740                     w_xtmp1, w_xtmp2, w_xtmp3,
10741                     tmp4, tmp5,
10742                     tmp6);
10743   movl(tmp1, in2);
10744   andl(tmp1, 0x00000007);
10745   negl(tmp1);
10746   addl(tmp1, in2);
10747   addq(tmp1, in1);
10748 
10749   BIND(L_wordByWord);
10750   cmpq(in1, tmp1);
10751   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10752     crc32(in_out, Address(in1, 0), 4);
10753     addq(in1, 4);
10754     jmp(L_wordByWord);
10755 
10756   BIND(L_byteByByteProlog);
10757   andl(in2, 0x00000007);
10758   movl(tmp2, 1);
10759 
10760   BIND(L_byteByByte);
10761   cmpl(tmp2, in2);
10762   jccb(Assembler::greater, L_exit);
10763     crc32(in_out, Address(in1, 0), 1);
10764     incq(in1);
10765     incl(tmp2);
10766     jmp(L_byteByByte);
10767 
10768   BIND(L_exit);
10769 }
10770 #else
10771 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10772                                           Register tmp1, Register  tmp2, Register tmp3,
10773                                           Register tmp4, Register  tmp5, Register tmp6,
10774                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10775                                           bool is_pclmulqdq_supported) {
10776   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10777   Label L_wordByWord;
10778   Label L_byteByByteProlog;
10779   Label L_byteByByte;
10780   Label L_exit;
10781 
10782   if (is_pclmulqdq_supported) {
10783     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10784     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10785 
10786     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10787     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10788 
10789     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10790     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10791   } else {
10792     const_or_pre_comp_const_index[0] = 1;
10793     const_or_pre_comp_const_index[1] = 0;
10794 
10795     const_or_pre_comp_const_index[2] = 3;
10796     const_or_pre_comp_const_index[3] = 2;
10797 
10798     const_or_pre_comp_const_index[4] = 5;
10799     const_or_pre_comp_const_index[5] = 4;
10800   }
10801   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10802                     in2, in1, in_out,
10803                     tmp1, tmp2, tmp3,
10804                     w_xtmp1, w_xtmp2, w_xtmp3,
10805                     tmp4, tmp5,
10806                     tmp6);
10807   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10808                     in2, in1, in_out,
10809                     tmp1, tmp2, tmp3,
10810                     w_xtmp1, w_xtmp2, w_xtmp3,
10811                     tmp4, tmp5,
10812                     tmp6);
10813   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10814                     in2, in1, in_out,
10815                     tmp1, tmp2, tmp3,
10816                     w_xtmp1, w_xtmp2, w_xtmp3,
10817                     tmp4, tmp5,
10818                     tmp6);
10819   movl(tmp1, in2);
10820   andl(tmp1, 0x00000007);
10821   negl(tmp1);
10822   addl(tmp1, in2);
10823   addl(tmp1, in1);
10824 
10825   BIND(L_wordByWord);
10826   cmpl(in1, tmp1);
10827   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10828     crc32(in_out, Address(in1,0), 4);
10829     addl(in1, 4);
10830     jmp(L_wordByWord);
10831 
10832   BIND(L_byteByByteProlog);
10833   andl(in2, 0x00000007);
10834   movl(tmp2, 1);
10835 
10836   BIND(L_byteByByte);
10837   cmpl(tmp2, in2);
10838   jccb(Assembler::greater, L_exit);
10839     movb(tmp1, Address(in1, 0));
10840     crc32(in_out, tmp1, 1);
10841     incl(in1);
10842     incl(tmp2);
10843     jmp(L_byteByByte);
10844 
10845   BIND(L_exit);
10846 }
10847 #endif // LP64
10848 #undef BIND
10849 #undef BLOCK_COMMENT
10850 
10851 // Compress char[] array to byte[].
10852 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10853 //   @HotSpotIntrinsicCandidate
10854 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10855 //     for (int i = 0; i < len; i++) {
10856 //       int c = src[srcOff++];
10857 //       if (c >>> 8 != 0) {
10858 //         return 0;
10859 //       }
10860 //       dst[dstOff++] = (byte)c;
10861 //     }
10862 //     return len;
10863 //   }
10864 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10865   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10866   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10867   Register tmp5, Register result) {
10868   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10869 
10870   // rsi: src
10871   // rdi: dst
10872   // rdx: len
10873   // rcx: tmp5
10874   // rax: result
10875 
10876   // rsi holds start addr of source char[] to be compressed
10877   // rdi holds start addr of destination byte[]
10878   // rdx holds length
10879 
10880   assert(len != result, "");
10881 
10882   // save length for return
10883   push(len);
10884 
10885   if ((UseAVX > 2) && // AVX512
10886     VM_Version::supports_avx512vlbw() &&
10887     VM_Version::supports_bmi2()) {
10888 
10889     set_vector_masking();  // opening of the stub context for programming mask registers
10890 
10891     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10892 
10893     // alignement
10894     Label post_alignement;
10895 
10896     // if length of the string is less than 16, handle it in an old fashioned
10897     // way
10898     testl(len, -32);
10899     jcc(Assembler::zero, below_threshold);
10900 
10901     // First check whether a character is compressable ( <= 0xFF).
10902     // Create mask to test for Unicode chars inside zmm vector
10903     movl(result, 0x00FF);
10904     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10905 
10906     // Save k1
10907     kmovql(k3, k1);
10908 
10909     testl(len, -64);
10910     jcc(Assembler::zero, post_alignement);
10911 
10912     movl(tmp5, dst);
10913     andl(tmp5, (32 - 1));
10914     negl(tmp5);
10915     andl(tmp5, (32 - 1));
10916 
10917     // bail out when there is nothing to be done
10918     testl(tmp5, 0xFFFFFFFF);
10919     jcc(Assembler::zero, post_alignement);
10920 
10921     // ~(~0 << len), where len is the # of remaining elements to process
10922     movl(result, 0xFFFFFFFF);
10923     shlxl(result, result, tmp5);
10924     notl(result);
10925     kmovdl(k1, result);
10926 
10927     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10928     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10929     ktestd(k2, k1);
10930     jcc(Assembler::carryClear, restore_k1_return_zero);
10931 
10932     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10933 
10934     addptr(src, tmp5);
10935     addptr(src, tmp5);
10936     addptr(dst, tmp5);
10937     subl(len, tmp5);
10938 
10939     bind(post_alignement);
10940     // end of alignement
10941 
10942     movl(tmp5, len);
10943     andl(tmp5, (32 - 1));    // tail count (in chars)
10944     andl(len, ~(32 - 1));    // vector count (in chars)
10945     jcc(Assembler::zero, copy_loop_tail);
10946 
10947     lea(src, Address(src, len, Address::times_2));
10948     lea(dst, Address(dst, len, Address::times_1));
10949     negptr(len);
10950 
10951     bind(copy_32_loop);
10952     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10953     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10954     kortestdl(k2, k2);
10955     jcc(Assembler::carryClear, restore_k1_return_zero);
10956 
10957     // All elements in current processed chunk are valid candidates for
10958     // compression. Write a truncated byte elements to the memory.
10959     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10960     addptr(len, 32);
10961     jcc(Assembler::notZero, copy_32_loop);
10962 
10963     bind(copy_loop_tail);
10964     // bail out when there is nothing to be done
10965     testl(tmp5, 0xFFFFFFFF);
10966     // Restore k1
10967     kmovql(k1, k3);
10968     jcc(Assembler::zero, return_length);
10969 
10970     movl(len, tmp5);
10971 
10972     // ~(~0 << len), where len is the # of remaining elements to process
10973     movl(result, 0xFFFFFFFF);
10974     shlxl(result, result, len);
10975     notl(result);
10976 
10977     kmovdl(k1, result);
10978 
10979     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10980     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10981     ktestd(k2, k1);
10982     jcc(Assembler::carryClear, restore_k1_return_zero);
10983 
10984     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10985     // Restore k1
10986     kmovql(k1, k3);
10987     jmp(return_length);
10988 
10989     bind(restore_k1_return_zero);
10990     // Restore k1
10991     kmovql(k1, k3);
10992     jmp(return_zero);
10993 
10994     clear_vector_masking();   // closing of the stub context for programming mask registers
10995   }
10996   if (UseSSE42Intrinsics) {
10997     Label copy_32_loop, copy_16, copy_tail;
10998 
10999     bind(below_threshold);
11000 
11001     movl(result, len);
11002 
11003     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
11004 
11005     // vectored compression
11006     andl(len, 0xfffffff0);    // vector count (in chars)
11007     andl(result, 0x0000000f);    // tail count (in chars)
11008     testl(len, len);
11009     jccb(Assembler::zero, copy_16);
11010 
11011     // compress 16 chars per iter
11012     movdl(tmp1Reg, tmp5);
11013     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11014     pxor(tmp4Reg, tmp4Reg);
11015 
11016     lea(src, Address(src, len, Address::times_2));
11017     lea(dst, Address(dst, len, Address::times_1));
11018     negptr(len);
11019 
11020     bind(copy_32_loop);
11021     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
11022     por(tmp4Reg, tmp2Reg);
11023     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
11024     por(tmp4Reg, tmp3Reg);
11025     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
11026     jcc(Assembler::notZero, return_zero);
11027     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
11028     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
11029     addptr(len, 16);
11030     jcc(Assembler::notZero, copy_32_loop);
11031 
11032     // compress next vector of 8 chars (if any)
11033     bind(copy_16);
11034     movl(len, result);
11035     andl(len, 0xfffffff8);    // vector count (in chars)
11036     andl(result, 0x00000007);    // tail count (in chars)
11037     testl(len, len);
11038     jccb(Assembler::zero, copy_tail);
11039 
11040     movdl(tmp1Reg, tmp5);
11041     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11042     pxor(tmp3Reg, tmp3Reg);
11043 
11044     movdqu(tmp2Reg, Address(src, 0));
11045     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
11046     jccb(Assembler::notZero, return_zero);
11047     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
11048     movq(Address(dst, 0), tmp2Reg);
11049     addptr(src, 16);
11050     addptr(dst, 8);
11051 
11052     bind(copy_tail);
11053     movl(len, result);
11054   }
11055   // compress 1 char per iter
11056   testl(len, len);
11057   jccb(Assembler::zero, return_length);
11058   lea(src, Address(src, len, Address::times_2));
11059   lea(dst, Address(dst, len, Address::times_1));
11060   negptr(len);
11061 
11062   bind(copy_chars_loop);
11063   load_unsigned_short(result, Address(src, len, Address::times_2));
11064   testl(result, 0xff00);      // check if Unicode char
11065   jccb(Assembler::notZero, return_zero);
11066   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
11067   increment(len);
11068   jcc(Assembler::notZero, copy_chars_loop);
11069 
11070   // if compression succeeded, return length
11071   bind(return_length);
11072   pop(result);
11073   jmpb(done);
11074 
11075   // if compression failed, return 0
11076   bind(return_zero);
11077   xorl(result, result);
11078   addptr(rsp, wordSize);
11079 
11080   bind(done);
11081 }
11082 
11083 // Inflate byte[] array to char[].
11084 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
11085 //   @HotSpotIntrinsicCandidate
11086 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
11087 //     for (int i = 0; i < len; i++) {
11088 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
11089 //     }
11090 //   }
11091 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
11092   XMMRegister tmp1, Register tmp2) {
11093   Label copy_chars_loop, done, below_threshold;
11094   // rsi: src
11095   // rdi: dst
11096   // rdx: len
11097   // rcx: tmp2
11098 
11099   // rsi holds start addr of source byte[] to be inflated
11100   // rdi holds start addr of destination char[]
11101   // rdx holds length
11102   assert_different_registers(src, dst, len, tmp2);
11103 
11104   if ((UseAVX > 2) && // AVX512
11105     VM_Version::supports_avx512vlbw() &&
11106     VM_Version::supports_bmi2()) {
11107 
11108     set_vector_masking();  // opening of the stub context for programming mask registers
11109 
11110     Label copy_32_loop, copy_tail;
11111     Register tmp3_aliased = len;
11112 
11113     // if length of the string is less than 16, handle it in an old fashioned
11114     // way
11115     testl(len, -16);
11116     jcc(Assembler::zero, below_threshold);
11117 
11118     // In order to use only one arithmetic operation for the main loop we use
11119     // this pre-calculation
11120     movl(tmp2, len);
11121     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
11122     andl(len, -32);     // vector count
11123     jccb(Assembler::zero, copy_tail);
11124 
11125     lea(src, Address(src, len, Address::times_1));
11126     lea(dst, Address(dst, len, Address::times_2));
11127     negptr(len);
11128 
11129 
11130     // inflate 32 chars per iter
11131     bind(copy_32_loop);
11132     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
11133     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
11134     addptr(len, 32);
11135     jcc(Assembler::notZero, copy_32_loop);
11136 
11137     bind(copy_tail);
11138     // bail out when there is nothing to be done
11139     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
11140     jcc(Assembler::zero, done);
11141 
11142     // Save k1
11143     kmovql(k2, k1);
11144 
11145     // ~(~0 << length), where length is the # of remaining elements to process
11146     movl(tmp3_aliased, -1);
11147     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
11148     notl(tmp3_aliased);
11149     kmovdl(k1, tmp3_aliased);
11150     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
11151     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
11152 
11153     // Restore k1
11154     kmovql(k1, k2);
11155     jmp(done);
11156 
11157     clear_vector_masking();   // closing of the stub context for programming mask registers
11158   }
11159   if (UseSSE42Intrinsics) {
11160     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
11161 
11162     movl(tmp2, len);
11163 
11164     if (UseAVX > 1) {
11165       andl(tmp2, (16 - 1));
11166       andl(len, -16);
11167       jccb(Assembler::zero, copy_new_tail);
11168     } else {
11169       andl(tmp2, 0x00000007);   // tail count (in chars)
11170       andl(len, 0xfffffff8);    // vector count (in chars)
11171       jccb(Assembler::zero, copy_tail);
11172     }
11173 
11174     // vectored inflation
11175     lea(src, Address(src, len, Address::times_1));
11176     lea(dst, Address(dst, len, Address::times_2));
11177     negptr(len);
11178 
11179     if (UseAVX > 1) {
11180       bind(copy_16_loop);
11181       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
11182       vmovdqu(Address(dst, len, Address::times_2), tmp1);
11183       addptr(len, 16);
11184       jcc(Assembler::notZero, copy_16_loop);
11185 
11186       bind(below_threshold);
11187       bind(copy_new_tail);
11188       if ((UseAVX > 2) &&
11189         VM_Version::supports_avx512vlbw() &&
11190         VM_Version::supports_bmi2()) {
11191         movl(tmp2, len);
11192       } else {
11193         movl(len, tmp2);
11194       }
11195       andl(tmp2, 0x00000007);
11196       andl(len, 0xFFFFFFF8);
11197       jccb(Assembler::zero, copy_tail);
11198 
11199       pmovzxbw(tmp1, Address(src, 0));
11200       movdqu(Address(dst, 0), tmp1);
11201       addptr(src, 8);
11202       addptr(dst, 2 * 8);
11203 
11204       jmp(copy_tail, true);
11205     }
11206 
11207     // inflate 8 chars per iter
11208     bind(copy_8_loop);
11209     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
11210     movdqu(Address(dst, len, Address::times_2), tmp1);
11211     addptr(len, 8);
11212     jcc(Assembler::notZero, copy_8_loop);
11213 
11214     bind(copy_tail);
11215     movl(len, tmp2);
11216 
11217     cmpl(len, 4);
11218     jccb(Assembler::less, copy_bytes);
11219 
11220     movdl(tmp1, Address(src, 0));  // load 4 byte chars
11221     pmovzxbw(tmp1, tmp1);
11222     movq(Address(dst, 0), tmp1);
11223     subptr(len, 4);
11224     addptr(src, 4);
11225     addptr(dst, 8);
11226 
11227     bind(copy_bytes);
11228   }
11229   testl(len, len);
11230   jccb(Assembler::zero, done);
11231   lea(src, Address(src, len, Address::times_1));
11232   lea(dst, Address(dst, len, Address::times_2));
11233   negptr(len);
11234 
11235   // inflate 1 char per iter
11236   bind(copy_chars_loop);
11237   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11238   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11239   increment(len);
11240   jcc(Assembler::notZero, copy_chars_loop);
11241 
11242   bind(done);
11243 }
11244 
11245 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11246   switch (cond) {
11247     // Note some conditions are synonyms for others
11248     case Assembler::zero:         return Assembler::notZero;
11249     case Assembler::notZero:      return Assembler::zero;
11250     case Assembler::less:         return Assembler::greaterEqual;
11251     case Assembler::lessEqual:    return Assembler::greater;
11252     case Assembler::greater:      return Assembler::lessEqual;
11253     case Assembler::greaterEqual: return Assembler::less;
11254     case Assembler::below:        return Assembler::aboveEqual;
11255     case Assembler::belowEqual:   return Assembler::above;
11256     case Assembler::above:        return Assembler::belowEqual;
11257     case Assembler::aboveEqual:   return Assembler::below;
11258     case Assembler::overflow:     return Assembler::noOverflow;
11259     case Assembler::noOverflow:   return Assembler::overflow;
11260     case Assembler::negative:     return Assembler::positive;
11261     case Assembler::positive:     return Assembler::negative;
11262     case Assembler::parity:       return Assembler::noParity;
11263     case Assembler::noParity:     return Assembler::parity;
11264   }
11265   ShouldNotReachHere(); return Assembler::overflow;
11266 }
11267 
11268 SkipIfEqual::SkipIfEqual(
11269     MacroAssembler* masm, const bool* flag_addr, bool value) {
11270   _masm = masm;
11271   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11272   _masm->jcc(Assembler::equal, _label);
11273 }
11274 
11275 SkipIfEqual::~SkipIfEqual() {
11276   _masm->bind(_label);
11277 }
11278 
11279 // 32-bit Windows has its own fast-path implementation
11280 // of get_thread
11281 #if !defined(WIN32) || defined(_LP64)
11282 
11283 // This is simply a call to Thread::current()
11284 void MacroAssembler::get_thread(Register thread) {
11285   if (thread != rax) {
11286     push(rax);
11287   }
11288   LP64_ONLY(push(rdi);)
11289   LP64_ONLY(push(rsi);)
11290   push(rdx);
11291   push(rcx);
11292 #ifdef _LP64
11293   push(r8);
11294   push(r9);
11295   push(r10);
11296   push(r11);
11297 #endif
11298 
11299   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11300 
11301 #ifdef _LP64
11302   pop(r11);
11303   pop(r10);
11304   pop(r9);
11305   pop(r8);
11306 #endif
11307   pop(rcx);
11308   pop(rdx);
11309   LP64_ONLY(pop(rsi);)
11310   LP64_ONLY(pop(rdi);)
11311   if (thread != rax) {
11312     mov(thread, rax);
11313     pop(rax);
11314   }
11315 }
11316 
11317 #endif
--- EOF ---