1 /*
   2  * Copyright (c) 1997, 2016, 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/methodHandles.hpp"
  36 #include "runtime/biasedLocking.hpp"
  37 #include "runtime/interfaceSupport.hpp"
  38 #include "runtime/objectMonitor.hpp"
  39 #include "runtime/os.hpp"
  40 #include "runtime/sharedRuntime.hpp"
  41 #include "runtime/stubRoutines.hpp"
  42 #include "runtime/thread.hpp"
  43 #include "utilities/macros.hpp"
  44 #if INCLUDE_ALL_GCS
  45 #include "gc/g1/g1CollectedHeap.inline.hpp"
  46 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  47 #include "gc/g1/heapRegion.hpp"
  48 #endif // INCLUDE_ALL_GCS
  49 #include "crc32c.h"
  50 #ifdef COMPILER2
  51 #include "opto/intrinsicnode.hpp"
  52 #endif
  53 
  54 #ifdef PRODUCT
  55 #define BLOCK_COMMENT(str) /* nothing */
  56 #define STOP(error) stop(error)
  57 #else
  58 #define BLOCK_COMMENT(str) block_comment(str)
  59 #define STOP(error) block_comment(error); stop(error)
  60 #endif
  61 
  62 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  63 
  64 #ifdef ASSERT
  65 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  66 #endif
  67 
  68 static Assembler::Condition reverse[] = {
  69     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  70     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  71     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  72     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  73     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  74     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  75     Assembler::above          /* belowEqual    = 0x6 */ ,
  76     Assembler::belowEqual     /* above         = 0x7 */ ,
  77     Assembler::positive       /* negative      = 0x8 */ ,
  78     Assembler::negative       /* positive      = 0x9 */ ,
  79     Assembler::noParity       /* parity        = 0xa */ ,
  80     Assembler::parity         /* noParity      = 0xb */ ,
  81     Assembler::greaterEqual   /* less          = 0xc */ ,
  82     Assembler::less           /* greaterEqual  = 0xd */ ,
  83     Assembler::greater        /* lessEqual     = 0xe */ ,
  84     Assembler::lessEqual      /* greater       = 0xf, */
  85 
  86 };
  87 
  88 
  89 // Implementation of MacroAssembler
  90 
  91 // First all the versions that have distinct versions depending on 32/64 bit
  92 // Unless the difference is trivial (1 line or so).
  93 
  94 #ifndef _LP64
  95 
  96 // 32bit versions
  97 
  98 Address MacroAssembler::as_Address(AddressLiteral adr) {
  99   return Address(adr.target(), adr.rspec());
 100 }
 101 
 102 Address MacroAssembler::as_Address(ArrayAddress adr) {
 103   return Address::make_array(adr);
 104 }
 105 
 106 void MacroAssembler::call_VM_leaf_base(address entry_point,
 107                                        int number_of_arguments) {
 108   call(RuntimeAddress(entry_point));
 109   increment(rsp, number_of_arguments * wordSize);
 110 }
 111 
 112 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 113   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 114 }
 115 
 116 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 117   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 118 }
 119 
 120 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 121   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 122 }
 123 
 124 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 125   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 126 }
 127 
 128 void MacroAssembler::extend_sign(Register hi, Register lo) {
 129   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 130   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 131     cdql();
 132   } else {
 133     movl(hi, lo);
 134     sarl(hi, 31);
 135   }
 136 }
 137 
 138 void MacroAssembler::jC2(Register tmp, Label& L) {
 139   // set parity bit if FPU flag C2 is set (via rax)
 140   save_rax(tmp);
 141   fwait(); fnstsw_ax();
 142   sahf();
 143   restore_rax(tmp);
 144   // branch
 145   jcc(Assembler::parity, L);
 146 }
 147 
 148 void MacroAssembler::jnC2(Register tmp, Label& L) {
 149   // set parity bit if FPU flag C2 is set (via rax)
 150   save_rax(tmp);
 151   fwait(); fnstsw_ax();
 152   sahf();
 153   restore_rax(tmp);
 154   // branch
 155   jcc(Assembler::noParity, L);
 156 }
 157 
 158 // 32bit can do a case table jump in one instruction but we no longer allow the base
 159 // to be installed in the Address class
 160 void MacroAssembler::jump(ArrayAddress entry) {
 161   jmp(as_Address(entry));
 162 }
 163 
 164 // Note: y_lo will be destroyed
 165 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 166   // Long compare for Java (semantics as described in JVM spec.)
 167   Label high, low, done;
 168 
 169   cmpl(x_hi, y_hi);
 170   jcc(Assembler::less, low);
 171   jcc(Assembler::greater, high);
 172   // x_hi is the return register
 173   xorl(x_hi, x_hi);
 174   cmpl(x_lo, y_lo);
 175   jcc(Assembler::below, low);
 176   jcc(Assembler::equal, done);
 177 
 178   bind(high);
 179   xorl(x_hi, x_hi);
 180   increment(x_hi);
 181   jmp(done);
 182 
 183   bind(low);
 184   xorl(x_hi, x_hi);
 185   decrementl(x_hi);
 186 
 187   bind(done);
 188 }
 189 
 190 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 191     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 192 }
 193 
 194 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 195   // leal(dst, as_Address(adr));
 196   // see note in movl as to why we must use a move
 197   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 198 }
 199 
 200 void MacroAssembler::leave() {
 201   mov(rsp, rbp);
 202   pop(rbp);
 203 }
 204 
 205 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 206   // Multiplication of two Java long values stored on the stack
 207   // as illustrated below. Result is in rdx:rax.
 208   //
 209   // rsp ---> [  ??  ] \               \
 210   //            ....    | y_rsp_offset  |
 211   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 212   //          [ y_hi ]                  | (in bytes)
 213   //            ....                    |
 214   //          [ x_lo ]                 /
 215   //          [ x_hi ]
 216   //            ....
 217   //
 218   // Basic idea: lo(result) = lo(x_lo * y_lo)
 219   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 220   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 221   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 222   Label quick;
 223   // load x_hi, y_hi and check if quick
 224   // multiplication is possible
 225   movl(rbx, x_hi);
 226   movl(rcx, y_hi);
 227   movl(rax, rbx);
 228   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 229   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 230   // do full multiplication
 231   // 1st step
 232   mull(y_lo);                                    // x_hi * y_lo
 233   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 234   // 2nd step
 235   movl(rax, x_lo);
 236   mull(rcx);                                     // x_lo * y_hi
 237   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 238   // 3rd step
 239   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 240   movl(rax, x_lo);
 241   mull(y_lo);                                    // x_lo * y_lo
 242   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 243 }
 244 
 245 void MacroAssembler::lneg(Register hi, Register lo) {
 246   negl(lo);
 247   adcl(hi, 0);
 248   negl(hi);
 249 }
 250 
 251 void MacroAssembler::lshl(Register hi, Register lo) {
 252   // Java shift left long support (semantics as described in JVM spec., p.305)
 253   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 254   // shift value is in rcx !
 255   assert(hi != rcx, "must not use rcx");
 256   assert(lo != rcx, "must not use rcx");
 257   const Register s = rcx;                        // shift count
 258   const int      n = BitsPerWord;
 259   Label L;
 260   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 261   cmpl(s, n);                                    // if (s < n)
 262   jcc(Assembler::less, L);                       // else (s >= n)
 263   movl(hi, lo);                                  // x := x << n
 264   xorl(lo, lo);
 265   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 266   bind(L);                                       // s (mod n) < n
 267   shldl(hi, lo);                                 // x := x << s
 268   shll(lo);
 269 }
 270 
 271 
 272 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 273   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 274   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 275   assert(hi != rcx, "must not use rcx");
 276   assert(lo != rcx, "must not use rcx");
 277   const Register s = rcx;                        // shift count
 278   const int      n = BitsPerWord;
 279   Label L;
 280   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 281   cmpl(s, n);                                    // if (s < n)
 282   jcc(Assembler::less, L);                       // else (s >= n)
 283   movl(lo, hi);                                  // x := x >> n
 284   if (sign_extension) sarl(hi, 31);
 285   else                xorl(hi, hi);
 286   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 287   bind(L);                                       // s (mod n) < n
 288   shrdl(lo, hi);                                 // x := x >> s
 289   if (sign_extension) sarl(hi);
 290   else                shrl(hi);
 291 }
 292 
 293 void MacroAssembler::movoop(Register dst, jobject obj) {
 294   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 295 }
 296 
 297 void MacroAssembler::movoop(Address dst, jobject obj) {
 298   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 299 }
 300 
 301 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 302   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 303 }
 304 
 305 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 306   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 307 }
 308 
 309 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 310   // scratch register is not used,
 311   // it is defined to match parameters of 64-bit version of this method.
 312   if (src.is_lval()) {
 313     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 314   } else {
 315     movl(dst, as_Address(src));
 316   }
 317 }
 318 
 319 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 320   movl(as_Address(dst), src);
 321 }
 322 
 323 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 324   movl(dst, as_Address(src));
 325 }
 326 
 327 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 328 void MacroAssembler::movptr(Address dst, intptr_t src) {
 329   movl(dst, src);
 330 }
 331 
 332 
 333 void MacroAssembler::pop_callee_saved_registers() {
 334   pop(rcx);
 335   pop(rdx);
 336   pop(rdi);
 337   pop(rsi);
 338 }
 339 
 340 void MacroAssembler::pop_fTOS() {
 341   fld_d(Address(rsp, 0));
 342   addl(rsp, 2 * wordSize);
 343 }
 344 
 345 void MacroAssembler::push_callee_saved_registers() {
 346   push(rsi);
 347   push(rdi);
 348   push(rdx);
 349   push(rcx);
 350 }
 351 
 352 void MacroAssembler::push_fTOS() {
 353   subl(rsp, 2 * wordSize);
 354   fstp_d(Address(rsp, 0));
 355 }
 356 
 357 
 358 void MacroAssembler::pushoop(jobject obj) {
 359   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 360 }
 361 
 362 void MacroAssembler::pushklass(Metadata* obj) {
 363   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 364 }
 365 
 366 void MacroAssembler::pushptr(AddressLiteral src) {
 367   if (src.is_lval()) {
 368     push_literal32((int32_t)src.target(), src.rspec());
 369   } else {
 370     pushl(as_Address(src));
 371   }
 372 }
 373 
 374 void MacroAssembler::set_word_if_not_zero(Register dst) {
 375   xorl(dst, dst);
 376   set_byte_if_not_zero(dst);
 377 }
 378 
 379 static void pass_arg0(MacroAssembler* masm, Register arg) {
 380   masm->push(arg);
 381 }
 382 
 383 static void pass_arg1(MacroAssembler* masm, Register arg) {
 384   masm->push(arg);
 385 }
 386 
 387 static void pass_arg2(MacroAssembler* masm, Register arg) {
 388   masm->push(arg);
 389 }
 390 
 391 static void pass_arg3(MacroAssembler* masm, Register arg) {
 392   masm->push(arg);
 393 }
 394 
 395 #ifndef PRODUCT
 396 extern "C" void findpc(intptr_t x);
 397 #endif
 398 
 399 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 400   // In order to get locks to work, we need to fake a in_VM state
 401   JavaThread* thread = JavaThread::current();
 402   JavaThreadState saved_state = thread->thread_state();
 403   thread->set_thread_state(_thread_in_vm);
 404   if (ShowMessageBoxOnError) {
 405     JavaThread* thread = JavaThread::current();
 406     JavaThreadState saved_state = thread->thread_state();
 407     thread->set_thread_state(_thread_in_vm);
 408     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 409       ttyLocker ttyl;
 410       BytecodeCounter::print();
 411     }
 412     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 413     // This is the value of eip which points to where verify_oop will return.
 414     if (os::message_box(msg, "Execution stopped, print registers?")) {
 415       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 416       BREAKPOINT;
 417     }
 418   } else {
 419     ttyLocker ttyl;
 420     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 421   }
 422   // Don't assert holding the ttyLock
 423     assert(false, "DEBUG MESSAGE: %s", msg);
 424   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 425 }
 426 
 427 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 428   ttyLocker ttyl;
 429   FlagSetting fs(Debugging, true);
 430   tty->print_cr("eip = 0x%08x", eip);
 431 #ifndef PRODUCT
 432   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 433     tty->cr();
 434     findpc(eip);
 435     tty->cr();
 436   }
 437 #endif
 438 #define PRINT_REG(rax) \
 439   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 440   PRINT_REG(rax);
 441   PRINT_REG(rbx);
 442   PRINT_REG(rcx);
 443   PRINT_REG(rdx);
 444   PRINT_REG(rdi);
 445   PRINT_REG(rsi);
 446   PRINT_REG(rbp);
 447   PRINT_REG(rsp);
 448 #undef PRINT_REG
 449   // Print some words near top of staack.
 450   int* dump_sp = (int*) rsp;
 451   for (int col1 = 0; col1 < 8; col1++) {
 452     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 453     os::print_location(tty, *dump_sp++);
 454   }
 455   for (int row = 0; row < 16; row++) {
 456     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 457     for (int col = 0; col < 8; col++) {
 458       tty->print(" 0x%08x", *dump_sp++);
 459     }
 460     tty->cr();
 461   }
 462   // Print some instructions around pc:
 463   Disassembler::decode((address)eip-64, (address)eip);
 464   tty->print_cr("--------");
 465   Disassembler::decode((address)eip, (address)eip+32);
 466 }
 467 
 468 void MacroAssembler::stop(const char* msg) {
 469   ExternalAddress message((address)msg);
 470   // push address of message
 471   pushptr(message.addr());
 472   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 473   pusha();                                            // push registers
 474   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 475   hlt();
 476 }
 477 
 478 void MacroAssembler::warn(const char* msg) {
 479   push_CPU_state();
 480 
 481   ExternalAddress message((address) msg);
 482   // push address of message
 483   pushptr(message.addr());
 484 
 485   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 486   addl(rsp, wordSize);       // discard argument
 487   pop_CPU_state();
 488 }
 489 
 490 void MacroAssembler::print_state() {
 491   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 492   pusha();                                            // push registers
 493 
 494   push_CPU_state();
 495   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 496   pop_CPU_state();
 497 
 498   popa();
 499   addl(rsp, wordSize);
 500 }
 501 
 502 #else // _LP64
 503 
 504 // 64 bit versions
 505 
 506 Address MacroAssembler::as_Address(AddressLiteral adr) {
 507   // amd64 always does this as a pc-rel
 508   // we can be absolute or disp based on the instruction type
 509   // jmp/call are displacements others are absolute
 510   assert(!adr.is_lval(), "must be rval");
 511   assert(reachable(adr), "must be");
 512   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 513 
 514 }
 515 
 516 Address MacroAssembler::as_Address(ArrayAddress adr) {
 517   AddressLiteral base = adr.base();
 518   lea(rscratch1, base);
 519   Address index = adr.index();
 520   assert(index._disp == 0, "must not have disp"); // maybe it can?
 521   Address array(rscratch1, index._index, index._scale, index._disp);
 522   return array;
 523 }
 524 
 525 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 526   Label L, E;
 527 
 528 #ifdef _WIN64
 529   // Windows always allocates space for it's register args
 530   assert(num_args <= 4, "only register arguments supported");
 531   subq(rsp,  frame::arg_reg_save_area_bytes);
 532 #endif
 533 
 534   // Align stack if necessary
 535   testl(rsp, 15);
 536   jcc(Assembler::zero, L);
 537 
 538   subq(rsp, 8);
 539   {
 540     call(RuntimeAddress(entry_point));
 541   }
 542   addq(rsp, 8);
 543   jmp(E);
 544 
 545   bind(L);
 546   {
 547     call(RuntimeAddress(entry_point));
 548   }
 549 
 550   bind(E);
 551 
 552 #ifdef _WIN64
 553   // restore stack pointer
 554   addq(rsp, frame::arg_reg_save_area_bytes);
 555 #endif
 556 
 557 }
 558 
 559 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 560   assert(!src2.is_lval(), "should use cmpptr");
 561 
 562   if (reachable(src2)) {
 563     cmpq(src1, as_Address(src2));
 564   } else {
 565     lea(rscratch1, src2);
 566     Assembler::cmpq(src1, Address(rscratch1, 0));
 567   }
 568 }
 569 
 570 int MacroAssembler::corrected_idivq(Register reg) {
 571   // Full implementation of Java ldiv and lrem; checks for special
 572   // case as described in JVM spec., p.243 & p.271.  The function
 573   // returns the (pc) offset of the idivl instruction - may be needed
 574   // for implicit exceptions.
 575   //
 576   //         normal case                           special case
 577   //
 578   // input : rax: dividend                         min_long
 579   //         reg: divisor   (may not be eax/edx)   -1
 580   //
 581   // output: rax: quotient  (= rax idiv reg)       min_long
 582   //         rdx: remainder (= rax irem reg)       0
 583   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 584   static const int64_t min_long = 0x8000000000000000;
 585   Label normal_case, special_case;
 586 
 587   // check for special case
 588   cmp64(rax, ExternalAddress((address) &min_long));
 589   jcc(Assembler::notEqual, normal_case);
 590   xorl(rdx, rdx); // prepare rdx for possible special case (where
 591                   // remainder = 0)
 592   cmpq(reg, -1);
 593   jcc(Assembler::equal, special_case);
 594 
 595   // handle normal case
 596   bind(normal_case);
 597   cdqq();
 598   int idivq_offset = offset();
 599   idivq(reg);
 600 
 601   // normal and special case exit
 602   bind(special_case);
 603 
 604   return idivq_offset;
 605 }
 606 
 607 void MacroAssembler::decrementq(Register reg, int value) {
 608   if (value == min_jint) { subq(reg, value); return; }
 609   if (value <  0) { incrementq(reg, -value); return; }
 610   if (value == 0) {                        ; return; }
 611   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 612   /* else */      { subq(reg, value)       ; return; }
 613 }
 614 
 615 void MacroAssembler::decrementq(Address dst, int value) {
 616   if (value == min_jint) { subq(dst, value); return; }
 617   if (value <  0) { incrementq(dst, -value); return; }
 618   if (value == 0) {                        ; return; }
 619   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 620   /* else */      { subq(dst, value)       ; return; }
 621 }
 622 
 623 void MacroAssembler::incrementq(AddressLiteral dst) {
 624   if (reachable(dst)) {
 625     incrementq(as_Address(dst));
 626   } else {
 627     lea(rscratch1, dst);
 628     incrementq(Address(rscratch1, 0));
 629   }
 630 }
 631 
 632 void MacroAssembler::incrementq(Register reg, int value) {
 633   if (value == min_jint) { addq(reg, value); return; }
 634   if (value <  0) { decrementq(reg, -value); return; }
 635   if (value == 0) {                        ; return; }
 636   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 637   /* else */      { addq(reg, value)       ; return; }
 638 }
 639 
 640 void MacroAssembler::incrementq(Address dst, int value) {
 641   if (value == min_jint) { addq(dst, value); return; }
 642   if (value <  0) { decrementq(dst, -value); return; }
 643   if (value == 0) {                        ; return; }
 644   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 645   /* else */      { addq(dst, value)       ; return; }
 646 }
 647 
 648 // 32bit can do a case table jump in one instruction but we no longer allow the base
 649 // to be installed in the Address class
 650 void MacroAssembler::jump(ArrayAddress entry) {
 651   lea(rscratch1, entry.base());
 652   Address dispatch = entry.index();
 653   assert(dispatch._base == noreg, "must be");
 654   dispatch._base = rscratch1;
 655   jmp(dispatch);
 656 }
 657 
 658 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 659   ShouldNotReachHere(); // 64bit doesn't use two regs
 660   cmpq(x_lo, y_lo);
 661 }
 662 
 663 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 664     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 665 }
 666 
 667 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 668   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 669   movptr(dst, rscratch1);
 670 }
 671 
 672 void MacroAssembler::leave() {
 673   // %%% is this really better? Why not on 32bit too?
 674   emit_int8((unsigned char)0xC9); // LEAVE
 675 }
 676 
 677 void MacroAssembler::lneg(Register hi, Register lo) {
 678   ShouldNotReachHere(); // 64bit doesn't use two regs
 679   negq(lo);
 680 }
 681 
 682 void MacroAssembler::movoop(Register dst, jobject obj) {
 683   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 684 }
 685 
 686 void MacroAssembler::movoop(Address dst, jobject obj) {
 687   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 688   movq(dst, rscratch1);
 689 }
 690 
 691 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 692   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 693 }
 694 
 695 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 696   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 697   movq(dst, rscratch1);
 698 }
 699 
 700 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 701   if (src.is_lval()) {
 702     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 703   } else {
 704     if (reachable(src)) {
 705       movq(dst, as_Address(src));
 706     } else {
 707       lea(scratch, src);
 708       movq(dst, Address(scratch, 0));
 709     }
 710   }
 711 }
 712 
 713 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 714   movq(as_Address(dst), src);
 715 }
 716 
 717 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 718   movq(dst, as_Address(src));
 719 }
 720 
 721 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 722 void MacroAssembler::movptr(Address dst, intptr_t src) {
 723   mov64(rscratch1, src);
 724   movq(dst, rscratch1);
 725 }
 726 
 727 // These are mostly for initializing NULL
 728 void MacroAssembler::movptr(Address dst, int32_t src) {
 729   movslq(dst, src);
 730 }
 731 
 732 void MacroAssembler::movptr(Register dst, int32_t src) {
 733   mov64(dst, (intptr_t)src);
 734 }
 735 
 736 void MacroAssembler::pushoop(jobject obj) {
 737   movoop(rscratch1, obj);
 738   push(rscratch1);
 739 }
 740 
 741 void MacroAssembler::pushklass(Metadata* obj) {
 742   mov_metadata(rscratch1, obj);
 743   push(rscratch1);
 744 }
 745 
 746 void MacroAssembler::pushptr(AddressLiteral src) {
 747   lea(rscratch1, src);
 748   if (src.is_lval()) {
 749     push(rscratch1);
 750   } else {
 751     pushq(Address(rscratch1, 0));
 752   }
 753 }
 754 
 755 void MacroAssembler::reset_last_Java_frame(bool clear_fp,
 756                                            bool clear_pc) {
 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   if (clear_pc) {
 766     movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 767   }
 768 }
 769 
 770 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 771                                          Register last_java_fp,
 772                                          address  last_java_pc) {
 773   // determine last_java_sp register
 774   if (!last_java_sp->is_valid()) {
 775     last_java_sp = rsp;
 776   }
 777 
 778   // last_java_fp is optional
 779   if (last_java_fp->is_valid()) {
 780     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 781            last_java_fp);
 782   }
 783 
 784   // last_java_pc is optional
 785   if (last_java_pc != NULL) {
 786     Address java_pc(r15_thread,
 787                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 788     lea(rscratch1, InternalAddress(last_java_pc));
 789     movptr(java_pc, rscratch1);
 790   }
 791 
 792   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 793 }
 794 
 795 static void pass_arg0(MacroAssembler* masm, Register arg) {
 796   if (c_rarg0 != arg ) {
 797     masm->mov(c_rarg0, arg);
 798   }
 799 }
 800 
 801 static void pass_arg1(MacroAssembler* masm, Register arg) {
 802   if (c_rarg1 != arg ) {
 803     masm->mov(c_rarg1, arg);
 804   }
 805 }
 806 
 807 static void pass_arg2(MacroAssembler* masm, Register arg) {
 808   if (c_rarg2 != arg ) {
 809     masm->mov(c_rarg2, arg);
 810   }
 811 }
 812 
 813 static void pass_arg3(MacroAssembler* masm, Register arg) {
 814   if (c_rarg3 != arg ) {
 815     masm->mov(c_rarg3, arg);
 816   }
 817 }
 818 
 819 void MacroAssembler::stop(const char* msg) {
 820   address rip = pc();
 821   pusha(); // get regs on stack
 822   lea(c_rarg0, ExternalAddress((address) msg));
 823   lea(c_rarg1, InternalAddress(rip));
 824   movq(c_rarg2, rsp); // pass pointer to regs array
 825   andq(rsp, -16); // align stack as required by ABI
 826   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 827   hlt();
 828 }
 829 
 830 void MacroAssembler::warn(const char* msg) {
 831   push(rbp);
 832   movq(rbp, rsp);
 833   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 834   push_CPU_state();   // keeps alignment at 16 bytes
 835   lea(c_rarg0, ExternalAddress((address) msg));
 836   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 837   pop_CPU_state();
 838   mov(rsp, rbp);
 839   pop(rbp);
 840 }
 841 
 842 void MacroAssembler::print_state() {
 843   address rip = pc();
 844   pusha();            // get regs on stack
 845   push(rbp);
 846   movq(rbp, rsp);
 847   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 848   push_CPU_state();   // keeps alignment at 16 bytes
 849 
 850   lea(c_rarg0, InternalAddress(rip));
 851   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 852   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 853 
 854   pop_CPU_state();
 855   mov(rsp, rbp);
 856   pop(rbp);
 857   popa();
 858 }
 859 
 860 #ifndef PRODUCT
 861 extern "C" void findpc(intptr_t x);
 862 #endif
 863 
 864 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 865   // In order to get locks to work, we need to fake a in_VM state
 866   if (ShowMessageBoxOnError) {
 867     JavaThread* thread = JavaThread::current();
 868     JavaThreadState saved_state = thread->thread_state();
 869     thread->set_thread_state(_thread_in_vm);
 870 #ifndef PRODUCT
 871     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 872       ttyLocker ttyl;
 873       BytecodeCounter::print();
 874     }
 875 #endif
 876     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 877     // XXX correct this offset for amd64
 878     // This is the value of eip which points to where verify_oop will return.
 879     if (os::message_box(msg, "Execution stopped, print registers?")) {
 880       print_state64(pc, regs);
 881       BREAKPOINT;
 882       assert(false, "start up GDB");
 883     }
 884     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 885   } else {
 886     ttyLocker ttyl;
 887     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 888                     msg);
 889     assert(false, "DEBUG MESSAGE: %s", msg);
 890   }
 891 }
 892 
 893 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 894   ttyLocker ttyl;
 895   FlagSetting fs(Debugging, true);
 896   tty->print_cr("rip = 0x%016lx", pc);
 897 #ifndef PRODUCT
 898   tty->cr();
 899   findpc(pc);
 900   tty->cr();
 901 #endif
 902 #define PRINT_REG(rax, value) \
 903   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 904   PRINT_REG(rax, regs[15]);
 905   PRINT_REG(rbx, regs[12]);
 906   PRINT_REG(rcx, regs[14]);
 907   PRINT_REG(rdx, regs[13]);
 908   PRINT_REG(rdi, regs[8]);
 909   PRINT_REG(rsi, regs[9]);
 910   PRINT_REG(rbp, regs[10]);
 911   PRINT_REG(rsp, regs[11]);
 912   PRINT_REG(r8 , regs[7]);
 913   PRINT_REG(r9 , regs[6]);
 914   PRINT_REG(r10, regs[5]);
 915   PRINT_REG(r11, regs[4]);
 916   PRINT_REG(r12, regs[3]);
 917   PRINT_REG(r13, regs[2]);
 918   PRINT_REG(r14, regs[1]);
 919   PRINT_REG(r15, regs[0]);
 920 #undef PRINT_REG
 921   // Print some words near top of staack.
 922   int64_t* rsp = (int64_t*) regs[11];
 923   int64_t* dump_sp = rsp;
 924   for (int col1 = 0; col1 < 8; col1++) {
 925     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 926     os::print_location(tty, *dump_sp++);
 927   }
 928   for (int row = 0; row < 25; row++) {
 929     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 930     for (int col = 0; col < 4; col++) {
 931       tty->print(" 0x%016lx", *dump_sp++);
 932     }
 933     tty->cr();
 934   }
 935   // Print some instructions around pc:
 936   Disassembler::decode((address)pc-64, (address)pc);
 937   tty->print_cr("--------");
 938   Disassembler::decode((address)pc, (address)pc+32);
 939 }
 940 
 941 #endif // _LP64
 942 
 943 // Now versions that are common to 32/64 bit
 944 
 945 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 946   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 947 }
 948 
 949 void MacroAssembler::addptr(Register dst, Register src) {
 950   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 951 }
 952 
 953 void MacroAssembler::addptr(Address dst, Register src) {
 954   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 955 }
 956 
 957 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 958   if (reachable(src)) {
 959     Assembler::addsd(dst, as_Address(src));
 960   } else {
 961     lea(rscratch1, src);
 962     Assembler::addsd(dst, Address(rscratch1, 0));
 963   }
 964 }
 965 
 966 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 967   if (reachable(src)) {
 968     addss(dst, as_Address(src));
 969   } else {
 970     lea(rscratch1, src);
 971     addss(dst, Address(rscratch1, 0));
 972   }
 973 }
 974 
 975 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 976   if (reachable(src)) {
 977     Assembler::addpd(dst, as_Address(src));
 978   } else {
 979     lea(rscratch1, src);
 980     Assembler::addpd(dst, Address(rscratch1, 0));
 981   }
 982 }
 983 
 984 void MacroAssembler::align(int modulus) {
 985   align(modulus, offset());
 986 }
 987 
 988 void MacroAssembler::align(int modulus, int target) {
 989   if (target % modulus != 0) {
 990     nop(modulus - (target % modulus));
 991   }
 992 }
 993 
 994 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 995   // Used in sign-masking with aligned address.
 996   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 997   if (reachable(src)) {
 998     Assembler::andpd(dst, as_Address(src));
 999   } else {
1000     lea(rscratch1, src);
1001     Assembler::andpd(dst, Address(rscratch1, 0));
1002   }
1003 }
1004 
1005 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1006   // Used in sign-masking with aligned address.
1007   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1008   if (reachable(src)) {
1009     Assembler::andps(dst, as_Address(src));
1010   } else {
1011     lea(rscratch1, src);
1012     Assembler::andps(dst, Address(rscratch1, 0));
1013   }
1014 }
1015 
1016 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1017   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1018 }
1019 
1020 void MacroAssembler::atomic_incl(Address counter_addr) {
1021   if (os::is_MP())
1022     lock();
1023   incrementl(counter_addr);
1024 }
1025 
1026 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1027   if (reachable(counter_addr)) {
1028     atomic_incl(as_Address(counter_addr));
1029   } else {
1030     lea(scr, counter_addr);
1031     atomic_incl(Address(scr, 0));
1032   }
1033 }
1034 
1035 #ifdef _LP64
1036 void MacroAssembler::atomic_incq(Address counter_addr) {
1037   if (os::is_MP())
1038     lock();
1039   incrementq(counter_addr);
1040 }
1041 
1042 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1043   if (reachable(counter_addr)) {
1044     atomic_incq(as_Address(counter_addr));
1045   } else {
1046     lea(scr, counter_addr);
1047     atomic_incq(Address(scr, 0));
1048   }
1049 }
1050 #endif
1051 
1052 // Writes to stack successive pages until offset reached to check for
1053 // stack overflow + shadow pages.  This clobbers tmp.
1054 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1055   movptr(tmp, rsp);
1056   // Bang stack for total size given plus shadow page size.
1057   // Bang one page at a time because large size can bang beyond yellow and
1058   // red zones.
1059   Label loop;
1060   bind(loop);
1061   movl(Address(tmp, (-os::vm_page_size())), size );
1062   subptr(tmp, os::vm_page_size());
1063   subl(size, os::vm_page_size());
1064   jcc(Assembler::greater, loop);
1065 
1066   // Bang down shadow pages too.
1067   // At this point, (tmp-0) is the last address touched, so don't
1068   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1069   // was post-decremented.)  Skip this address by starting at i=1, and
1070   // touch a few more pages below.  N.B.  It is important to touch all
1071   // the way down including all pages in the shadow zone.
1072   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1073     // this could be any sized move but this is can be a debugging crumb
1074     // so the bigger the better.
1075     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1076   }
1077 }
1078 
1079 void MacroAssembler::reserved_stack_check() {
1080     // testing if reserved zone needs to be enabled
1081     Label no_reserved_zone_enabling;
1082     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1083     NOT_LP64(get_thread(rsi);)
1084 
1085     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1086     jcc(Assembler::below, no_reserved_zone_enabling);
1087 
1088     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1089     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1090     should_not_reach_here();
1091 
1092     bind(no_reserved_zone_enabling);
1093 }
1094 
1095 int MacroAssembler::biased_locking_enter(Register lock_reg,
1096                                          Register obj_reg,
1097                                          Register swap_reg,
1098                                          Register tmp_reg,
1099                                          bool swap_reg_contains_mark,
1100                                          Label& done,
1101                                          Label* slow_case,
1102                                          BiasedLockingCounters* counters) {
1103   assert(UseBiasedLocking, "why call this otherwise?");
1104   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1105   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1106   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1107   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1108   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1109   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1110 
1111   if (PrintBiasedLockingStatistics && counters == NULL) {
1112     counters = BiasedLocking::counters();
1113   }
1114   // Biased locking
1115   // See whether the lock is currently biased toward our thread and
1116   // whether the epoch is still valid
1117   // Note that the runtime guarantees sufficient alignment of JavaThread
1118   // pointers to allow age to be placed into low bits
1119   // First check to see whether biasing is even enabled for this object
1120   Label cas_label;
1121   int null_check_offset = -1;
1122   if (!swap_reg_contains_mark) {
1123     null_check_offset = offset();
1124     movptr(swap_reg, mark_addr);
1125   }
1126   movptr(tmp_reg, swap_reg);
1127   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1128   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1129   jcc(Assembler::notEqual, cas_label);
1130   // The bias pattern is present in the object's header. Need to check
1131   // whether the bias owner and the epoch are both still current.
1132 #ifndef _LP64
1133   // Note that because there is no current thread register on x86_32 we
1134   // need to store off the mark word we read out of the object to
1135   // avoid reloading it and needing to recheck invariants below. This
1136   // store is unfortunate but it makes the overall code shorter and
1137   // simpler.
1138   movptr(saved_mark_addr, swap_reg);
1139 #endif
1140   if (swap_reg_contains_mark) {
1141     null_check_offset = offset();
1142   }
1143   load_prototype_header(tmp_reg, obj_reg);
1144 #ifdef _LP64
1145   orptr(tmp_reg, r15_thread);
1146   xorptr(tmp_reg, swap_reg);
1147   Register header_reg = tmp_reg;
1148 #else
1149   xorptr(tmp_reg, swap_reg);
1150   get_thread(swap_reg);
1151   xorptr(swap_reg, tmp_reg);
1152   Register header_reg = swap_reg;
1153 #endif
1154   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1155   if (counters != NULL) {
1156     cond_inc32(Assembler::zero,
1157                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1158   }
1159   jcc(Assembler::equal, done);
1160 
1161   Label try_revoke_bias;
1162   Label try_rebias;
1163 
1164   // At this point we know that the header has the bias pattern and
1165   // that we are not the bias owner in the current epoch. We need to
1166   // figure out more details about the state of the header in order to
1167   // know what operations can be legally performed on the object's
1168   // header.
1169 
1170   // If the low three bits in the xor result aren't clear, that means
1171   // the prototype header is no longer biased and we have to revoke
1172   // the bias on this object.
1173   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1174   jccb(Assembler::notZero, try_revoke_bias);
1175 
1176   // Biasing is still enabled for this data type. See whether the
1177   // epoch of the current bias is still valid, meaning that the epoch
1178   // bits of the mark word are equal to the epoch bits of the
1179   // prototype header. (Note that the prototype header's epoch bits
1180   // only change at a safepoint.) If not, attempt to rebias the object
1181   // toward the current thread. Note that we must be absolutely sure
1182   // that the current epoch is invalid in order to do this because
1183   // otherwise the manipulations it performs on the mark word are
1184   // illegal.
1185   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1186   jccb(Assembler::notZero, try_rebias);
1187 
1188   // The epoch of the current bias is still valid but we know nothing
1189   // about the owner; it might be set or it might be clear. Try to
1190   // acquire the bias of the object using an atomic operation. If this
1191   // fails we will go in to the runtime to revoke the object's bias.
1192   // Note that we first construct the presumed unbiased header so we
1193   // don't accidentally blow away another thread's valid bias.
1194   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1195   andptr(swap_reg,
1196          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1197 #ifdef _LP64
1198   movptr(tmp_reg, swap_reg);
1199   orptr(tmp_reg, r15_thread);
1200 #else
1201   get_thread(tmp_reg);
1202   orptr(tmp_reg, swap_reg);
1203 #endif
1204   if (os::is_MP()) {
1205     lock();
1206   }
1207   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1208   // If the biasing toward our thread failed, this means that
1209   // another thread succeeded in biasing it toward itself and we
1210   // need to revoke that bias. The revocation will occur in the
1211   // interpreter runtime in the slow case.
1212   if (counters != NULL) {
1213     cond_inc32(Assembler::zero,
1214                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1215   }
1216   if (slow_case != NULL) {
1217     jcc(Assembler::notZero, *slow_case);
1218   }
1219   jmp(done);
1220 
1221   bind(try_rebias);
1222   // At this point we know the epoch has expired, meaning that the
1223   // current "bias owner", if any, is actually invalid. Under these
1224   // circumstances _only_, we are allowed to use the current header's
1225   // value as the comparison value when doing the cas to acquire the
1226   // bias in the current epoch. In other words, we allow transfer of
1227   // the bias from one thread to another directly in this situation.
1228   //
1229   // FIXME: due to a lack of registers we currently blow away the age
1230   // bits in this situation. Should attempt to preserve them.
1231   load_prototype_header(tmp_reg, obj_reg);
1232 #ifdef _LP64
1233   orptr(tmp_reg, r15_thread);
1234 #else
1235   get_thread(swap_reg);
1236   orptr(tmp_reg, swap_reg);
1237   movptr(swap_reg, saved_mark_addr);
1238 #endif
1239   if (os::is_MP()) {
1240     lock();
1241   }
1242   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1243   // If the biasing toward our thread failed, then another thread
1244   // succeeded in biasing it toward itself and we need to revoke that
1245   // bias. The revocation will occur in the runtime in the slow case.
1246   if (counters != NULL) {
1247     cond_inc32(Assembler::zero,
1248                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1249   }
1250   if (slow_case != NULL) {
1251     jcc(Assembler::notZero, *slow_case);
1252   }
1253   jmp(done);
1254 
1255   bind(try_revoke_bias);
1256   // The prototype mark in the klass doesn't have the bias bit set any
1257   // more, indicating that objects of this data type are not supposed
1258   // to be biased any more. We are going to try to reset the mark of
1259   // this object to the prototype value and fall through to the
1260   // CAS-based locking scheme. Note that if our CAS fails, it means
1261   // that another thread raced us for the privilege of revoking the
1262   // bias of this particular object, so it's okay to continue in the
1263   // normal locking code.
1264   //
1265   // FIXME: due to a lack of registers we currently blow away the age
1266   // bits in this situation. Should attempt to preserve them.
1267   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1268   load_prototype_header(tmp_reg, obj_reg);
1269   if (os::is_MP()) {
1270     lock();
1271   }
1272   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1273   // Fall through to the normal CAS-based lock, because no matter what
1274   // the result of the above CAS, some thread must have succeeded in
1275   // removing the bias bit from the object's header.
1276   if (counters != NULL) {
1277     cond_inc32(Assembler::zero,
1278                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1279   }
1280 
1281   bind(cas_label);
1282 
1283   return null_check_offset;
1284 }
1285 
1286 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1287   assert(UseBiasedLocking, "why call this otherwise?");
1288 
1289   // Check for biased locking unlock case, which is a no-op
1290   // Note: we do not have to check the thread ID for two reasons.
1291   // First, the interpreter checks for IllegalMonitorStateException at
1292   // a higher level. Second, if the bias was revoked while we held the
1293   // lock, the object could not be rebiased toward another thread, so
1294   // the bias bit would be clear.
1295   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1296   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1297   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1298   jcc(Assembler::equal, done);
1299 }
1300 
1301 #ifdef COMPILER2
1302 
1303 #if INCLUDE_RTM_OPT
1304 
1305 // Update rtm_counters based on abort status
1306 // input: abort_status
1307 //        rtm_counters (RTMLockingCounters*)
1308 // flags are killed
1309 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1310 
1311   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1312   if (PrintPreciseRTMLockingStatistics) {
1313     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1314       Label check_abort;
1315       testl(abort_status, (1<<i));
1316       jccb(Assembler::equal, check_abort);
1317       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1318       bind(check_abort);
1319     }
1320   }
1321 }
1322 
1323 // Branch if (random & (count-1) != 0), count is 2^n
1324 // tmp, scr and flags are killed
1325 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1326   assert(tmp == rax, "");
1327   assert(scr == rdx, "");
1328   rdtsc(); // modifies EDX:EAX
1329   andptr(tmp, count-1);
1330   jccb(Assembler::notZero, brLabel);
1331 }
1332 
1333 // Perform abort ratio calculation, set no_rtm bit if high ratio
1334 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1335 // tmpReg, rtm_counters_Reg and flags are killed
1336 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1337                                                  Register rtm_counters_Reg,
1338                                                  RTMLockingCounters* rtm_counters,
1339                                                  Metadata* method_data) {
1340   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1341 
1342   if (RTMLockingCalculationDelay > 0) {
1343     // Delay calculation
1344     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1345     testptr(tmpReg, tmpReg);
1346     jccb(Assembler::equal, L_done);
1347   }
1348   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1349   //   Aborted transactions = abort_count * 100
1350   //   All transactions = total_count *  RTMTotalCountIncrRate
1351   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1352 
1353   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1354   cmpptr(tmpReg, RTMAbortThreshold);
1355   jccb(Assembler::below, L_check_always_rtm2);
1356   imulptr(tmpReg, tmpReg, 100);
1357 
1358   Register scrReg = rtm_counters_Reg;
1359   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1360   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1361   imulptr(scrReg, scrReg, RTMAbortRatio);
1362   cmpptr(tmpReg, scrReg);
1363   jccb(Assembler::below, L_check_always_rtm1);
1364   if (method_data != NULL) {
1365     // set rtm_state to "no rtm" in MDO
1366     mov_metadata(tmpReg, method_data);
1367     if (os::is_MP()) {
1368       lock();
1369     }
1370     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1371   }
1372   jmpb(L_done);
1373   bind(L_check_always_rtm1);
1374   // Reload RTMLockingCounters* address
1375   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1376   bind(L_check_always_rtm2);
1377   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1378   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1379   jccb(Assembler::below, L_done);
1380   if (method_data != NULL) {
1381     // set rtm_state to "always rtm" in MDO
1382     mov_metadata(tmpReg, method_data);
1383     if (os::is_MP()) {
1384       lock();
1385     }
1386     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1387   }
1388   bind(L_done);
1389 }
1390 
1391 // Update counters and perform abort ratio calculation
1392 // input:  abort_status_Reg
1393 // rtm_counters_Reg, flags are killed
1394 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1395                                    Register rtm_counters_Reg,
1396                                    RTMLockingCounters* rtm_counters,
1397                                    Metadata* method_data,
1398                                    bool profile_rtm) {
1399 
1400   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1401   // update rtm counters based on rax value at abort
1402   // reads abort_status_Reg, updates flags
1403   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1404   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1405   if (profile_rtm) {
1406     // Save abort status because abort_status_Reg is used by following code.
1407     if (RTMRetryCount > 0) {
1408       push(abort_status_Reg);
1409     }
1410     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1411     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1412     // restore abort status
1413     if (RTMRetryCount > 0) {
1414       pop(abort_status_Reg);
1415     }
1416   }
1417 }
1418 
1419 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1420 // inputs: retry_count_Reg
1421 //       : abort_status_Reg
1422 // output: retry_count_Reg decremented by 1
1423 // flags are killed
1424 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1425   Label doneRetry;
1426   assert(abort_status_Reg == rax, "");
1427   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1428   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1429   // if reason is in 0x6 and retry count != 0 then retry
1430   andptr(abort_status_Reg, 0x6);
1431   jccb(Assembler::zero, doneRetry);
1432   testl(retry_count_Reg, retry_count_Reg);
1433   jccb(Assembler::zero, doneRetry);
1434   pause();
1435   decrementl(retry_count_Reg);
1436   jmp(retryLabel);
1437   bind(doneRetry);
1438 }
1439 
1440 // Spin and retry if lock is busy,
1441 // inputs: box_Reg (monitor address)
1442 //       : retry_count_Reg
1443 // output: retry_count_Reg decremented by 1
1444 //       : clear z flag if retry count exceeded
1445 // tmp_Reg, scr_Reg, flags are killed
1446 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1447                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1448   Label SpinLoop, SpinExit, doneRetry;
1449   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1450 
1451   testl(retry_count_Reg, retry_count_Reg);
1452   jccb(Assembler::zero, doneRetry);
1453   decrementl(retry_count_Reg);
1454   movptr(scr_Reg, RTMSpinLoopCount);
1455 
1456   bind(SpinLoop);
1457   pause();
1458   decrementl(scr_Reg);
1459   jccb(Assembler::lessEqual, SpinExit);
1460   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1461   testptr(tmp_Reg, tmp_Reg);
1462   jccb(Assembler::notZero, SpinLoop);
1463 
1464   bind(SpinExit);
1465   jmp(retryLabel);
1466   bind(doneRetry);
1467   incrementl(retry_count_Reg); // clear z flag
1468 }
1469 
1470 // Use RTM for normal stack locks
1471 // Input: objReg (object to lock)
1472 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1473                                        Register retry_on_abort_count_Reg,
1474                                        RTMLockingCounters* stack_rtm_counters,
1475                                        Metadata* method_data, bool profile_rtm,
1476                                        Label& DONE_LABEL, Label& IsInflated) {
1477   assert(UseRTMForStackLocks, "why call this otherwise?");
1478   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1479   assert(tmpReg == rax, "");
1480   assert(scrReg == rdx, "");
1481   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1482 
1483   if (RTMRetryCount > 0) {
1484     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1485     bind(L_rtm_retry);
1486   }
1487   movptr(tmpReg, Address(objReg, 0));
1488   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1489   jcc(Assembler::notZero, IsInflated);
1490 
1491   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1492     Label L_noincrement;
1493     if (RTMTotalCountIncrRate > 1) {
1494       // tmpReg, scrReg and flags are killed
1495       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1496     }
1497     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1498     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1499     bind(L_noincrement);
1500   }
1501   xbegin(L_on_abort);
1502   movptr(tmpReg, Address(objReg, 0));       // fetch markword
1503   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1504   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1505   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1506 
1507   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1508   if (UseRTMXendForLockBusy) {
1509     xend();
1510     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1511     jmp(L_decrement_retry);
1512   }
1513   else {
1514     xabort(0);
1515   }
1516   bind(L_on_abort);
1517   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1518     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1519   }
1520   bind(L_decrement_retry);
1521   if (RTMRetryCount > 0) {
1522     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1523     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1524   }
1525 }
1526 
1527 // Use RTM for inflating locks
1528 // inputs: objReg (object to lock)
1529 //         boxReg (on-stack box address (displaced header location) - KILLED)
1530 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1531 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1532                                           Register scrReg, Register retry_on_busy_count_Reg,
1533                                           Register retry_on_abort_count_Reg,
1534                                           RTMLockingCounters* rtm_counters,
1535                                           Metadata* method_data, bool profile_rtm,
1536                                           Label& DONE_LABEL) {
1537   assert(UseRTMLocking, "why call this otherwise?");
1538   assert(tmpReg == rax, "");
1539   assert(scrReg == rdx, "");
1540   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1541   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1542 
1543   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1544   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1545   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1546 
1547   if (RTMRetryCount > 0) {
1548     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1549     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1550     bind(L_rtm_retry);
1551   }
1552   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1553     Label L_noincrement;
1554     if (RTMTotalCountIncrRate > 1) {
1555       // tmpReg, scrReg and flags are killed
1556       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1557     }
1558     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1559     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1560     bind(L_noincrement);
1561   }
1562   xbegin(L_on_abort);
1563   movptr(tmpReg, Address(objReg, 0));
1564   movptr(tmpReg, Address(tmpReg, owner_offset));
1565   testptr(tmpReg, tmpReg);
1566   jcc(Assembler::zero, DONE_LABEL);
1567   if (UseRTMXendForLockBusy) {
1568     xend();
1569     jmp(L_decrement_retry);
1570   }
1571   else {
1572     xabort(0);
1573   }
1574   bind(L_on_abort);
1575   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1576   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1577     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1578   }
1579   if (RTMRetryCount > 0) {
1580     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1581     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1582   }
1583 
1584   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1585   testptr(tmpReg, tmpReg) ;
1586   jccb(Assembler::notZero, L_decrement_retry) ;
1587 
1588   // Appears unlocked - try to swing _owner from null to non-null.
1589   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1590 #ifdef _LP64
1591   Register threadReg = r15_thread;
1592 #else
1593   get_thread(scrReg);
1594   Register threadReg = scrReg;
1595 #endif
1596   if (os::is_MP()) {
1597     lock();
1598   }
1599   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1600 
1601   if (RTMRetryCount > 0) {
1602     // success done else retry
1603     jccb(Assembler::equal, DONE_LABEL) ;
1604     bind(L_decrement_retry);
1605     // Spin and retry if lock is busy.
1606     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1607   }
1608   else {
1609     bind(L_decrement_retry);
1610   }
1611 }
1612 
1613 #endif //  INCLUDE_RTM_OPT
1614 
1615 // Fast_Lock and Fast_Unlock used by C2
1616 
1617 // Because the transitions from emitted code to the runtime
1618 // monitorenter/exit helper stubs are so slow it's critical that
1619 // we inline both the stack-locking fast-path and the inflated fast path.
1620 //
1621 // See also: cmpFastLock and cmpFastUnlock.
1622 //
1623 // What follows is a specialized inline transliteration of the code
1624 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1625 // another option would be to emit TrySlowEnter and TrySlowExit methods
1626 // at startup-time.  These methods would accept arguments as
1627 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1628 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1629 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1630 // In practice, however, the # of lock sites is bounded and is usually small.
1631 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1632 // if the processor uses simple bimodal branch predictors keyed by EIP
1633 // Since the helper routines would be called from multiple synchronization
1634 // sites.
1635 //
1636 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1637 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1638 // to those specialized methods.  That'd give us a mostly platform-independent
1639 // implementation that the JITs could optimize and inline at their pleasure.
1640 // Done correctly, the only time we'd need to cross to native could would be
1641 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1642 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1643 // (b) explicit barriers or fence operations.
1644 //
1645 // TODO:
1646 //
1647 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1648 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1649 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1650 //    the lock operators would typically be faster than reifying Self.
1651 //
1652 // *  Ideally I'd define the primitives as:
1653 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1654 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1655 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1656 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1657 //    Furthermore the register assignments are overconstrained, possibly resulting in
1658 //    sub-optimal code near the synchronization site.
1659 //
1660 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1661 //    Alternately, use a better sp-proximity test.
1662 //
1663 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1664 //    Either one is sufficient to uniquely identify a thread.
1665 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1666 //
1667 // *  Intrinsify notify() and notifyAll() for the common cases where the
1668 //    object is locked by the calling thread but the waitlist is empty.
1669 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1670 //
1671 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1672 //    But beware of excessive branch density on AMD Opterons.
1673 //
1674 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1675 //    or failure of the fast-path.  If the fast-path fails then we pass
1676 //    control to the slow-path, typically in C.  In Fast_Lock and
1677 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1678 //    will emit a conditional branch immediately after the node.
1679 //    So we have branches to branches and lots of ICC.ZF games.
1680 //    Instead, it might be better to have C2 pass a "FailureLabel"
1681 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1682 //    will drop through the node.  ICC.ZF is undefined at exit.
1683 //    In the case of failure, the node will branch directly to the
1684 //    FailureLabel
1685 
1686 
1687 // obj: object to lock
1688 // box: on-stack box address (displaced header location) - KILLED
1689 // rax,: tmp -- KILLED
1690 // scr: tmp -- KILLED
1691 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1692                                Register scrReg, Register cx1Reg, Register cx2Reg,
1693                                BiasedLockingCounters* counters,
1694                                RTMLockingCounters* rtm_counters,
1695                                RTMLockingCounters* stack_rtm_counters,
1696                                Metadata* method_data,
1697                                bool use_rtm, bool profile_rtm) {
1698   // Ensure the register assignments are disjoint
1699   assert(tmpReg == rax, "");
1700 
1701   if (use_rtm) {
1702     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1703   } else {
1704     assert(cx1Reg == noreg, "");
1705     assert(cx2Reg == noreg, "");
1706     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1707   }
1708 
1709   if (counters != NULL) {
1710     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1711   }
1712   if (EmitSync & 1) {
1713       // set box->dhw = markOopDesc::unused_mark()
1714       // Force all sync thru slow-path: slow_enter() and slow_exit()
1715       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1716       cmpptr (rsp, (int32_t)NULL_WORD);
1717   } else {
1718     // Possible cases that we'll encounter in fast_lock
1719     // ------------------------------------------------
1720     // * Inflated
1721     //    -- unlocked
1722     //    -- Locked
1723     //       = by self
1724     //       = by other
1725     // * biased
1726     //    -- by Self
1727     //    -- by other
1728     // * neutral
1729     // * stack-locked
1730     //    -- by self
1731     //       = sp-proximity test hits
1732     //       = sp-proximity test generates false-negative
1733     //    -- by other
1734     //
1735 
1736     Label IsInflated, DONE_LABEL;
1737 
1738     // it's stack-locked, biased or neutral
1739     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1740     // order to reduce the number of conditional branches in the most common cases.
1741     // Beware -- there's a subtle invariant that fetch of the markword
1742     // at [FETCH], below, will never observe a biased encoding (*101b).
1743     // If this invariant is not held we risk exclusion (safety) failure.
1744     if (UseBiasedLocking && !UseOptoBiasInlining) {
1745       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1746     }
1747 
1748 #if INCLUDE_RTM_OPT
1749     if (UseRTMForStackLocks && use_rtm) {
1750       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1751                         stack_rtm_counters, method_data, profile_rtm,
1752                         DONE_LABEL, IsInflated);
1753     }
1754 #endif // INCLUDE_RTM_OPT
1755 
1756     movptr(tmpReg, Address(objReg, 0));          // [FETCH]
1757     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1758     jccb(Assembler::notZero, IsInflated);
1759 
1760     // Attempt stack-locking ...
1761     orptr (tmpReg, markOopDesc::unlocked_value);
1762     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1763     if (os::is_MP()) {
1764       lock();
1765     }
1766     cmpxchgptr(boxReg, Address(objReg, 0));      // Updates tmpReg
1767     if (counters != NULL) {
1768       cond_inc32(Assembler::equal,
1769                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1770     }
1771     jcc(Assembler::equal, DONE_LABEL);           // Success
1772 
1773     // Recursive locking.
1774     // The object is stack-locked: markword contains stack pointer to BasicLock.
1775     // Locked by current thread if difference with current SP is less than one page.
1776     subptr(tmpReg, rsp);
1777     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1778     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1779     movptr(Address(boxReg, 0), tmpReg);
1780     if (counters != NULL) {
1781       cond_inc32(Assembler::equal,
1782                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1783     }
1784     jmp(DONE_LABEL);
1785 
1786     bind(IsInflated);
1787     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1788 
1789 #if INCLUDE_RTM_OPT
1790     // Use the same RTM locking code in 32- and 64-bit VM.
1791     if (use_rtm) {
1792       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1793                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1794     } else {
1795 #endif // INCLUDE_RTM_OPT
1796 
1797 #ifndef _LP64
1798     // The object is inflated.
1799 
1800     // boxReg refers to the on-stack BasicLock in the current frame.
1801     // We'd like to write:
1802     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1803     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1804     // additional latency as we have another ST in the store buffer that must drain.
1805 
1806     if (EmitSync & 8192) {
1807        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1808        get_thread (scrReg);
1809        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1810        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1811        if (os::is_MP()) {
1812          lock();
1813        }
1814        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1815     } else
1816     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1817        // register juggle because we need tmpReg for cmpxchgptr below
1818        movptr(scrReg, boxReg);
1819        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1820 
1821        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1822        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1823           // prefetchw [eax + Offset(_owner)-2]
1824           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1825        }
1826 
1827        if ((EmitSync & 64) == 0) {
1828          // Optimistic form: consider XORL tmpReg,tmpReg
1829          movptr(tmpReg, NULL_WORD);
1830        } else {
1831          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1832          // Test-And-CAS instead of CAS
1833          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1834          testptr(tmpReg, tmpReg);                   // Locked ?
1835          jccb  (Assembler::notZero, DONE_LABEL);
1836        }
1837 
1838        // Appears unlocked - try to swing _owner from null to non-null.
1839        // Ideally, I'd manifest "Self" with get_thread and then attempt
1840        // to CAS the register containing Self into m->Owner.
1841        // But we don't have enough registers, so instead we can either try to CAS
1842        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1843        // we later store "Self" into m->Owner.  Transiently storing a stack address
1844        // (rsp or the address of the box) into  m->owner is harmless.
1845        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1846        if (os::is_MP()) {
1847          lock();
1848        }
1849        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1850        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1851        // If we weren't able to swing _owner from NULL to the BasicLock
1852        // then take the slow path.
1853        jccb  (Assembler::notZero, DONE_LABEL);
1854        // update _owner from BasicLock to thread
1855        get_thread (scrReg);                    // beware: clobbers ICCs
1856        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1857        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1858 
1859        // If the CAS fails we can either retry or pass control to the slow-path.
1860        // We use the latter tactic.
1861        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1862        // If the CAS was successful ...
1863        //   Self has acquired the lock
1864        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1865        // Intentional fall-through into DONE_LABEL ...
1866     } else {
1867        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1868        movptr(boxReg, tmpReg);
1869 
1870        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1871        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1872           // prefetchw [eax + Offset(_owner)-2]
1873           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1874        }
1875 
1876        if ((EmitSync & 64) == 0) {
1877          // Optimistic form
1878          xorptr  (tmpReg, tmpReg);
1879        } else {
1880          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1881          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1882          testptr(tmpReg, tmpReg);                   // Locked ?
1883          jccb  (Assembler::notZero, DONE_LABEL);
1884        }
1885 
1886        // Appears unlocked - try to swing _owner from null to non-null.
1887        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1888        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1889        get_thread (scrReg);
1890        if (os::is_MP()) {
1891          lock();
1892        }
1893        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1894 
1895        // If the CAS fails we can either retry or pass control to the slow-path.
1896        // We use the latter tactic.
1897        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1898        // If the CAS was successful ...
1899        //   Self has acquired the lock
1900        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1901        // Intentional fall-through into DONE_LABEL ...
1902     }
1903 #else // _LP64
1904     // It's inflated
1905     movq(scrReg, tmpReg);
1906     xorq(tmpReg, tmpReg);
1907 
1908     if (os::is_MP()) {
1909       lock();
1910     }
1911     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1912     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1913     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1914     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1915     // Intentional fall-through into DONE_LABEL ...
1916     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1917 #endif // _LP64
1918 #if INCLUDE_RTM_OPT
1919     } // use_rtm()
1920 #endif
1921     // DONE_LABEL is a hot target - we'd really like to place it at the
1922     // start of cache line by padding with NOPs.
1923     // See the AMD and Intel software optimization manuals for the
1924     // most efficient "long" NOP encodings.
1925     // Unfortunately none of our alignment mechanisms suffice.
1926     bind(DONE_LABEL);
1927 
1928     // At DONE_LABEL the icc ZFlag is set as follows ...
1929     // Fast_Unlock uses the same protocol.
1930     // ZFlag == 1 -> Success
1931     // ZFlag == 0 -> Failure - force control through the slow-path
1932   }
1933 }
1934 
1935 // obj: object to unlock
1936 // box: box address (displaced header location), killed.  Must be EAX.
1937 // tmp: killed, cannot be obj nor box.
1938 //
1939 // Some commentary on balanced locking:
1940 //
1941 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1942 // Methods that don't have provably balanced locking are forced to run in the
1943 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1944 // The interpreter provides two properties:
1945 // I1:  At return-time the interpreter automatically and quietly unlocks any
1946 //      objects acquired the current activation (frame).  Recall that the
1947 //      interpreter maintains an on-stack list of locks currently held by
1948 //      a frame.
1949 // I2:  If a method attempts to unlock an object that is not held by the
1950 //      the frame the interpreter throws IMSX.
1951 //
1952 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1953 // B() doesn't have provably balanced locking so it runs in the interpreter.
1954 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1955 // is still locked by A().
1956 //
1957 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1958 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1959 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1960 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1961 // Arguably given that the spec legislates the JNI case as undefined our implementation
1962 // could reasonably *avoid* checking owner in Fast_Unlock().
1963 // In the interest of performance we elide m->Owner==Self check in unlock.
1964 // A perfectly viable alternative is to elide the owner check except when
1965 // Xcheck:jni is enabled.
1966 
1967 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1968   assert(boxReg == rax, "");
1969   assert_different_registers(objReg, boxReg, tmpReg);
1970 
1971   if (EmitSync & 4) {
1972     // Disable - inhibit all inlining.  Force control through the slow-path
1973     cmpptr (rsp, 0);
1974   } else {
1975     Label DONE_LABEL, Stacked, CheckSucc;
1976 
1977     // Critically, the biased locking test must have precedence over
1978     // and appear before the (box->dhw == 0) recursive stack-lock test.
1979     if (UseBiasedLocking && !UseOptoBiasInlining) {
1980        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1981     }
1982 
1983 #if INCLUDE_RTM_OPT
1984     if (UseRTMForStackLocks && use_rtm) {
1985       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1986       Label L_regular_unlock;
1987       movptr(tmpReg, Address(objReg, 0));           // fetch markword
1988       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1989       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1990       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1991       xend();                                       // otherwise end...
1992       jmp(DONE_LABEL);                              // ... and we're done
1993       bind(L_regular_unlock);
1994     }
1995 #endif
1996 
1997     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
1998     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
1999     movptr(tmpReg, Address(objReg, 0));             // Examine the object's markword
2000     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2001     jccb  (Assembler::zero, Stacked);
2002 
2003     // It's inflated.
2004 #if INCLUDE_RTM_OPT
2005     if (use_rtm) {
2006       Label L_regular_inflated_unlock;
2007       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2008       movptr(boxReg, Address(tmpReg, owner_offset));
2009       testptr(boxReg, boxReg);
2010       jccb(Assembler::notZero, L_regular_inflated_unlock);
2011       xend();
2012       jmpb(DONE_LABEL);
2013       bind(L_regular_inflated_unlock);
2014     }
2015 #endif
2016 
2017     // Despite our balanced locking property we still check that m->_owner == Self
2018     // as java routines or native JNI code called by this thread might
2019     // have released the lock.
2020     // Refer to the comments in synchronizer.cpp for how we might encode extra
2021     // state in _succ so we can avoid fetching EntryList|cxq.
2022     //
2023     // I'd like to add more cases in fast_lock() and fast_unlock() --
2024     // such as recursive enter and exit -- but we have to be wary of
2025     // I$ bloat, T$ effects and BP$ effects.
2026     //
2027     // If there's no contention try a 1-0 exit.  That is, exit without
2028     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2029     // we detect and recover from the race that the 1-0 exit admits.
2030     //
2031     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2032     // before it STs null into _owner, releasing the lock.  Updates
2033     // to data protected by the critical section must be visible before
2034     // we drop the lock (and thus before any other thread could acquire
2035     // the lock and observe the fields protected by the lock).
2036     // IA32's memory-model is SPO, so STs are ordered with respect to
2037     // each other and there's no need for an explicit barrier (fence).
2038     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2039 #ifndef _LP64
2040     get_thread (boxReg);
2041     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2042       // prefetchw [ebx + Offset(_owner)-2]
2043       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2044     }
2045 
2046     // Note that we could employ various encoding schemes to reduce
2047     // the number of loads below (currently 4) to just 2 or 3.
2048     // Refer to the comments in synchronizer.cpp.
2049     // In practice the chain of fetches doesn't seem to impact performance, however.
2050     xorptr(boxReg, boxReg);
2051     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2052        // Attempt to reduce branch density - AMD's branch predictor.
2053        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2054        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2055        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2056        jccb  (Assembler::notZero, DONE_LABEL);
2057        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2058        jmpb  (DONE_LABEL);
2059     } else {
2060        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2061        jccb  (Assembler::notZero, DONE_LABEL);
2062        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2063        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2064        jccb  (Assembler::notZero, CheckSucc);
2065        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2066        jmpb  (DONE_LABEL);
2067     }
2068 
2069     // The Following code fragment (EmitSync & 65536) improves the performance of
2070     // contended applications and contended synchronization microbenchmarks.
2071     // Unfortunately the emission of the code - even though not executed - causes regressions
2072     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2073     // with an equal number of never-executed NOPs results in the same regression.
2074     // We leave it off by default.
2075 
2076     if ((EmitSync & 65536) != 0) {
2077        Label LSuccess, LGoSlowPath ;
2078 
2079        bind  (CheckSucc);
2080 
2081        // Optional pre-test ... it's safe to elide this
2082        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2083        jccb(Assembler::zero, LGoSlowPath);
2084 
2085        // We have a classic Dekker-style idiom:
2086        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2087        // There are a number of ways to implement the barrier:
2088        // (1) lock:andl &m->_owner, 0
2089        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2090        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2091        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2092        // (2) If supported, an explicit MFENCE is appealing.
2093        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2094        //     particularly if the write-buffer is full as might be the case if
2095        //     if stores closely precede the fence or fence-equivalent instruction.
2096        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2097        //     as the situation has changed with Nehalem and Shanghai.
2098        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2099        //     The $lines underlying the top-of-stack should be in M-state.
2100        //     The locked add instruction is serializing, of course.
2101        // (4) Use xchg, which is serializing
2102        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2103        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2104        //     The integer condition codes will tell us if succ was 0.
2105        //     Since _succ and _owner should reside in the same $line and
2106        //     we just stored into _owner, it's likely that the $line
2107        //     remains in M-state for the lock:orl.
2108        //
2109        // We currently use (3), although it's likely that switching to (2)
2110        // is correct for the future.
2111 
2112        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2113        if (os::is_MP()) {
2114          lock(); addptr(Address(rsp, 0), 0);
2115        }
2116        // Ratify _succ remains non-null
2117        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2118        jccb  (Assembler::notZero, LSuccess);
2119 
2120        xorptr(boxReg, boxReg);                  // box is really EAX
2121        if (os::is_MP()) { lock(); }
2122        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2123        // There's no successor so we tried to regrab the lock with the
2124        // placeholder value. If that didn't work, then another thread
2125        // grabbed the lock so we're done (and exit was a success).
2126        jccb  (Assembler::notEqual, LSuccess);
2127        // Since we're low on registers we installed rsp as a placeholding in _owner.
2128        // Now install Self over rsp.  This is safe as we're transitioning from
2129        // non-null to non=null
2130        get_thread (boxReg);
2131        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2132        // Intentional fall-through into LGoSlowPath ...
2133 
2134        bind  (LGoSlowPath);
2135        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2136        jmpb  (DONE_LABEL);
2137 
2138        bind  (LSuccess);
2139        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2140        jmpb  (DONE_LABEL);
2141     }
2142 
2143     bind (Stacked);
2144     // It's not inflated and it's not recursively stack-locked and it's not biased.
2145     // It must be stack-locked.
2146     // Try to reset the header to displaced header.
2147     // The "box" value on the stack is stable, so we can reload
2148     // and be assured we observe the same value as above.
2149     movptr(tmpReg, Address(boxReg, 0));
2150     if (os::is_MP()) {
2151       lock();
2152     }
2153     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2154     // Intention fall-thru into DONE_LABEL
2155 
2156     // DONE_LABEL is a hot target - we'd really like to place it at the
2157     // start of cache line by padding with NOPs.
2158     // See the AMD and Intel software optimization manuals for the
2159     // most efficient "long" NOP encodings.
2160     // Unfortunately none of our alignment mechanisms suffice.
2161     if ((EmitSync & 65536) == 0) {
2162        bind (CheckSucc);
2163     }
2164 #else // _LP64
2165     // It's inflated
2166     if (EmitSync & 1024) {
2167       // Emit code to check that _owner == Self
2168       // We could fold the _owner test into subsequent code more efficiently
2169       // than using a stand-alone check, but since _owner checking is off by
2170       // default we don't bother. We also might consider predicating the
2171       // _owner==Self check on Xcheck:jni or running on a debug build.
2172       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2173       xorptr(boxReg, r15_thread);
2174     } else {
2175       xorptr(boxReg, boxReg);
2176     }
2177     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2178     jccb  (Assembler::notZero, DONE_LABEL);
2179     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2180     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2181     jccb  (Assembler::notZero, CheckSucc);
2182     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2183     jmpb  (DONE_LABEL);
2184 
2185     if ((EmitSync & 65536) == 0) {
2186       // Try to avoid passing control into the slow_path ...
2187       Label LSuccess, LGoSlowPath ;
2188       bind  (CheckSucc);
2189 
2190       // The following optional optimization can be elided if necessary
2191       // Effectively: if (succ == null) goto SlowPath
2192       // The code reduces the window for a race, however,
2193       // and thus benefits performance.
2194       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2195       jccb  (Assembler::zero, LGoSlowPath);
2196 
2197       xorptr(boxReg, boxReg);
2198       if ((EmitSync & 16) && os::is_MP()) {
2199         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2200       } else {
2201         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2202         if (os::is_MP()) {
2203           // Memory barrier/fence
2204           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2205           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2206           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2207           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2208           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2209           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2210           lock(); addl(Address(rsp, 0), 0);
2211         }
2212       }
2213       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2214       jccb  (Assembler::notZero, LSuccess);
2215 
2216       // Rare inopportune interleaving - race.
2217       // The successor vanished in the small window above.
2218       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2219       // We need to ensure progress and succession.
2220       // Try to reacquire the lock.
2221       // If that fails then the new owner is responsible for succession and this
2222       // thread needs to take no further action and can exit via the fast path (success).
2223       // If the re-acquire succeeds then pass control into the slow path.
2224       // As implemented, this latter mode is horrible because we generated more
2225       // coherence traffic on the lock *and* artifically extended the critical section
2226       // length while by virtue of passing control into the slow path.
2227 
2228       // box is really RAX -- the following CMPXCHG depends on that binding
2229       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2230       if (os::is_MP()) { lock(); }
2231       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2232       // There's no successor so we tried to regrab the lock.
2233       // If that didn't work, then another thread grabbed the
2234       // lock so we're done (and exit was a success).
2235       jccb  (Assembler::notEqual, LSuccess);
2236       // Intentional fall-through into slow-path
2237 
2238       bind  (LGoSlowPath);
2239       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2240       jmpb  (DONE_LABEL);
2241 
2242       bind  (LSuccess);
2243       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2244       jmpb  (DONE_LABEL);
2245     }
2246 
2247     bind  (Stacked);
2248     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2249     if (os::is_MP()) { lock(); }
2250     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2251 
2252     if (EmitSync & 65536) {
2253        bind (CheckSucc);
2254     }
2255 #endif
2256     bind(DONE_LABEL);
2257   }
2258 }
2259 #endif // COMPILER2
2260 
2261 void MacroAssembler::c2bool(Register x) {
2262   // implements x == 0 ? 0 : 1
2263   // note: must only look at least-significant byte of x
2264   //       since C-style booleans are stored in one byte
2265   //       only! (was bug)
2266   andl(x, 0xFF);
2267   setb(Assembler::notZero, x);
2268 }
2269 
2270 // Wouldn't need if AddressLiteral version had new name
2271 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2272   Assembler::call(L, rtype);
2273 }
2274 
2275 void MacroAssembler::call(Register entry) {
2276   Assembler::call(entry);
2277 }
2278 
2279 void MacroAssembler::call(AddressLiteral entry) {
2280   if (reachable(entry)) {
2281     Assembler::call_literal(entry.target(), entry.rspec());
2282   } else {
2283     lea(rscratch1, entry);
2284     Assembler::call(rscratch1);
2285   }
2286 }
2287 
2288 void MacroAssembler::ic_call(address entry, jint method_index) {
2289   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2290   movptr(rax, (intptr_t)Universe::non_oop_word());
2291   call(AddressLiteral(entry, rh));
2292 }
2293 
2294 // Implementation of call_VM versions
2295 
2296 void MacroAssembler::call_VM(Register oop_result,
2297                              address entry_point,
2298                              bool check_exceptions) {
2299   Label C, E;
2300   call(C, relocInfo::none);
2301   jmp(E);
2302 
2303   bind(C);
2304   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2305   ret(0);
2306 
2307   bind(E);
2308 }
2309 
2310 void MacroAssembler::call_VM(Register oop_result,
2311                              address entry_point,
2312                              Register arg_1,
2313                              bool check_exceptions) {
2314   Label C, E;
2315   call(C, relocInfo::none);
2316   jmp(E);
2317 
2318   bind(C);
2319   pass_arg1(this, arg_1);
2320   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2321   ret(0);
2322 
2323   bind(E);
2324 }
2325 
2326 void MacroAssembler::call_VM(Register oop_result,
2327                              address entry_point,
2328                              Register arg_1,
2329                              Register arg_2,
2330                              bool check_exceptions) {
2331   Label C, E;
2332   call(C, relocInfo::none);
2333   jmp(E);
2334 
2335   bind(C);
2336 
2337   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2338 
2339   pass_arg2(this, arg_2);
2340   pass_arg1(this, arg_1);
2341   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2342   ret(0);
2343 
2344   bind(E);
2345 }
2346 
2347 void MacroAssembler::call_VM(Register oop_result,
2348                              address entry_point,
2349                              Register arg_1,
2350                              Register arg_2,
2351                              Register arg_3,
2352                              bool check_exceptions) {
2353   Label C, E;
2354   call(C, relocInfo::none);
2355   jmp(E);
2356 
2357   bind(C);
2358 
2359   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2360   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2361   pass_arg3(this, arg_3);
2362 
2363   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2364   pass_arg2(this, arg_2);
2365 
2366   pass_arg1(this, arg_1);
2367   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2368   ret(0);
2369 
2370   bind(E);
2371 }
2372 
2373 void MacroAssembler::call_VM(Register oop_result,
2374                              Register last_java_sp,
2375                              address entry_point,
2376                              int number_of_arguments,
2377                              bool check_exceptions) {
2378   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2379   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2380 }
2381 
2382 void MacroAssembler::call_VM(Register oop_result,
2383                              Register last_java_sp,
2384                              address entry_point,
2385                              Register arg_1,
2386                              bool check_exceptions) {
2387   pass_arg1(this, arg_1);
2388   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2389 }
2390 
2391 void MacroAssembler::call_VM(Register oop_result,
2392                              Register last_java_sp,
2393                              address entry_point,
2394                              Register arg_1,
2395                              Register arg_2,
2396                              bool check_exceptions) {
2397 
2398   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2399   pass_arg2(this, arg_2);
2400   pass_arg1(this, arg_1);
2401   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2402 }
2403 
2404 void MacroAssembler::call_VM(Register oop_result,
2405                              Register last_java_sp,
2406                              address entry_point,
2407                              Register arg_1,
2408                              Register arg_2,
2409                              Register arg_3,
2410                              bool check_exceptions) {
2411   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2412   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2413   pass_arg3(this, arg_3);
2414   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2415   pass_arg2(this, arg_2);
2416   pass_arg1(this, arg_1);
2417   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2418 }
2419 
2420 void MacroAssembler::super_call_VM(Register oop_result,
2421                                    Register last_java_sp,
2422                                    address entry_point,
2423                                    int number_of_arguments,
2424                                    bool check_exceptions) {
2425   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2426   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2427 }
2428 
2429 void MacroAssembler::super_call_VM(Register oop_result,
2430                                    Register last_java_sp,
2431                                    address entry_point,
2432                                    Register arg_1,
2433                                    bool check_exceptions) {
2434   pass_arg1(this, arg_1);
2435   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2436 }
2437 
2438 void MacroAssembler::super_call_VM(Register oop_result,
2439                                    Register last_java_sp,
2440                                    address entry_point,
2441                                    Register arg_1,
2442                                    Register arg_2,
2443                                    bool check_exceptions) {
2444 
2445   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2446   pass_arg2(this, arg_2);
2447   pass_arg1(this, arg_1);
2448   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2449 }
2450 
2451 void MacroAssembler::super_call_VM(Register oop_result,
2452                                    Register last_java_sp,
2453                                    address entry_point,
2454                                    Register arg_1,
2455                                    Register arg_2,
2456                                    Register arg_3,
2457                                    bool check_exceptions) {
2458   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2459   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2460   pass_arg3(this, arg_3);
2461   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2462   pass_arg2(this, arg_2);
2463   pass_arg1(this, arg_1);
2464   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2465 }
2466 
2467 void MacroAssembler::call_VM_base(Register oop_result,
2468                                   Register java_thread,
2469                                   Register last_java_sp,
2470                                   address  entry_point,
2471                                   int      number_of_arguments,
2472                                   bool     check_exceptions) {
2473   // determine java_thread register
2474   if (!java_thread->is_valid()) {
2475 #ifdef _LP64
2476     java_thread = r15_thread;
2477 #else
2478     java_thread = rdi;
2479     get_thread(java_thread);
2480 #endif // LP64
2481   }
2482   // determine last_java_sp register
2483   if (!last_java_sp->is_valid()) {
2484     last_java_sp = rsp;
2485   }
2486   // debugging support
2487   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2488   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2489 #ifdef ASSERT
2490   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2491   // r12 is the heapbase.
2492   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2493 #endif // ASSERT
2494 
2495   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2496   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2497 
2498   // push java thread (becomes first argument of C function)
2499 
2500   NOT_LP64(push(java_thread); number_of_arguments++);
2501   LP64_ONLY(mov(c_rarg0, r15_thread));
2502 
2503   // set last Java frame before call
2504   assert(last_java_sp != rbp, "can't use ebp/rbp");
2505 
2506   // Only interpreter should have to set fp
2507   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2508 
2509   // do the call, remove parameters
2510   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2511 
2512   // restore the thread (cannot use the pushed argument since arguments
2513   // may be overwritten by C code generated by an optimizing compiler);
2514   // however can use the register value directly if it is callee saved.
2515   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2516     // rdi & rsi (also r15) are callee saved -> nothing to do
2517 #ifdef ASSERT
2518     guarantee(java_thread != rax, "change this code");
2519     push(rax);
2520     { Label L;
2521       get_thread(rax);
2522       cmpptr(java_thread, rax);
2523       jcc(Assembler::equal, L);
2524       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2525       bind(L);
2526     }
2527     pop(rax);
2528 #endif
2529   } else {
2530     get_thread(java_thread);
2531   }
2532   // reset last Java frame
2533   // Only interpreter should have to clear fp
2534   reset_last_Java_frame(java_thread, true, false);
2535 
2536    // C++ interp handles this in the interpreter
2537   check_and_handle_popframe(java_thread);
2538   check_and_handle_earlyret(java_thread);
2539 
2540   if (check_exceptions) {
2541     // check for pending exceptions (java_thread is set upon return)
2542     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2543 #ifndef _LP64
2544     jump_cc(Assembler::notEqual,
2545             RuntimeAddress(StubRoutines::forward_exception_entry()));
2546 #else
2547     // This used to conditionally jump to forward_exception however it is
2548     // possible if we relocate that the branch will not reach. So we must jump
2549     // around so we can always reach
2550 
2551     Label ok;
2552     jcc(Assembler::equal, ok);
2553     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2554     bind(ok);
2555 #endif // LP64
2556   }
2557 
2558   // get oop result if there is one and reset the value in the thread
2559   if (oop_result->is_valid()) {
2560     get_vm_result(oop_result, java_thread);
2561   }
2562 }
2563 
2564 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2565 
2566   // Calculate the value for last_Java_sp
2567   // somewhat subtle. call_VM does an intermediate call
2568   // which places a return address on the stack just under the
2569   // stack pointer as the user finsihed with it. This allows
2570   // use to retrieve last_Java_pc from last_Java_sp[-1].
2571   // On 32bit we then have to push additional args on the stack to accomplish
2572   // the actual requested call. On 64bit call_VM only can use register args
2573   // so the only extra space is the return address that call_VM created.
2574   // This hopefully explains the calculations here.
2575 
2576 #ifdef _LP64
2577   // We've pushed one address, correct last_Java_sp
2578   lea(rax, Address(rsp, wordSize));
2579 #else
2580   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2581 #endif // LP64
2582 
2583   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2584 
2585 }
2586 
2587 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2588 void MacroAssembler::call_VM_leaf0(address entry_point) {
2589   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2590 }
2591 
2592 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2593   call_VM_leaf_base(entry_point, number_of_arguments);
2594 }
2595 
2596 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2597   pass_arg0(this, arg_0);
2598   call_VM_leaf(entry_point, 1);
2599 }
2600 
2601 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2602 
2603   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2604   pass_arg1(this, arg_1);
2605   pass_arg0(this, arg_0);
2606   call_VM_leaf(entry_point, 2);
2607 }
2608 
2609 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2610   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2611   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2612   pass_arg2(this, arg_2);
2613   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2614   pass_arg1(this, arg_1);
2615   pass_arg0(this, arg_0);
2616   call_VM_leaf(entry_point, 3);
2617 }
2618 
2619 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2620   pass_arg0(this, arg_0);
2621   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2622 }
2623 
2624 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2625 
2626   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2627   pass_arg1(this, arg_1);
2628   pass_arg0(this, arg_0);
2629   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2630 }
2631 
2632 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2633   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2634   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2635   pass_arg2(this, arg_2);
2636   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2637   pass_arg1(this, arg_1);
2638   pass_arg0(this, arg_0);
2639   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2640 }
2641 
2642 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2643   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2644   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2645   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2646   pass_arg3(this, arg_3);
2647   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2648   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2649   pass_arg2(this, arg_2);
2650   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2651   pass_arg1(this, arg_1);
2652   pass_arg0(this, arg_0);
2653   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2654 }
2655 
2656 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2657   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2658   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2659   verify_oop(oop_result, "broken oop in call_VM_base");
2660 }
2661 
2662 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2663   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2664   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2665 }
2666 
2667 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2668 }
2669 
2670 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2671 }
2672 
2673 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2674   if (reachable(src1)) {
2675     cmpl(as_Address(src1), imm);
2676   } else {
2677     lea(rscratch1, src1);
2678     cmpl(Address(rscratch1, 0), imm);
2679   }
2680 }
2681 
2682 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2683   assert(!src2.is_lval(), "use cmpptr");
2684   if (reachable(src2)) {
2685     cmpl(src1, as_Address(src2));
2686   } else {
2687     lea(rscratch1, src2);
2688     cmpl(src1, Address(rscratch1, 0));
2689   }
2690 }
2691 
2692 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2693   Assembler::cmpl(src1, imm);
2694 }
2695 
2696 void MacroAssembler::cmp32(Register src1, Address src2) {
2697   Assembler::cmpl(src1, src2);
2698 }
2699 
2700 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2701   ucomisd(opr1, opr2);
2702 
2703   Label L;
2704   if (unordered_is_less) {
2705     movl(dst, -1);
2706     jcc(Assembler::parity, L);
2707     jcc(Assembler::below , L);
2708     movl(dst, 0);
2709     jcc(Assembler::equal , L);
2710     increment(dst);
2711   } else { // unordered is greater
2712     movl(dst, 1);
2713     jcc(Assembler::parity, L);
2714     jcc(Assembler::above , L);
2715     movl(dst, 0);
2716     jcc(Assembler::equal , L);
2717     decrementl(dst);
2718   }
2719   bind(L);
2720 }
2721 
2722 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2723   ucomiss(opr1, opr2);
2724 
2725   Label L;
2726   if (unordered_is_less) {
2727     movl(dst, -1);
2728     jcc(Assembler::parity, L);
2729     jcc(Assembler::below , L);
2730     movl(dst, 0);
2731     jcc(Assembler::equal , L);
2732     increment(dst);
2733   } else { // unordered is greater
2734     movl(dst, 1);
2735     jcc(Assembler::parity, L);
2736     jcc(Assembler::above , L);
2737     movl(dst, 0);
2738     jcc(Assembler::equal , L);
2739     decrementl(dst);
2740   }
2741   bind(L);
2742 }
2743 
2744 
2745 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2746   if (reachable(src1)) {
2747     cmpb(as_Address(src1), imm);
2748   } else {
2749     lea(rscratch1, src1);
2750     cmpb(Address(rscratch1, 0), imm);
2751   }
2752 }
2753 
2754 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2755 #ifdef _LP64
2756   if (src2.is_lval()) {
2757     movptr(rscratch1, src2);
2758     Assembler::cmpq(src1, rscratch1);
2759   } else if (reachable(src2)) {
2760     cmpq(src1, as_Address(src2));
2761   } else {
2762     lea(rscratch1, src2);
2763     Assembler::cmpq(src1, Address(rscratch1, 0));
2764   }
2765 #else
2766   if (src2.is_lval()) {
2767     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2768   } else {
2769     cmpl(src1, as_Address(src2));
2770   }
2771 #endif // _LP64
2772 }
2773 
2774 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2775   assert(src2.is_lval(), "not a mem-mem compare");
2776 #ifdef _LP64
2777   // moves src2's literal address
2778   movptr(rscratch1, src2);
2779   Assembler::cmpq(src1, rscratch1);
2780 #else
2781   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2782 #endif // _LP64
2783 }
2784 
2785 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2786   if (reachable(adr)) {
2787     if (os::is_MP())
2788       lock();
2789     cmpxchgptr(reg, as_Address(adr));
2790   } else {
2791     lea(rscratch1, adr);
2792     if (os::is_MP())
2793       lock();
2794     cmpxchgptr(reg, Address(rscratch1, 0));
2795   }
2796 }
2797 
2798 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2799   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2800 }
2801 
2802 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2803   if (reachable(src)) {
2804     Assembler::comisd(dst, as_Address(src));
2805   } else {
2806     lea(rscratch1, src);
2807     Assembler::comisd(dst, Address(rscratch1, 0));
2808   }
2809 }
2810 
2811 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2812   if (reachable(src)) {
2813     Assembler::comiss(dst, as_Address(src));
2814   } else {
2815     lea(rscratch1, src);
2816     Assembler::comiss(dst, Address(rscratch1, 0));
2817   }
2818 }
2819 
2820 
2821 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2822   Condition negated_cond = negate_condition(cond);
2823   Label L;
2824   jcc(negated_cond, L);
2825   pushf(); // Preserve flags
2826   atomic_incl(counter_addr);
2827   popf();
2828   bind(L);
2829 }
2830 
2831 int MacroAssembler::corrected_idivl(Register reg) {
2832   // Full implementation of Java idiv and irem; checks for
2833   // special case as described in JVM spec., p.243 & p.271.
2834   // The function returns the (pc) offset of the idivl
2835   // instruction - may be needed for implicit exceptions.
2836   //
2837   //         normal case                           special case
2838   //
2839   // input : rax,: dividend                         min_int
2840   //         reg: divisor   (may not be rax,/rdx)   -1
2841   //
2842   // output: rax,: quotient  (= rax, idiv reg)       min_int
2843   //         rdx: remainder (= rax, irem reg)       0
2844   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2845   const int min_int = 0x80000000;
2846   Label normal_case, special_case;
2847 
2848   // check for special case
2849   cmpl(rax, min_int);
2850   jcc(Assembler::notEqual, normal_case);
2851   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2852   cmpl(reg, -1);
2853   jcc(Assembler::equal, special_case);
2854 
2855   // handle normal case
2856   bind(normal_case);
2857   cdql();
2858   int idivl_offset = offset();
2859   idivl(reg);
2860 
2861   // normal and special case exit
2862   bind(special_case);
2863 
2864   return idivl_offset;
2865 }
2866 
2867 
2868 
2869 void MacroAssembler::decrementl(Register reg, int value) {
2870   if (value == min_jint) {subl(reg, value) ; return; }
2871   if (value <  0) { incrementl(reg, -value); return; }
2872   if (value == 0) {                        ; return; }
2873   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2874   /* else */      { subl(reg, value)       ; return; }
2875 }
2876 
2877 void MacroAssembler::decrementl(Address dst, int value) {
2878   if (value == min_jint) {subl(dst, value) ; return; }
2879   if (value <  0) { incrementl(dst, -value); return; }
2880   if (value == 0) {                        ; return; }
2881   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2882   /* else */      { subl(dst, value)       ; return; }
2883 }
2884 
2885 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2886   assert (shift_value > 0, "illegal shift value");
2887   Label _is_positive;
2888   testl (reg, reg);
2889   jcc (Assembler::positive, _is_positive);
2890   int offset = (1 << shift_value) - 1 ;
2891 
2892   if (offset == 1) {
2893     incrementl(reg);
2894   } else {
2895     addl(reg, offset);
2896   }
2897 
2898   bind (_is_positive);
2899   sarl(reg, shift_value);
2900 }
2901 
2902 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2903   if (reachable(src)) {
2904     Assembler::divsd(dst, as_Address(src));
2905   } else {
2906     lea(rscratch1, src);
2907     Assembler::divsd(dst, Address(rscratch1, 0));
2908   }
2909 }
2910 
2911 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2912   if (reachable(src)) {
2913     Assembler::divss(dst, as_Address(src));
2914   } else {
2915     lea(rscratch1, src);
2916     Assembler::divss(dst, Address(rscratch1, 0));
2917   }
2918 }
2919 
2920 // !defined(COMPILER2) is because of stupid core builds
2921 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2922 void MacroAssembler::empty_FPU_stack() {
2923   if (VM_Version::supports_mmx()) {
2924     emms();
2925   } else {
2926     for (int i = 8; i-- > 0; ) ffree(i);
2927   }
2928 }
2929 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2930 
2931 
2932 // Defines obj, preserves var_size_in_bytes
2933 void MacroAssembler::eden_allocate(Register obj,
2934                                    Register var_size_in_bytes,
2935                                    int con_size_in_bytes,
2936                                    Register t1,
2937                                    Label& slow_case) {
2938   assert(obj == rax, "obj must be in rax, for cmpxchg");
2939   assert_different_registers(obj, var_size_in_bytes, t1);
2940   if (!Universe::heap()->supports_inline_contig_alloc()) {
2941     jmp(slow_case);
2942   } else {
2943     Register end = t1;
2944     Label retry;
2945     bind(retry);
2946     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2947     movptr(obj, heap_top);
2948     if (var_size_in_bytes == noreg) {
2949       lea(end, Address(obj, con_size_in_bytes));
2950     } else {
2951       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2952     }
2953     // if end < obj then we wrapped around => object too long => slow case
2954     cmpptr(end, obj);
2955     jcc(Assembler::below, slow_case);
2956     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2957     jcc(Assembler::above, slow_case);
2958     // Compare obj with the top addr, and if still equal, store the new top addr in
2959     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2960     // it otherwise. Use lock prefix for atomicity on MPs.
2961     locked_cmpxchgptr(end, heap_top);
2962     jcc(Assembler::notEqual, retry);
2963   }
2964 }
2965 
2966 void MacroAssembler::enter() {
2967   push(rbp);
2968   mov(rbp, rsp);
2969 }
2970 
2971 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2972 void MacroAssembler::fat_nop() {
2973   if (UseAddressNop) {
2974     addr_nop_5();
2975   } else {
2976     emit_int8(0x26); // es:
2977     emit_int8(0x2e); // cs:
2978     emit_int8(0x64); // fs:
2979     emit_int8(0x65); // gs:
2980     emit_int8((unsigned char)0x90);
2981   }
2982 }
2983 
2984 void MacroAssembler::fcmp(Register tmp) {
2985   fcmp(tmp, 1, true, true);
2986 }
2987 
2988 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2989   assert(!pop_right || pop_left, "usage error");
2990   if (VM_Version::supports_cmov()) {
2991     assert(tmp == noreg, "unneeded temp");
2992     if (pop_left) {
2993       fucomip(index);
2994     } else {
2995       fucomi(index);
2996     }
2997     if (pop_right) {
2998       fpop();
2999     }
3000   } else {
3001     assert(tmp != noreg, "need temp");
3002     if (pop_left) {
3003       if (pop_right) {
3004         fcompp();
3005       } else {
3006         fcomp(index);
3007       }
3008     } else {
3009       fcom(index);
3010     }
3011     // convert FPU condition into eflags condition via rax,
3012     save_rax(tmp);
3013     fwait(); fnstsw_ax();
3014     sahf();
3015     restore_rax(tmp);
3016   }
3017   // condition codes set as follows:
3018   //
3019   // CF (corresponds to C0) if x < y
3020   // PF (corresponds to C2) if unordered
3021   // ZF (corresponds to C3) if x = y
3022 }
3023 
3024 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3025   fcmp2int(dst, unordered_is_less, 1, true, true);
3026 }
3027 
3028 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3029   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3030   Label L;
3031   if (unordered_is_less) {
3032     movl(dst, -1);
3033     jcc(Assembler::parity, L);
3034     jcc(Assembler::below , L);
3035     movl(dst, 0);
3036     jcc(Assembler::equal , L);
3037     increment(dst);
3038   } else { // unordered is greater
3039     movl(dst, 1);
3040     jcc(Assembler::parity, L);
3041     jcc(Assembler::above , L);
3042     movl(dst, 0);
3043     jcc(Assembler::equal , L);
3044     decrementl(dst);
3045   }
3046   bind(L);
3047 }
3048 
3049 void MacroAssembler::fld_d(AddressLiteral src) {
3050   fld_d(as_Address(src));
3051 }
3052 
3053 void MacroAssembler::fld_s(AddressLiteral src) {
3054   fld_s(as_Address(src));
3055 }
3056 
3057 void MacroAssembler::fld_x(AddressLiteral src) {
3058   Assembler::fld_x(as_Address(src));
3059 }
3060 
3061 void MacroAssembler::fldcw(AddressLiteral src) {
3062   Assembler::fldcw(as_Address(src));
3063 }
3064 
3065 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3066   if (reachable(src)) {
3067     Assembler::mulpd(dst, as_Address(src));
3068   } else {
3069     lea(rscratch1, src);
3070     Assembler::mulpd(dst, Address(rscratch1, 0));
3071   }
3072 }
3073 
3074 void MacroAssembler::increase_precision() {
3075   subptr(rsp, BytesPerWord);
3076   fnstcw(Address(rsp, 0));
3077   movl(rax, Address(rsp, 0));
3078   orl(rax, 0x300);
3079   push(rax);
3080   fldcw(Address(rsp, 0));
3081   pop(rax);
3082 }
3083 
3084 void MacroAssembler::restore_precision() {
3085   fldcw(Address(rsp, 0));
3086   addptr(rsp, BytesPerWord);
3087 }
3088 
3089 void MacroAssembler::fpop() {
3090   ffree();
3091   fincstp();
3092 }
3093 
3094 void MacroAssembler::load_float(Address src) {
3095   if (UseSSE >= 1) {
3096     movflt(xmm0, src);
3097   } else {
3098     LP64_ONLY(ShouldNotReachHere());
3099     NOT_LP64(fld_s(src));
3100   }
3101 }
3102 
3103 void MacroAssembler::store_float(Address dst) {
3104   if (UseSSE >= 1) {
3105     movflt(dst, xmm0);
3106   } else {
3107     LP64_ONLY(ShouldNotReachHere());
3108     NOT_LP64(fstp_s(dst));
3109   }
3110 }
3111 
3112 void MacroAssembler::load_double(Address src) {
3113   if (UseSSE >= 2) {
3114     movdbl(xmm0, src);
3115   } else {
3116     LP64_ONLY(ShouldNotReachHere());
3117     NOT_LP64(fld_d(src));
3118   }
3119 }
3120 
3121 void MacroAssembler::store_double(Address dst) {
3122   if (UseSSE >= 2) {
3123     movdbl(dst, xmm0);
3124   } else {
3125     LP64_ONLY(ShouldNotReachHere());
3126     NOT_LP64(fstp_d(dst));
3127   }
3128 }
3129 
3130 void MacroAssembler::fremr(Register tmp) {
3131   save_rax(tmp);
3132   { Label L;
3133     bind(L);
3134     fprem();
3135     fwait(); fnstsw_ax();
3136 #ifdef _LP64
3137     testl(rax, 0x400);
3138     jcc(Assembler::notEqual, L);
3139 #else
3140     sahf();
3141     jcc(Assembler::parity, L);
3142 #endif // _LP64
3143   }
3144   restore_rax(tmp);
3145   // Result is in ST0.
3146   // Note: fxch & fpop to get rid of ST1
3147   // (otherwise FPU stack could overflow eventually)
3148   fxch(1);
3149   fpop();
3150 }
3151 
3152 
3153 void MacroAssembler::incrementl(AddressLiteral dst) {
3154   if (reachable(dst)) {
3155     incrementl(as_Address(dst));
3156   } else {
3157     lea(rscratch1, dst);
3158     incrementl(Address(rscratch1, 0));
3159   }
3160 }
3161 
3162 void MacroAssembler::incrementl(ArrayAddress dst) {
3163   incrementl(as_Address(dst));
3164 }
3165 
3166 void MacroAssembler::incrementl(Register reg, int value) {
3167   if (value == min_jint) {addl(reg, value) ; return; }
3168   if (value <  0) { decrementl(reg, -value); return; }
3169   if (value == 0) {                        ; return; }
3170   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3171   /* else */      { addl(reg, value)       ; return; }
3172 }
3173 
3174 void MacroAssembler::incrementl(Address dst, int value) {
3175   if (value == min_jint) {addl(dst, value) ; return; }
3176   if (value <  0) { decrementl(dst, -value); return; }
3177   if (value == 0) {                        ; return; }
3178   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3179   /* else */      { addl(dst, value)       ; return; }
3180 }
3181 
3182 void MacroAssembler::jump(AddressLiteral dst) {
3183   if (reachable(dst)) {
3184     jmp_literal(dst.target(), dst.rspec());
3185   } else {
3186     lea(rscratch1, dst);
3187     jmp(rscratch1);
3188   }
3189 }
3190 
3191 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3192   if (reachable(dst)) {
3193     InstructionMark im(this);
3194     relocate(dst.reloc());
3195     const int short_size = 2;
3196     const int long_size = 6;
3197     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3198     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3199       // 0111 tttn #8-bit disp
3200       emit_int8(0x70 | cc);
3201       emit_int8((offs - short_size) & 0xFF);
3202     } else {
3203       // 0000 1111 1000 tttn #32-bit disp
3204       emit_int8(0x0F);
3205       emit_int8((unsigned char)(0x80 | cc));
3206       emit_int32(offs - long_size);
3207     }
3208   } else {
3209 #ifdef ASSERT
3210     warning("reversing conditional branch");
3211 #endif /* ASSERT */
3212     Label skip;
3213     jccb(reverse[cc], skip);
3214     lea(rscratch1, dst);
3215     Assembler::jmp(rscratch1);
3216     bind(skip);
3217   }
3218 }
3219 
3220 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3221   if (reachable(src)) {
3222     Assembler::ldmxcsr(as_Address(src));
3223   } else {
3224     lea(rscratch1, src);
3225     Assembler::ldmxcsr(Address(rscratch1, 0));
3226   }
3227 }
3228 
3229 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3230   int off;
3231   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3232     off = offset();
3233     movsbl(dst, src); // movsxb
3234   } else {
3235     off = load_unsigned_byte(dst, src);
3236     shll(dst, 24);
3237     sarl(dst, 24);
3238   }
3239   return off;
3240 }
3241 
3242 // Note: load_signed_short used to be called load_signed_word.
3243 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3244 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3245 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3246 int MacroAssembler::load_signed_short(Register dst, Address src) {
3247   int off;
3248   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3249     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3250     // version but this is what 64bit has always done. This seems to imply
3251     // that users are only using 32bits worth.
3252     off = offset();
3253     movswl(dst, src); // movsxw
3254   } else {
3255     off = load_unsigned_short(dst, src);
3256     shll(dst, 16);
3257     sarl(dst, 16);
3258   }
3259   return off;
3260 }
3261 
3262 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3263   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3264   // and "3.9 Partial Register Penalties", p. 22).
3265   int off;
3266   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3267     off = offset();
3268     movzbl(dst, src); // movzxb
3269   } else {
3270     xorl(dst, dst);
3271     off = offset();
3272     movb(dst, src);
3273   }
3274   return off;
3275 }
3276 
3277 // Note: load_unsigned_short used to be called load_unsigned_word.
3278 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3279   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3280   // and "3.9 Partial Register Penalties", p. 22).
3281   int off;
3282   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3283     off = offset();
3284     movzwl(dst, src); // movzxw
3285   } else {
3286     xorl(dst, dst);
3287     off = offset();
3288     movw(dst, src);
3289   }
3290   return off;
3291 }
3292 
3293 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3294   switch (size_in_bytes) {
3295 #ifndef _LP64
3296   case  8:
3297     assert(dst2 != noreg, "second dest register required");
3298     movl(dst,  src);
3299     movl(dst2, src.plus_disp(BytesPerInt));
3300     break;
3301 #else
3302   case  8:  movq(dst, src); break;
3303 #endif
3304   case  4:  movl(dst, src); break;
3305   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3306   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3307   default:  ShouldNotReachHere();
3308   }
3309 }
3310 
3311 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3312   switch (size_in_bytes) {
3313 #ifndef _LP64
3314   case  8:
3315     assert(src2 != noreg, "second source register required");
3316     movl(dst,                        src);
3317     movl(dst.plus_disp(BytesPerInt), src2);
3318     break;
3319 #else
3320   case  8:  movq(dst, src); break;
3321 #endif
3322   case  4:  movl(dst, src); break;
3323   case  2:  movw(dst, src); break;
3324   case  1:  movb(dst, src); break;
3325   default:  ShouldNotReachHere();
3326   }
3327 }
3328 
3329 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3330   if (reachable(dst)) {
3331     movl(as_Address(dst), src);
3332   } else {
3333     lea(rscratch1, dst);
3334     movl(Address(rscratch1, 0), src);
3335   }
3336 }
3337 
3338 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3339   if (reachable(src)) {
3340     movl(dst, as_Address(src));
3341   } else {
3342     lea(rscratch1, src);
3343     movl(dst, Address(rscratch1, 0));
3344   }
3345 }
3346 
3347 // C++ bool manipulation
3348 
3349 void MacroAssembler::movbool(Register dst, Address src) {
3350   if(sizeof(bool) == 1)
3351     movb(dst, src);
3352   else if(sizeof(bool) == 2)
3353     movw(dst, src);
3354   else if(sizeof(bool) == 4)
3355     movl(dst, src);
3356   else
3357     // unsupported
3358     ShouldNotReachHere();
3359 }
3360 
3361 void MacroAssembler::movbool(Address dst, bool boolconst) {
3362   if(sizeof(bool) == 1)
3363     movb(dst, (int) boolconst);
3364   else if(sizeof(bool) == 2)
3365     movw(dst, (int) boolconst);
3366   else if(sizeof(bool) == 4)
3367     movl(dst, (int) boolconst);
3368   else
3369     // unsupported
3370     ShouldNotReachHere();
3371 }
3372 
3373 void MacroAssembler::movbool(Address dst, Register src) {
3374   if(sizeof(bool) == 1)
3375     movb(dst, src);
3376   else if(sizeof(bool) == 2)
3377     movw(dst, src);
3378   else if(sizeof(bool) == 4)
3379     movl(dst, src);
3380   else
3381     // unsupported
3382     ShouldNotReachHere();
3383 }
3384 
3385 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3386   movb(as_Address(dst), src);
3387 }
3388 
3389 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3390   if (reachable(src)) {
3391     movdl(dst, as_Address(src));
3392   } else {
3393     lea(rscratch1, src);
3394     movdl(dst, Address(rscratch1, 0));
3395   }
3396 }
3397 
3398 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3399   if (reachable(src)) {
3400     movq(dst, as_Address(src));
3401   } else {
3402     lea(rscratch1, src);
3403     movq(dst, Address(rscratch1, 0));
3404   }
3405 }
3406 
3407 void MacroAssembler::setvectmask(Register dst, Register src) {
3408   Assembler::movl(dst, 1);
3409   Assembler::shlxl(dst, dst, src);
3410   Assembler::decl(dst);
3411   Assembler::kmovdl(k1, dst);
3412   Assembler::movl(dst, src);
3413 }
3414 
3415 void MacroAssembler::restorevectmask() {
3416   Assembler::knotwl(k1, k0);
3417 }
3418 
3419 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3420   if (reachable(src)) {
3421     if (UseXmmLoadAndClearUpper) {
3422       movsd (dst, as_Address(src));
3423     } else {
3424       movlpd(dst, as_Address(src));
3425     }
3426   } else {
3427     lea(rscratch1, src);
3428     if (UseXmmLoadAndClearUpper) {
3429       movsd (dst, Address(rscratch1, 0));
3430     } else {
3431       movlpd(dst, Address(rscratch1, 0));
3432     }
3433   }
3434 }
3435 
3436 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3437   if (reachable(src)) {
3438     movss(dst, as_Address(src));
3439   } else {
3440     lea(rscratch1, src);
3441     movss(dst, Address(rscratch1, 0));
3442   }
3443 }
3444 
3445 void MacroAssembler::movptr(Register dst, Register src) {
3446   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3447 }
3448 
3449 void MacroAssembler::movptr(Register dst, Address src) {
3450   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3451 }
3452 
3453 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3454 void MacroAssembler::movptr(Register dst, intptr_t src) {
3455   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3456 }
3457 
3458 void MacroAssembler::movptr(Address dst, Register src) {
3459   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3460 }
3461 
3462 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3463   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3464     Assembler::vextractf32x4(dst, src, 0);
3465   } else {
3466     Assembler::movdqu(dst, src);
3467   }
3468 }
3469 
3470 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3471   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3472     Assembler::vinsertf32x4(dst, dst, src, 0);
3473   } else {
3474     Assembler::movdqu(dst, src);
3475   }
3476 }
3477 
3478 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3479   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3480     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3481   } else {
3482     Assembler::movdqu(dst, src);
3483   }
3484 }
3485 
3486 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src) {
3487   if (reachable(src)) {
3488     movdqu(dst, as_Address(src));
3489   } else {
3490     lea(rscratch1, src);
3491     movdqu(dst, Address(rscratch1, 0));
3492   }
3493 }
3494 
3495 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3496   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3497     vextractf64x4_low(dst, src);
3498   } else {
3499     Assembler::vmovdqu(dst, src);
3500   }
3501 }
3502 
3503 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3504   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3505     vinsertf64x4_low(dst, src);
3506   } else {
3507     Assembler::vmovdqu(dst, src);
3508   }
3509 }
3510 
3511 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3512   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3513     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3514   }
3515   else {
3516     Assembler::vmovdqu(dst, src);
3517   }
3518 }
3519 
3520 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3521   if (reachable(src)) {
3522     vmovdqu(dst, as_Address(src));
3523   }
3524   else {
3525     lea(rscratch1, src);
3526     vmovdqu(dst, Address(rscratch1, 0));
3527   }
3528 }
3529 
3530 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3531   if (reachable(src)) {
3532     Assembler::movdqa(dst, as_Address(src));
3533   } else {
3534     lea(rscratch1, src);
3535     Assembler::movdqa(dst, Address(rscratch1, 0));
3536   }
3537 }
3538 
3539 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3540   if (reachable(src)) {
3541     Assembler::movsd(dst, as_Address(src));
3542   } else {
3543     lea(rscratch1, src);
3544     Assembler::movsd(dst, Address(rscratch1, 0));
3545   }
3546 }
3547 
3548 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3549   if (reachable(src)) {
3550     Assembler::movss(dst, as_Address(src));
3551   } else {
3552     lea(rscratch1, src);
3553     Assembler::movss(dst, Address(rscratch1, 0));
3554   }
3555 }
3556 
3557 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3558   if (reachable(src)) {
3559     Assembler::mulsd(dst, as_Address(src));
3560   } else {
3561     lea(rscratch1, src);
3562     Assembler::mulsd(dst, Address(rscratch1, 0));
3563   }
3564 }
3565 
3566 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3567   if (reachable(src)) {
3568     Assembler::mulss(dst, as_Address(src));
3569   } else {
3570     lea(rscratch1, src);
3571     Assembler::mulss(dst, Address(rscratch1, 0));
3572   }
3573 }
3574 
3575 void MacroAssembler::null_check(Register reg, int offset) {
3576   if (needs_explicit_null_check(offset)) {
3577     // provoke OS NULL exception if reg = NULL by
3578     // accessing M[reg] w/o changing any (non-CC) registers
3579     // NOTE: cmpl is plenty here to provoke a segv
3580     cmpptr(rax, Address(reg, 0));
3581     // Note: should probably use testl(rax, Address(reg, 0));
3582     //       may be shorter code (however, this version of
3583     //       testl needs to be implemented first)
3584   } else {
3585     // nothing to do, (later) access of M[reg + offset]
3586     // will provoke OS NULL exception if reg = NULL
3587   }
3588 }
3589 
3590 void MacroAssembler::os_breakpoint() {
3591   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3592   // (e.g., MSVC can't call ps() otherwise)
3593   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3594 }
3595 
3596 #ifdef _LP64
3597 #define XSTATE_BV 0x200
3598 #endif
3599 
3600 void MacroAssembler::pop_CPU_state() {
3601   pop_FPU_state();
3602   pop_IU_state();
3603 }
3604 
3605 void MacroAssembler::pop_FPU_state() {
3606 #ifndef _LP64
3607   frstor(Address(rsp, 0));
3608 #else
3609   fxrstor(Address(rsp, 0));
3610 #endif
3611   addptr(rsp, FPUStateSizeInWords * wordSize);
3612 }
3613 
3614 void MacroAssembler::pop_IU_state() {
3615   popa();
3616   LP64_ONLY(addq(rsp, 8));
3617   popf();
3618 }
3619 
3620 // Save Integer and Float state
3621 // Warning: Stack must be 16 byte aligned (64bit)
3622 void MacroAssembler::push_CPU_state() {
3623   push_IU_state();
3624   push_FPU_state();
3625 }
3626 
3627 void MacroAssembler::push_FPU_state() {
3628   subptr(rsp, FPUStateSizeInWords * wordSize);
3629 #ifndef _LP64
3630   fnsave(Address(rsp, 0));
3631   fwait();
3632 #else
3633   fxsave(Address(rsp, 0));
3634 #endif // LP64
3635 }
3636 
3637 void MacroAssembler::push_IU_state() {
3638   // Push flags first because pusha kills them
3639   pushf();
3640   // Make sure rsp stays 16-byte aligned
3641   LP64_ONLY(subq(rsp, 8));
3642   pusha();
3643 }
3644 
3645 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp, bool clear_pc) {
3646   // determine java_thread register
3647   if (!java_thread->is_valid()) {
3648     java_thread = rdi;
3649     get_thread(java_thread);
3650   }
3651   // we must set sp to zero to clear frame
3652   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3653   if (clear_fp) {
3654     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3655   }
3656 
3657   if (clear_pc)
3658     movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3659 
3660 }
3661 
3662 void MacroAssembler::restore_rax(Register tmp) {
3663   if (tmp == noreg) pop(rax);
3664   else if (tmp != rax) mov(rax, tmp);
3665 }
3666 
3667 void MacroAssembler::round_to(Register reg, int modulus) {
3668   addptr(reg, modulus - 1);
3669   andptr(reg, -modulus);
3670 }
3671 
3672 void MacroAssembler::save_rax(Register tmp) {
3673   if (tmp == noreg) push(rax);
3674   else if (tmp != rax) mov(tmp, rax);
3675 }
3676 
3677 // Write serialization page so VM thread can do a pseudo remote membar.
3678 // We use the current thread pointer to calculate a thread specific
3679 // offset to write to within the page. This minimizes bus traffic
3680 // due to cache line collision.
3681 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3682   movl(tmp, thread);
3683   shrl(tmp, os::get_serialize_page_shift_count());
3684   andl(tmp, (os::vm_page_size() - sizeof(int)));
3685 
3686   Address index(noreg, tmp, Address::times_1);
3687   ExternalAddress page(os::get_memory_serialize_page());
3688 
3689   // Size of store must match masking code above
3690   movl(as_Address(ArrayAddress(page, index)), tmp);
3691 }
3692 
3693 // Calls to C land
3694 //
3695 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3696 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3697 // has to be reset to 0. This is required to allow proper stack traversal.
3698 void MacroAssembler::set_last_Java_frame(Register java_thread,
3699                                          Register last_java_sp,
3700                                          Register last_java_fp,
3701                                          address  last_java_pc) {
3702   // determine java_thread register
3703   if (!java_thread->is_valid()) {
3704     java_thread = rdi;
3705     get_thread(java_thread);
3706   }
3707   // determine last_java_sp register
3708   if (!last_java_sp->is_valid()) {
3709     last_java_sp = rsp;
3710   }
3711 
3712   // last_java_fp is optional
3713 
3714   if (last_java_fp->is_valid()) {
3715     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3716   }
3717 
3718   // last_java_pc is optional
3719 
3720   if (last_java_pc != NULL) {
3721     lea(Address(java_thread,
3722                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3723         InternalAddress(last_java_pc));
3724 
3725   }
3726   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3727 }
3728 
3729 void MacroAssembler::shlptr(Register dst, int imm8) {
3730   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3731 }
3732 
3733 void MacroAssembler::shrptr(Register dst, int imm8) {
3734   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3735 }
3736 
3737 void MacroAssembler::sign_extend_byte(Register reg) {
3738   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3739     movsbl(reg, reg); // movsxb
3740   } else {
3741     shll(reg, 24);
3742     sarl(reg, 24);
3743   }
3744 }
3745 
3746 void MacroAssembler::sign_extend_short(Register reg) {
3747   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3748     movswl(reg, reg); // movsxw
3749   } else {
3750     shll(reg, 16);
3751     sarl(reg, 16);
3752   }
3753 }
3754 
3755 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3756   assert(reachable(src), "Address should be reachable");
3757   testl(dst, as_Address(src));
3758 }
3759 
3760 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3761   int dst_enc = dst->encoding();
3762   int src_enc = src->encoding();
3763   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3764     Assembler::pcmpeqb(dst, src);
3765   } else if ((dst_enc < 16) && (src_enc < 16)) {
3766     Assembler::pcmpeqb(dst, src);
3767   } else if (src_enc < 16) {
3768     subptr(rsp, 64);
3769     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3770     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3771     Assembler::pcmpeqb(xmm0, src);
3772     movdqu(dst, xmm0);
3773     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3774     addptr(rsp, 64);
3775   } else if (dst_enc < 16) {
3776     subptr(rsp, 64);
3777     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3778     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3779     Assembler::pcmpeqb(dst, xmm0);
3780     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3781     addptr(rsp, 64);
3782   } else {
3783     subptr(rsp, 64);
3784     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3785     subptr(rsp, 64);
3786     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3787     movdqu(xmm0, src);
3788     movdqu(xmm1, dst);
3789     Assembler::pcmpeqb(xmm1, xmm0);
3790     movdqu(dst, xmm1);
3791     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3792     addptr(rsp, 64);
3793     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3794     addptr(rsp, 64);
3795   }
3796 }
3797 
3798 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3799   int dst_enc = dst->encoding();
3800   int src_enc = src->encoding();
3801   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3802     Assembler::pcmpeqw(dst, src);
3803   } else if ((dst_enc < 16) && (src_enc < 16)) {
3804     Assembler::pcmpeqw(dst, src);
3805   } else if (src_enc < 16) {
3806     subptr(rsp, 64);
3807     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3808     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3809     Assembler::pcmpeqw(xmm0, src);
3810     movdqu(dst, xmm0);
3811     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3812     addptr(rsp, 64);
3813   } else if (dst_enc < 16) {
3814     subptr(rsp, 64);
3815     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3816     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3817     Assembler::pcmpeqw(dst, xmm0);
3818     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3819     addptr(rsp, 64);
3820   } else {
3821     subptr(rsp, 64);
3822     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3823     subptr(rsp, 64);
3824     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3825     movdqu(xmm0, src);
3826     movdqu(xmm1, dst);
3827     Assembler::pcmpeqw(xmm1, xmm0);
3828     movdqu(dst, xmm1);
3829     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3830     addptr(rsp, 64);
3831     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3832     addptr(rsp, 64);
3833   }
3834 }
3835 
3836 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3837   int dst_enc = dst->encoding();
3838   if (dst_enc < 16) {
3839     Assembler::pcmpestri(dst, src, imm8);
3840   } else {
3841     subptr(rsp, 64);
3842     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3843     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3844     Assembler::pcmpestri(xmm0, src, imm8);
3845     movdqu(dst, xmm0);
3846     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3847     addptr(rsp, 64);
3848   }
3849 }
3850 
3851 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3852   int dst_enc = dst->encoding();
3853   int src_enc = src->encoding();
3854   if ((dst_enc < 16) && (src_enc < 16)) {
3855     Assembler::pcmpestri(dst, src, imm8);
3856   } else if (src_enc < 16) {
3857     subptr(rsp, 64);
3858     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3859     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3860     Assembler::pcmpestri(xmm0, src, imm8);
3861     movdqu(dst, xmm0);
3862     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3863     addptr(rsp, 64);
3864   } else if (dst_enc < 16) {
3865     subptr(rsp, 64);
3866     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3867     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3868     Assembler::pcmpestri(dst, xmm0, imm8);
3869     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3870     addptr(rsp, 64);
3871   } else {
3872     subptr(rsp, 64);
3873     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3874     subptr(rsp, 64);
3875     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3876     movdqu(xmm0, src);
3877     movdqu(xmm1, dst);
3878     Assembler::pcmpestri(xmm1, xmm0, imm8);
3879     movdqu(dst, xmm1);
3880     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3881     addptr(rsp, 64);
3882     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3883     addptr(rsp, 64);
3884   }
3885 }
3886 
3887 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3888   int dst_enc = dst->encoding();
3889   int src_enc = src->encoding();
3890   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3891     Assembler::pmovzxbw(dst, src);
3892   } else if ((dst_enc < 16) && (src_enc < 16)) {
3893     Assembler::pmovzxbw(dst, src);
3894   } else if (src_enc < 16) {
3895     subptr(rsp, 64);
3896     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3897     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3898     Assembler::pmovzxbw(xmm0, src);
3899     movdqu(dst, xmm0);
3900     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3901     addptr(rsp, 64);
3902   } else if (dst_enc < 16) {
3903     subptr(rsp, 64);
3904     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3905     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3906     Assembler::pmovzxbw(dst, xmm0);
3907     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3908     addptr(rsp, 64);
3909   } else {
3910     subptr(rsp, 64);
3911     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3912     subptr(rsp, 64);
3913     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3914     movdqu(xmm0, src);
3915     movdqu(xmm1, dst);
3916     Assembler::pmovzxbw(xmm1, xmm0);
3917     movdqu(dst, xmm1);
3918     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3919     addptr(rsp, 64);
3920     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3921     addptr(rsp, 64);
3922   }
3923 }
3924 
3925 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
3926   int dst_enc = dst->encoding();
3927   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3928     Assembler::pmovzxbw(dst, src);
3929   } else if (dst_enc < 16) {
3930     Assembler::pmovzxbw(dst, src);
3931   } else {
3932     subptr(rsp, 64);
3933     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3934     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3935     Assembler::pmovzxbw(xmm0, src);
3936     movdqu(dst, xmm0);
3937     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3938     addptr(rsp, 64);
3939   }
3940 }
3941 
3942 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
3943   int src_enc = src->encoding();
3944   if (src_enc < 16) {
3945     Assembler::pmovmskb(dst, src);
3946   } else {
3947     subptr(rsp, 64);
3948     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3949     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3950     Assembler::pmovmskb(dst, xmm0);
3951     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3952     addptr(rsp, 64);
3953   }
3954 }
3955 
3956 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
3957   int dst_enc = dst->encoding();
3958   int src_enc = src->encoding();
3959   if ((dst_enc < 16) && (src_enc < 16)) {
3960     Assembler::ptest(dst, src);
3961   } else if (src_enc < 16) {
3962     subptr(rsp, 64);
3963     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3964     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3965     Assembler::ptest(xmm0, src);
3966     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3967     addptr(rsp, 64);
3968   } else if (dst_enc < 16) {
3969     subptr(rsp, 64);
3970     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3971     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3972     Assembler::ptest(dst, xmm0);
3973     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3974     addptr(rsp, 64);
3975   } else {
3976     subptr(rsp, 64);
3977     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3978     subptr(rsp, 64);
3979     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3980     movdqu(xmm0, src);
3981     movdqu(xmm1, dst);
3982     Assembler::ptest(xmm1, xmm0);
3983     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3984     addptr(rsp, 64);
3985     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3986     addptr(rsp, 64);
3987   }
3988 }
3989 
3990 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
3991   if (reachable(src)) {
3992     Assembler::sqrtsd(dst, as_Address(src));
3993   } else {
3994     lea(rscratch1, src);
3995     Assembler::sqrtsd(dst, Address(rscratch1, 0));
3996   }
3997 }
3998 
3999 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4000   if (reachable(src)) {
4001     Assembler::sqrtss(dst, as_Address(src));
4002   } else {
4003     lea(rscratch1, src);
4004     Assembler::sqrtss(dst, Address(rscratch1, 0));
4005   }
4006 }
4007 
4008 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4009   if (reachable(src)) {
4010     Assembler::subsd(dst, as_Address(src));
4011   } else {
4012     lea(rscratch1, src);
4013     Assembler::subsd(dst, Address(rscratch1, 0));
4014   }
4015 }
4016 
4017 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4018   if (reachable(src)) {
4019     Assembler::subss(dst, as_Address(src));
4020   } else {
4021     lea(rscratch1, src);
4022     Assembler::subss(dst, Address(rscratch1, 0));
4023   }
4024 }
4025 
4026 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4027   if (reachable(src)) {
4028     Assembler::ucomisd(dst, as_Address(src));
4029   } else {
4030     lea(rscratch1, src);
4031     Assembler::ucomisd(dst, Address(rscratch1, 0));
4032   }
4033 }
4034 
4035 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4036   if (reachable(src)) {
4037     Assembler::ucomiss(dst, as_Address(src));
4038   } else {
4039     lea(rscratch1, src);
4040     Assembler::ucomiss(dst, Address(rscratch1, 0));
4041   }
4042 }
4043 
4044 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4045   // Used in sign-bit flipping with aligned address.
4046   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4047   if (reachable(src)) {
4048     Assembler::xorpd(dst, as_Address(src));
4049   } else {
4050     lea(rscratch1, src);
4051     Assembler::xorpd(dst, Address(rscratch1, 0));
4052   }
4053 }
4054 
4055 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4056   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4057     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4058   }
4059   else {
4060     Assembler::xorpd(dst, src);
4061   }
4062 }
4063 
4064 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4065   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4066     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4067   } else {
4068     Assembler::xorps(dst, src);
4069   }
4070 }
4071 
4072 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4073   // Used in sign-bit flipping with aligned address.
4074   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4075   if (reachable(src)) {
4076     Assembler::xorps(dst, as_Address(src));
4077   } else {
4078     lea(rscratch1, src);
4079     Assembler::xorps(dst, Address(rscratch1, 0));
4080   }
4081 }
4082 
4083 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4084   // Used in sign-bit flipping with aligned address.
4085   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4086   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4087   if (reachable(src)) {
4088     Assembler::pshufb(dst, as_Address(src));
4089   } else {
4090     lea(rscratch1, src);
4091     Assembler::pshufb(dst, Address(rscratch1, 0));
4092   }
4093 }
4094 
4095 // AVX 3-operands instructions
4096 
4097 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4098   if (reachable(src)) {
4099     vaddsd(dst, nds, as_Address(src));
4100   } else {
4101     lea(rscratch1, src);
4102     vaddsd(dst, nds, Address(rscratch1, 0));
4103   }
4104 }
4105 
4106 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4107   if (reachable(src)) {
4108     vaddss(dst, nds, as_Address(src));
4109   } else {
4110     lea(rscratch1, src);
4111     vaddss(dst, nds, Address(rscratch1, 0));
4112   }
4113 }
4114 
4115 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4116   int dst_enc = dst->encoding();
4117   int nds_enc = nds->encoding();
4118   int src_enc = src->encoding();
4119   if ((dst_enc < 16) && (nds_enc < 16)) {
4120     vandps(dst, nds, negate_field, vector_len);
4121   } else if ((src_enc < 16) && (dst_enc < 16)) {
4122     movss(src, nds);
4123     vandps(dst, src, negate_field, vector_len);
4124   } else if (src_enc < 16) {
4125     movss(src, nds);
4126     vandps(src, src, negate_field, vector_len);
4127     movss(dst, src);
4128   } else if (dst_enc < 16) {
4129     movdqu(src, xmm0);
4130     movss(xmm0, nds);
4131     vandps(dst, xmm0, negate_field, vector_len);
4132     movdqu(xmm0, src);
4133   } else if (nds_enc < 16) {
4134     movdqu(src, xmm0);
4135     vandps(xmm0, nds, negate_field, vector_len);
4136     movss(dst, xmm0);
4137     movdqu(xmm0, src);
4138   } else {
4139     movdqu(src, xmm0);
4140     movss(xmm0, nds);
4141     vandps(xmm0, xmm0, negate_field, vector_len);
4142     movss(dst, xmm0);
4143     movdqu(xmm0, src);
4144   }
4145 }
4146 
4147 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4148   int dst_enc = dst->encoding();
4149   int nds_enc = nds->encoding();
4150   int src_enc = src->encoding();
4151   if ((dst_enc < 16) && (nds_enc < 16)) {
4152     vandpd(dst, nds, negate_field, vector_len);
4153   } else if ((src_enc < 16) && (dst_enc < 16)) {
4154     movsd(src, nds);
4155     vandpd(dst, src, negate_field, vector_len);
4156   } else if (src_enc < 16) {
4157     movsd(src, nds);
4158     vandpd(src, src, negate_field, vector_len);
4159     movsd(dst, src);
4160   } else if (dst_enc < 16) {
4161     movdqu(src, xmm0);
4162     movsd(xmm0, nds);
4163     vandpd(dst, xmm0, negate_field, vector_len);
4164     movdqu(xmm0, src);
4165   } else if (nds_enc < 16) {
4166     movdqu(src, xmm0);
4167     vandpd(xmm0, nds, negate_field, vector_len);
4168     movsd(dst, xmm0);
4169     movdqu(xmm0, src);
4170   } else {
4171     movdqu(src, xmm0);
4172     movsd(xmm0, nds);
4173     vandpd(xmm0, xmm0, negate_field, vector_len);
4174     movsd(dst, xmm0);
4175     movdqu(xmm0, src);
4176   }
4177 }
4178 
4179 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4180   int dst_enc = dst->encoding();
4181   int nds_enc = nds->encoding();
4182   int src_enc = src->encoding();
4183   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4184     Assembler::vpaddb(dst, nds, src, vector_len);
4185   } else if ((dst_enc < 16) && (src_enc < 16)) {
4186     Assembler::vpaddb(dst, dst, src, vector_len);
4187   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4188     // use nds as scratch for src
4189     evmovdqul(nds, src, Assembler::AVX_512bit);
4190     Assembler::vpaddb(dst, dst, nds, vector_len);
4191   } else if ((src_enc < 16) && (nds_enc < 16)) {
4192     // use nds as scratch for dst
4193     evmovdqul(nds, dst, Assembler::AVX_512bit);
4194     Assembler::vpaddb(nds, nds, src, vector_len);
4195     evmovdqul(dst, nds, Assembler::AVX_512bit);
4196   } else if (dst_enc < 16) {
4197     // use nds as scatch for xmm0 to hold src
4198     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4199     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4200     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4201     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4202   } else {
4203     // worse case scenario, all regs are in the upper bank
4204     subptr(rsp, 64);
4205     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4206     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4207     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4208     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4209     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4210     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4211     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4212     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4213     addptr(rsp, 64);
4214   }
4215 }
4216 
4217 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4218   int dst_enc = dst->encoding();
4219   int nds_enc = nds->encoding();
4220   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4221     Assembler::vpaddb(dst, nds, src, vector_len);
4222   } else if (dst_enc < 16) {
4223     Assembler::vpaddb(dst, dst, src, vector_len);
4224   } else if (nds_enc < 16) {
4225     // implies dst_enc in upper bank with src as scratch
4226     evmovdqul(nds, dst, Assembler::AVX_512bit);
4227     Assembler::vpaddb(nds, nds, src, vector_len);
4228     evmovdqul(dst, nds, Assembler::AVX_512bit);
4229   } else {
4230     // worse case scenario, all regs in upper bank
4231     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4232     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4233     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4234     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4235   }
4236 }
4237 
4238 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4239   int dst_enc = dst->encoding();
4240   int nds_enc = nds->encoding();
4241   int src_enc = src->encoding();
4242   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4243     Assembler::vpaddw(dst, nds, src, vector_len);
4244   } else if ((dst_enc < 16) && (src_enc < 16)) {
4245     Assembler::vpaddw(dst, dst, src, vector_len);
4246   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4247     // use nds as scratch for src
4248     evmovdqul(nds, src, Assembler::AVX_512bit);
4249     Assembler::vpaddw(dst, dst, nds, vector_len);
4250   } else if ((src_enc < 16) && (nds_enc < 16)) {
4251     // use nds as scratch for dst
4252     evmovdqul(nds, dst, Assembler::AVX_512bit);
4253     Assembler::vpaddw(nds, nds, src, vector_len);
4254     evmovdqul(dst, nds, Assembler::AVX_512bit);
4255   } else if (dst_enc < 16) {
4256     // use nds as scatch for xmm0 to hold src
4257     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4258     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4259     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4260     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4261   } else {
4262     // worse case scenario, all regs are in the upper bank
4263     subptr(rsp, 64);
4264     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4265     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4266     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4267     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4268     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4269     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4270     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4271     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4272     addptr(rsp, 64);
4273   }
4274 }
4275 
4276 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4277   int dst_enc = dst->encoding();
4278   int nds_enc = nds->encoding();
4279   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4280     Assembler::vpaddw(dst, nds, src, vector_len);
4281   } else if (dst_enc < 16) {
4282     Assembler::vpaddw(dst, dst, src, vector_len);
4283   } else if (nds_enc < 16) {
4284     // implies dst_enc in upper bank with src as scratch
4285     evmovdqul(nds, dst, Assembler::AVX_512bit);
4286     Assembler::vpaddw(nds, nds, src, vector_len);
4287     evmovdqul(dst, nds, Assembler::AVX_512bit);
4288   } else {
4289     // worse case scenario, all regs in upper bank
4290     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4291     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4292     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4293     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4294   }
4295 }
4296 
4297 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4298   int dst_enc = dst->encoding();
4299   int src_enc = src->encoding();
4300   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4301     Assembler::vpbroadcastw(dst, src);
4302   } else if ((dst_enc < 16) && (src_enc < 16)) {
4303     Assembler::vpbroadcastw(dst, src);
4304   } else if (src_enc < 16) {
4305     subptr(rsp, 64);
4306     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4307     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4308     Assembler::vpbroadcastw(xmm0, src);
4309     movdqu(dst, xmm0);
4310     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4311     addptr(rsp, 64);
4312   } else if (dst_enc < 16) {
4313     subptr(rsp, 64);
4314     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4315     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4316     Assembler::vpbroadcastw(dst, xmm0);
4317     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4318     addptr(rsp, 64);
4319   } else {
4320     subptr(rsp, 64);
4321     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4322     subptr(rsp, 64);
4323     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4324     movdqu(xmm0, src);
4325     movdqu(xmm1, dst);
4326     Assembler::vpbroadcastw(xmm1, xmm0);
4327     movdqu(dst, xmm1);
4328     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4329     addptr(rsp, 64);
4330     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4331     addptr(rsp, 64);
4332   }
4333 }
4334 
4335 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4336   int dst_enc = dst->encoding();
4337   int nds_enc = nds->encoding();
4338   int src_enc = src->encoding();
4339   assert(dst_enc == nds_enc, "");
4340   if ((dst_enc < 16) && (src_enc < 16)) {
4341     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4342   } else if (src_enc < 16) {
4343     subptr(rsp, 64);
4344     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4345     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4346     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4347     movdqu(dst, xmm0);
4348     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4349     addptr(rsp, 64);
4350   } else if (dst_enc < 16) {
4351     subptr(rsp, 64);
4352     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4353     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4354     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4355     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4356     addptr(rsp, 64);
4357   } else {
4358     subptr(rsp, 64);
4359     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4360     subptr(rsp, 64);
4361     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4362     movdqu(xmm0, src);
4363     movdqu(xmm1, dst);
4364     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4365     movdqu(dst, xmm1);
4366     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4367     addptr(rsp, 64);
4368     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4369     addptr(rsp, 64);
4370   }
4371 }
4372 
4373 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4374   int dst_enc = dst->encoding();
4375   int nds_enc = nds->encoding();
4376   int src_enc = src->encoding();
4377   assert(dst_enc == nds_enc, "");
4378   if ((dst_enc < 16) && (src_enc < 16)) {
4379     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4380   } else if (src_enc < 16) {
4381     subptr(rsp, 64);
4382     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4383     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4384     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4385     movdqu(dst, xmm0);
4386     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4387     addptr(rsp, 64);
4388   } else if (dst_enc < 16) {
4389     subptr(rsp, 64);
4390     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4391     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4392     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4393     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4394     addptr(rsp, 64);
4395   } else {
4396     subptr(rsp, 64);
4397     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4398     subptr(rsp, 64);
4399     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4400     movdqu(xmm0, src);
4401     movdqu(xmm1, dst);
4402     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4403     movdqu(dst, xmm1);
4404     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4405     addptr(rsp, 64);
4406     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4407     addptr(rsp, 64);
4408   }
4409 }
4410 
4411 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4412   int dst_enc = dst->encoding();
4413   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4414     Assembler::vpmovzxbw(dst, src, vector_len);
4415   } else if (dst_enc < 16) {
4416     Assembler::vpmovzxbw(dst, src, vector_len);
4417   } else {
4418     subptr(rsp, 64);
4419     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4420     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4421     Assembler::vpmovzxbw(xmm0, src, vector_len);
4422     movdqu(dst, xmm0);
4423     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4424     addptr(rsp, 64);
4425   }
4426 }
4427 
4428 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4429   int src_enc = src->encoding();
4430   if (src_enc < 16) {
4431     Assembler::vpmovmskb(dst, src);
4432   } else {
4433     subptr(rsp, 64);
4434     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4435     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4436     Assembler::vpmovmskb(dst, xmm0);
4437     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4438     addptr(rsp, 64);
4439   }
4440 }
4441 
4442 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4443   int dst_enc = dst->encoding();
4444   int nds_enc = nds->encoding();
4445   int src_enc = src->encoding();
4446   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4447     Assembler::vpmullw(dst, nds, src, vector_len);
4448   } else if ((dst_enc < 16) && (src_enc < 16)) {
4449     Assembler::vpmullw(dst, dst, src, vector_len);
4450   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4451     // use nds as scratch for src
4452     evmovdqul(nds, src, Assembler::AVX_512bit);
4453     Assembler::vpmullw(dst, dst, nds, vector_len);
4454   } else if ((src_enc < 16) && (nds_enc < 16)) {
4455     // use nds as scratch for dst
4456     evmovdqul(nds, dst, Assembler::AVX_512bit);
4457     Assembler::vpmullw(nds, nds, src, vector_len);
4458     evmovdqul(dst, nds, Assembler::AVX_512bit);
4459   } else if (dst_enc < 16) {
4460     // use nds as scatch for xmm0 to hold src
4461     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4462     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4463     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4464     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4465   } else {
4466     // worse case scenario, all regs are in the upper bank
4467     subptr(rsp, 64);
4468     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4469     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4470     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4471     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4472     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4473     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4474     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4475     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4476     addptr(rsp, 64);
4477   }
4478 }
4479 
4480 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4481   int dst_enc = dst->encoding();
4482   int nds_enc = nds->encoding();
4483   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4484     Assembler::vpmullw(dst, nds, src, vector_len);
4485   } else if (dst_enc < 16) {
4486     Assembler::vpmullw(dst, dst, src, vector_len);
4487   } else if (nds_enc < 16) {
4488     // implies dst_enc in upper bank with src as scratch
4489     evmovdqul(nds, dst, Assembler::AVX_512bit);
4490     Assembler::vpmullw(nds, nds, src, vector_len);
4491     evmovdqul(dst, nds, Assembler::AVX_512bit);
4492   } else {
4493     // worse case scenario, all regs in upper bank
4494     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4495     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4496     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4497     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4498   }
4499 }
4500 
4501 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4502   int dst_enc = dst->encoding();
4503   int nds_enc = nds->encoding();
4504   int src_enc = src->encoding();
4505   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4506     Assembler::vpsubb(dst, nds, src, vector_len);
4507   } else if ((dst_enc < 16) && (src_enc < 16)) {
4508     Assembler::vpsubb(dst, dst, src, vector_len);
4509   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4510     // use nds as scratch for src
4511     evmovdqul(nds, src, Assembler::AVX_512bit);
4512     Assembler::vpsubb(dst, dst, nds, vector_len);
4513   } else if ((src_enc < 16) && (nds_enc < 16)) {
4514     // use nds as scratch for dst
4515     evmovdqul(nds, dst, Assembler::AVX_512bit);
4516     Assembler::vpsubb(nds, nds, src, vector_len);
4517     evmovdqul(dst, nds, Assembler::AVX_512bit);
4518   } else if (dst_enc < 16) {
4519     // use nds as scatch for xmm0 to hold src
4520     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4521     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4522     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4523     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4524   } else {
4525     // worse case scenario, all regs are in the upper bank
4526     subptr(rsp, 64);
4527     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4528     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4529     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4530     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4531     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4532     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4533     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4534     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4535     addptr(rsp, 64);
4536   }
4537 }
4538 
4539 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4540   int dst_enc = dst->encoding();
4541   int nds_enc = nds->encoding();
4542   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4543     Assembler::vpsubb(dst, nds, src, vector_len);
4544   } else if (dst_enc < 16) {
4545     Assembler::vpsubb(dst, dst, src, vector_len);
4546   } else if (nds_enc < 16) {
4547     // implies dst_enc in upper bank with src as scratch
4548     evmovdqul(nds, dst, Assembler::AVX_512bit);
4549     Assembler::vpsubb(nds, nds, src, vector_len);
4550     evmovdqul(dst, nds, Assembler::AVX_512bit);
4551   } else {
4552     // worse case scenario, all regs in upper bank
4553     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4554     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4555     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4556     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4557   }
4558 }
4559 
4560 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4561   int dst_enc = dst->encoding();
4562   int nds_enc = nds->encoding();
4563   int src_enc = src->encoding();
4564   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4565     Assembler::vpsubw(dst, nds, src, vector_len);
4566   } else if ((dst_enc < 16) && (src_enc < 16)) {
4567     Assembler::vpsubw(dst, dst, src, vector_len);
4568   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4569     // use nds as scratch for src
4570     evmovdqul(nds, src, Assembler::AVX_512bit);
4571     Assembler::vpsubw(dst, dst, nds, vector_len);
4572   } else if ((src_enc < 16) && (nds_enc < 16)) {
4573     // use nds as scratch for dst
4574     evmovdqul(nds, dst, Assembler::AVX_512bit);
4575     Assembler::vpsubw(nds, nds, src, vector_len);
4576     evmovdqul(dst, nds, Assembler::AVX_512bit);
4577   } else if (dst_enc < 16) {
4578     // use nds as scatch for xmm0 to hold src
4579     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4580     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4581     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4582     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4583   } else {
4584     // worse case scenario, all regs are in the upper bank
4585     subptr(rsp, 64);
4586     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4587     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4588     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4589     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4590     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4591     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4592     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4593     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4594     addptr(rsp, 64);
4595   }
4596 }
4597 
4598 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4599   int dst_enc = dst->encoding();
4600   int nds_enc = nds->encoding();
4601   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4602     Assembler::vpsubw(dst, nds, src, vector_len);
4603   } else if (dst_enc < 16) {
4604     Assembler::vpsubw(dst, dst, src, vector_len);
4605   } else if (nds_enc < 16) {
4606     // implies dst_enc in upper bank with src as scratch
4607     evmovdqul(nds, dst, Assembler::AVX_512bit);
4608     Assembler::vpsubw(nds, nds, src, vector_len);
4609     evmovdqul(dst, nds, Assembler::AVX_512bit);
4610   } else {
4611     // worse case scenario, all regs in upper bank
4612     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4613     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4614     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4615     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4616   }
4617 }
4618 
4619 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4620   int dst_enc = dst->encoding();
4621   int nds_enc = nds->encoding();
4622   int shift_enc = shift->encoding();
4623   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4624     Assembler::vpsraw(dst, nds, shift, vector_len);
4625   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4626     Assembler::vpsraw(dst, dst, shift, vector_len);
4627   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4628     // use nds_enc as scratch with shift
4629     evmovdqul(nds, shift, Assembler::AVX_512bit);
4630     Assembler::vpsraw(dst, dst, nds, vector_len);
4631   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4632     // use nds as scratch with dst
4633     evmovdqul(nds, dst, Assembler::AVX_512bit);
4634     Assembler::vpsraw(nds, nds, shift, vector_len);
4635     evmovdqul(dst, nds, Assembler::AVX_512bit);
4636   } else if (dst_enc < 16) {
4637     // use nds to save a copy of xmm0 and hold shift
4638     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4639     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4640     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4641     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4642   } else if (nds_enc < 16) {
4643     // use nds as dest as temps
4644     evmovdqul(nds, dst, Assembler::AVX_512bit);
4645     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4646     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4647     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4648     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4649     evmovdqul(dst, nds, Assembler::AVX_512bit);
4650   } else {
4651     // worse case scenario, all regs are in the upper bank
4652     subptr(rsp, 64);
4653     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4654     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4655     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4656     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4657     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4658     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4659     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4660     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4661     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4662     addptr(rsp, 64);
4663   }
4664 }
4665 
4666 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4667   int dst_enc = dst->encoding();
4668   int nds_enc = nds->encoding();
4669   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4670     Assembler::vpsraw(dst, nds, shift, vector_len);
4671   } else if (dst_enc < 16) {
4672     Assembler::vpsraw(dst, dst, shift, vector_len);
4673   } else if (nds_enc < 16) {
4674     // use nds as scratch
4675     evmovdqul(nds, dst, Assembler::AVX_512bit);
4676     Assembler::vpsraw(nds, nds, shift, vector_len);
4677     evmovdqul(dst, nds, Assembler::AVX_512bit);
4678   } else {
4679     // use nds as scratch for xmm0
4680     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4681     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4682     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4683     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4684   }
4685 }
4686 
4687 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4688   int dst_enc = dst->encoding();
4689   int nds_enc = nds->encoding();
4690   int shift_enc = shift->encoding();
4691   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4692     Assembler::vpsrlw(dst, nds, shift, vector_len);
4693   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4694     Assembler::vpsrlw(dst, dst, shift, vector_len);
4695   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4696     // use nds_enc as scratch with shift
4697     evmovdqul(nds, shift, Assembler::AVX_512bit);
4698     Assembler::vpsrlw(dst, dst, nds, vector_len);
4699   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4700     // use nds as scratch with dst
4701     evmovdqul(nds, dst, Assembler::AVX_512bit);
4702     Assembler::vpsrlw(nds, nds, shift, vector_len);
4703     evmovdqul(dst, nds, Assembler::AVX_512bit);
4704   } else if (dst_enc < 16) {
4705     // use nds to save a copy of xmm0 and hold shift
4706     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4707     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4708     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4709     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4710   } else if (nds_enc < 16) {
4711     // use nds as dest as temps
4712     evmovdqul(nds, dst, Assembler::AVX_512bit);
4713     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4714     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4715     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4716     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4717     evmovdqul(dst, nds, Assembler::AVX_512bit);
4718   } else {
4719     // worse case scenario, all regs are in the upper bank
4720     subptr(rsp, 64);
4721     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4722     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4723     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4724     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4725     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4726     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4727     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4728     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4729     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4730     addptr(rsp, 64);
4731   }
4732 }
4733 
4734 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4735   int dst_enc = dst->encoding();
4736   int nds_enc = nds->encoding();
4737   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4738     Assembler::vpsrlw(dst, nds, shift, vector_len);
4739   } else if (dst_enc < 16) {
4740     Assembler::vpsrlw(dst, dst, shift, vector_len);
4741   } else if (nds_enc < 16) {
4742     // use nds as scratch
4743     evmovdqul(nds, dst, Assembler::AVX_512bit);
4744     Assembler::vpsrlw(nds, nds, shift, vector_len);
4745     evmovdqul(dst, nds, Assembler::AVX_512bit);
4746   } else {
4747     // use nds as scratch for xmm0
4748     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4749     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4750     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4751     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4752   }
4753 }
4754 
4755 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4756   int dst_enc = dst->encoding();
4757   int nds_enc = nds->encoding();
4758   int shift_enc = shift->encoding();
4759   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4760     Assembler::vpsllw(dst, nds, shift, vector_len);
4761   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4762     Assembler::vpsllw(dst, dst, shift, vector_len);
4763   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4764     // use nds_enc as scratch with shift
4765     evmovdqul(nds, shift, Assembler::AVX_512bit);
4766     Assembler::vpsllw(dst, dst, nds, vector_len);
4767   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4768     // use nds as scratch with dst
4769     evmovdqul(nds, dst, Assembler::AVX_512bit);
4770     Assembler::vpsllw(nds, nds, shift, vector_len);
4771     evmovdqul(dst, nds, Assembler::AVX_512bit);
4772   } else if (dst_enc < 16) {
4773     // use nds to save a copy of xmm0 and hold shift
4774     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4775     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4776     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4777     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4778   } else if (nds_enc < 16) {
4779     // use nds as dest as temps
4780     evmovdqul(nds, dst, Assembler::AVX_512bit);
4781     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4782     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4783     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4784     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4785     evmovdqul(dst, nds, Assembler::AVX_512bit);
4786   } else {
4787     // worse case scenario, all regs are in the upper bank
4788     subptr(rsp, 64);
4789     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4790     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4791     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4792     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4793     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4794     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4795     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4796     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4797     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4798     addptr(rsp, 64);
4799   }
4800 }
4801 
4802 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4803   int dst_enc = dst->encoding();
4804   int nds_enc = nds->encoding();
4805   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4806     Assembler::vpsllw(dst, nds, shift, vector_len);
4807   } else if (dst_enc < 16) {
4808     Assembler::vpsllw(dst, dst, shift, vector_len);
4809   } else if (nds_enc < 16) {
4810     // use nds as scratch
4811     evmovdqul(nds, dst, Assembler::AVX_512bit);
4812     Assembler::vpsllw(nds, nds, shift, vector_len);
4813     evmovdqul(dst, nds, Assembler::AVX_512bit);
4814   } else {
4815     // use nds as scratch for xmm0
4816     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4817     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4818     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4819     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4820   }
4821 }
4822 
4823 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4824   int dst_enc = dst->encoding();
4825   int src_enc = src->encoding();
4826   if ((dst_enc < 16) && (src_enc < 16)) {
4827     Assembler::vptest(dst, src);
4828   } else if (src_enc < 16) {
4829     subptr(rsp, 64);
4830     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4831     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4832     Assembler::vptest(xmm0, src);
4833     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4834     addptr(rsp, 64);
4835   } else if (dst_enc < 16) {
4836     subptr(rsp, 64);
4837     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4838     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4839     Assembler::vptest(dst, xmm0);
4840     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4841     addptr(rsp, 64);
4842   } else {
4843     subptr(rsp, 64);
4844     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4845     subptr(rsp, 64);
4846     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4847     movdqu(xmm0, src);
4848     movdqu(xmm1, dst);
4849     Assembler::vptest(xmm1, xmm0);
4850     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4851     addptr(rsp, 64);
4852     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4853     addptr(rsp, 64);
4854   }
4855 }
4856 
4857 // This instruction exists within macros, ergo we cannot control its input
4858 // when emitted through those patterns.
4859 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4860   if (VM_Version::supports_avx512nobw()) {
4861     int dst_enc = dst->encoding();
4862     int src_enc = src->encoding();
4863     if (dst_enc == src_enc) {
4864       if (dst_enc < 16) {
4865         Assembler::punpcklbw(dst, src);
4866       } else {
4867         subptr(rsp, 64);
4868         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4869         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4870         Assembler::punpcklbw(xmm0, xmm0);
4871         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4872         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4873         addptr(rsp, 64);
4874       }
4875     } else {
4876       if ((src_enc < 16) && (dst_enc < 16)) {
4877         Assembler::punpcklbw(dst, src);
4878       } else if (src_enc < 16) {
4879         subptr(rsp, 64);
4880         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4881         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4882         Assembler::punpcklbw(xmm0, src);
4883         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4884         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4885         addptr(rsp, 64);
4886       } else if (dst_enc < 16) {
4887         subptr(rsp, 64);
4888         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4889         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4890         Assembler::punpcklbw(dst, xmm0);
4891         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4892         addptr(rsp, 64);
4893       } else {
4894         subptr(rsp, 64);
4895         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4896         subptr(rsp, 64);
4897         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4898         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4899         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4900         Assembler::punpcklbw(xmm0, xmm1);
4901         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4902         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4903         addptr(rsp, 64);
4904         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4905         addptr(rsp, 64);
4906       }
4907     }
4908   } else {
4909     Assembler::punpcklbw(dst, src);
4910   }
4911 }
4912 
4913 // This instruction exists within macros, ergo we cannot control its input
4914 // when emitted through those patterns.
4915 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
4916   if (VM_Version::supports_avx512nobw()) {
4917     int dst_enc = dst->encoding();
4918     int src_enc = src->encoding();
4919     if (dst_enc == src_enc) {
4920       if (dst_enc < 16) {
4921         Assembler::pshuflw(dst, src, mode);
4922       } else {
4923         subptr(rsp, 64);
4924         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4925         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4926         Assembler::pshuflw(xmm0, xmm0, mode);
4927         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4928         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4929         addptr(rsp, 64);
4930       }
4931     } else {
4932       if ((src_enc < 16) && (dst_enc < 16)) {
4933         Assembler::pshuflw(dst, src, mode);
4934       } else if (src_enc < 16) {
4935         subptr(rsp, 64);
4936         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4937         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4938         Assembler::pshuflw(xmm0, src, mode);
4939         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4940         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4941         addptr(rsp, 64);
4942       } else if (dst_enc < 16) {
4943         subptr(rsp, 64);
4944         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4945         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4946         Assembler::pshuflw(dst, xmm0, mode);
4947         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4948         addptr(rsp, 64);
4949       } else {
4950         subptr(rsp, 64);
4951         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4952         subptr(rsp, 64);
4953         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4954         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4955         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4956         Assembler::pshuflw(xmm0, xmm1, mode);
4957         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4958         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4959         addptr(rsp, 64);
4960         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4961         addptr(rsp, 64);
4962       }
4963     }
4964   } else {
4965     Assembler::pshuflw(dst, src, mode);
4966   }
4967 }
4968 
4969 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4970   if (reachable(src)) {
4971     vandpd(dst, nds, as_Address(src), vector_len);
4972   } else {
4973     lea(rscratch1, src);
4974     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
4975   }
4976 }
4977 
4978 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4979   if (reachable(src)) {
4980     vandps(dst, nds, as_Address(src), vector_len);
4981   } else {
4982     lea(rscratch1, src);
4983     vandps(dst, nds, Address(rscratch1, 0), vector_len);
4984   }
4985 }
4986 
4987 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4988   if (reachable(src)) {
4989     vdivsd(dst, nds, as_Address(src));
4990   } else {
4991     lea(rscratch1, src);
4992     vdivsd(dst, nds, Address(rscratch1, 0));
4993   }
4994 }
4995 
4996 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4997   if (reachable(src)) {
4998     vdivss(dst, nds, as_Address(src));
4999   } else {
5000     lea(rscratch1, src);
5001     vdivss(dst, nds, Address(rscratch1, 0));
5002   }
5003 }
5004 
5005 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5006   if (reachable(src)) {
5007     vmulsd(dst, nds, as_Address(src));
5008   } else {
5009     lea(rscratch1, src);
5010     vmulsd(dst, nds, Address(rscratch1, 0));
5011   }
5012 }
5013 
5014 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5015   if (reachable(src)) {
5016     vmulss(dst, nds, as_Address(src));
5017   } else {
5018     lea(rscratch1, src);
5019     vmulss(dst, nds, Address(rscratch1, 0));
5020   }
5021 }
5022 
5023 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5024   if (reachable(src)) {
5025     vsubsd(dst, nds, as_Address(src));
5026   } else {
5027     lea(rscratch1, src);
5028     vsubsd(dst, nds, Address(rscratch1, 0));
5029   }
5030 }
5031 
5032 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5033   if (reachable(src)) {
5034     vsubss(dst, nds, as_Address(src));
5035   } else {
5036     lea(rscratch1, src);
5037     vsubss(dst, nds, Address(rscratch1, 0));
5038   }
5039 }
5040 
5041 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5042   int nds_enc = nds->encoding();
5043   int dst_enc = dst->encoding();
5044   bool dst_upper_bank = (dst_enc > 15);
5045   bool nds_upper_bank = (nds_enc > 15);
5046   if (VM_Version::supports_avx512novl() &&
5047       (nds_upper_bank || dst_upper_bank)) {
5048     if (dst_upper_bank) {
5049       subptr(rsp, 64);
5050       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5051       movflt(xmm0, nds);
5052       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5053       movflt(dst, xmm0);
5054       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5055       addptr(rsp, 64);
5056     } else {
5057       movflt(dst, nds);
5058       vxorps(dst, dst, src, Assembler::AVX_128bit);
5059     }
5060   } else {
5061     vxorps(dst, nds, src, Assembler::AVX_128bit);
5062   }
5063 }
5064 
5065 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5066   int nds_enc = nds->encoding();
5067   int dst_enc = dst->encoding();
5068   bool dst_upper_bank = (dst_enc > 15);
5069   bool nds_upper_bank = (nds_enc > 15);
5070   if (VM_Version::supports_avx512novl() &&
5071       (nds_upper_bank || dst_upper_bank)) {
5072     if (dst_upper_bank) {
5073       subptr(rsp, 64);
5074       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5075       movdbl(xmm0, nds);
5076       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5077       movdbl(dst, xmm0);
5078       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5079       addptr(rsp, 64);
5080     } else {
5081       movdbl(dst, nds);
5082       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5083     }
5084   } else {
5085     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5086   }
5087 }
5088 
5089 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5090   if (reachable(src)) {
5091     vxorpd(dst, nds, as_Address(src), vector_len);
5092   } else {
5093     lea(rscratch1, src);
5094     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5095   }
5096 }
5097 
5098 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5099   if (reachable(src)) {
5100     vxorps(dst, nds, as_Address(src), vector_len);
5101   } else {
5102     lea(rscratch1, src);
5103     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5104   }
5105 }
5106 
5107 
5108 //////////////////////////////////////////////////////////////////////////////////
5109 #if INCLUDE_ALL_GCS
5110 
5111 void MacroAssembler::g1_write_barrier_pre(Register obj,
5112                                           Register pre_val,
5113                                           Register thread,
5114                                           Register tmp,
5115                                           bool tosca_live,
5116                                           bool expand_call) {
5117 
5118   // If expand_call is true then we expand the call_VM_leaf macro
5119   // directly to skip generating the check by
5120   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5121 
5122 #ifdef _LP64
5123   assert(thread == r15_thread, "must be");
5124 #endif // _LP64
5125 
5126   Label done;
5127   Label runtime;
5128 
5129   assert(pre_val != noreg, "check this code");
5130 
5131   if (obj != noreg) {
5132     assert_different_registers(obj, pre_val, tmp);
5133     assert(pre_val != rax, "check this code");
5134   }
5135 
5136   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5137                                        SATBMarkQueue::byte_offset_of_active()));
5138   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5139                                        SATBMarkQueue::byte_offset_of_index()));
5140   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5141                                        SATBMarkQueue::byte_offset_of_buf()));
5142 
5143 
5144   // Is marking active?
5145   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5146     cmpl(in_progress, 0);
5147   } else {
5148     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5149     cmpb(in_progress, 0);
5150   }
5151   jcc(Assembler::equal, done);
5152 
5153   // Do we need to load the previous value?
5154   if (obj != noreg) {
5155     load_heap_oop(pre_val, Address(obj, 0));
5156   }
5157 
5158   // Is the previous value null?
5159   cmpptr(pre_val, (int32_t) NULL_WORD);
5160   jcc(Assembler::equal, done);
5161 
5162   // Can we store original value in the thread's buffer?
5163   // Is index == 0?
5164   // (The index field is typed as size_t.)
5165 
5166   movptr(tmp, index);                   // tmp := *index_adr
5167   cmpptr(tmp, 0);                       // tmp == 0?
5168   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5169 
5170   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5171   movptr(index, tmp);                   // *index_adr := tmp
5172   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5173 
5174   // Record the previous value
5175   movptr(Address(tmp, 0), pre_val);
5176   jmp(done);
5177 
5178   bind(runtime);
5179   // save the live input values
5180   if(tosca_live) push(rax);
5181 
5182   if (obj != noreg && obj != rax)
5183     push(obj);
5184 
5185   if (pre_val != rax)
5186     push(pre_val);
5187 
5188   // Calling the runtime using the regular call_VM_leaf mechanism generates
5189   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5190   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5191   //
5192   // If we care generating the pre-barrier without a frame (e.g. in the
5193   // intrinsified Reference.get() routine) then ebp might be pointing to
5194   // the caller frame and so this check will most likely fail at runtime.
5195   //
5196   // Expanding the call directly bypasses the generation of the check.
5197   // So when we do not have have a full interpreter frame on the stack
5198   // expand_call should be passed true.
5199 
5200   NOT_LP64( push(thread); )
5201 
5202   if (expand_call) {
5203     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5204     pass_arg1(this, thread);
5205     pass_arg0(this, pre_val);
5206     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5207   } else {
5208     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5209   }
5210 
5211   NOT_LP64( pop(thread); )
5212 
5213   // save the live input values
5214   if (pre_val != rax)
5215     pop(pre_val);
5216 
5217   if (obj != noreg && obj != rax)
5218     pop(obj);
5219 
5220   if(tosca_live) pop(rax);
5221 
5222   bind(done);
5223 }
5224 
5225 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5226                                            Register new_val,
5227                                            Register thread,
5228                                            Register tmp,
5229                                            Register tmp2) {
5230 #ifdef _LP64
5231   assert(thread == r15_thread, "must be");
5232 #endif // _LP64
5233 
5234   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5235                                        DirtyCardQueue::byte_offset_of_index()));
5236   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5237                                        DirtyCardQueue::byte_offset_of_buf()));
5238 
5239   CardTableModRefBS* ct =
5240     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5241   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5242 
5243   Label done;
5244   Label runtime;
5245 
5246   // Does store cross heap regions?
5247 
5248   movptr(tmp, store_addr);
5249   xorptr(tmp, new_val);
5250   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5251   jcc(Assembler::equal, done);
5252 
5253   // crosses regions, storing NULL?
5254 
5255   cmpptr(new_val, (int32_t) NULL_WORD);
5256   jcc(Assembler::equal, done);
5257 
5258   // storing region crossing non-NULL, is card already dirty?
5259 
5260   const Register card_addr = tmp;
5261   const Register cardtable = tmp2;
5262 
5263   movptr(card_addr, store_addr);
5264   shrptr(card_addr, CardTableModRefBS::card_shift);
5265   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5266   // a valid address and therefore is not properly handled by the relocation code.
5267   movptr(cardtable, (intptr_t)ct->byte_map_base);
5268   addptr(card_addr, cardtable);
5269 
5270   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5271   jcc(Assembler::equal, done);
5272 
5273   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5274   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5275   jcc(Assembler::equal, done);
5276 
5277 
5278   // storing a region crossing, non-NULL oop, card is clean.
5279   // dirty card and log.
5280 
5281   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5282 
5283   cmpl(queue_index, 0);
5284   jcc(Assembler::equal, runtime);
5285   subl(queue_index, wordSize);
5286   movptr(tmp2, buffer);
5287 #ifdef _LP64
5288   movslq(rscratch1, queue_index);
5289   addq(tmp2, rscratch1);
5290   movq(Address(tmp2, 0), card_addr);
5291 #else
5292   addl(tmp2, queue_index);
5293   movl(Address(tmp2, 0), card_addr);
5294 #endif
5295   jmp(done);
5296 
5297   bind(runtime);
5298   // save the live input values
5299   push(store_addr);
5300   push(new_val);
5301 #ifdef _LP64
5302   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5303 #else
5304   push(thread);
5305   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5306   pop(thread);
5307 #endif
5308   pop(new_val);
5309   pop(store_addr);
5310 
5311   bind(done);
5312 }
5313 
5314 #endif // INCLUDE_ALL_GCS
5315 //////////////////////////////////////////////////////////////////////////////////
5316 
5317 
5318 void MacroAssembler::store_check(Register obj, Address dst) {
5319   store_check(obj);
5320 }
5321 
5322 void MacroAssembler::store_check(Register obj) {
5323   // Does a store check for the oop in register obj. The content of
5324   // register obj is destroyed afterwards.
5325   BarrierSet* bs = Universe::heap()->barrier_set();
5326   assert(bs->kind() == BarrierSet::CardTableForRS ||
5327          bs->kind() == BarrierSet::CardTableExtension,
5328          "Wrong barrier set kind");
5329 
5330   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5331   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5332 
5333   shrptr(obj, CardTableModRefBS::card_shift);
5334 
5335   Address card_addr;
5336 
5337   // The calculation for byte_map_base is as follows:
5338   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5339   // So this essentially converts an address to a displacement and it will
5340   // never need to be relocated. On 64bit however the value may be too
5341   // large for a 32bit displacement.
5342   intptr_t disp = (intptr_t) ct->byte_map_base;
5343   if (is_simm32(disp)) {
5344     card_addr = Address(noreg, obj, Address::times_1, disp);
5345   } else {
5346     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5347     // displacement and done in a single instruction given favorable mapping and a
5348     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5349     // entry and that entry is not properly handled by the relocation code.
5350     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5351     Address index(noreg, obj, Address::times_1);
5352     card_addr = as_Address(ArrayAddress(cardtable, index));
5353   }
5354 
5355   int dirty = CardTableModRefBS::dirty_card_val();
5356   if (UseCondCardMark) {
5357     Label L_already_dirty;
5358     if (UseConcMarkSweepGC) {
5359       membar(Assembler::StoreLoad);
5360     }
5361     cmpb(card_addr, dirty);
5362     jcc(Assembler::equal, L_already_dirty);
5363     movb(card_addr, dirty);
5364     bind(L_already_dirty);
5365   } else {
5366     movb(card_addr, dirty);
5367   }
5368 }
5369 
5370 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5371   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5372 }
5373 
5374 // Force generation of a 4 byte immediate value even if it fits into 8bit
5375 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5376   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5377 }
5378 
5379 void MacroAssembler::subptr(Register dst, Register src) {
5380   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5381 }
5382 
5383 // C++ bool manipulation
5384 void MacroAssembler::testbool(Register dst) {
5385   if(sizeof(bool) == 1)
5386     testb(dst, 0xff);
5387   else if(sizeof(bool) == 2) {
5388     // testw implementation needed for two byte bools
5389     ShouldNotReachHere();
5390   } else if(sizeof(bool) == 4)
5391     testl(dst, dst);
5392   else
5393     // unsupported
5394     ShouldNotReachHere();
5395 }
5396 
5397 void MacroAssembler::testptr(Register dst, Register src) {
5398   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5399 }
5400 
5401 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5402 void MacroAssembler::tlab_allocate(Register obj,
5403                                    Register var_size_in_bytes,
5404                                    int con_size_in_bytes,
5405                                    Register t1,
5406                                    Register t2,
5407                                    Label& slow_case) {
5408   assert_different_registers(obj, t1, t2);
5409   assert_different_registers(obj, var_size_in_bytes, t1);
5410   Register end = t2;
5411   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5412 
5413   verify_tlab();
5414 
5415   NOT_LP64(get_thread(thread));
5416 
5417   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5418   if (var_size_in_bytes == noreg) {
5419     lea(end, Address(obj, con_size_in_bytes));
5420   } else {
5421     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5422   }
5423   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5424   jcc(Assembler::above, slow_case);
5425 
5426   // update the tlab top pointer
5427   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5428 
5429   // recover var_size_in_bytes if necessary
5430   if (var_size_in_bytes == end) {
5431     subptr(var_size_in_bytes, obj);
5432   }
5433   verify_tlab();
5434 }
5435 
5436 // Preserves rbx, and rdx.
5437 Register MacroAssembler::tlab_refill(Label& retry,
5438                                      Label& try_eden,
5439                                      Label& slow_case) {
5440   Register top = rax;
5441   Register t1  = rcx; // object size
5442   Register t2  = rsi;
5443   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5444   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5445   Label do_refill, discard_tlab;
5446 
5447   if (!Universe::heap()->supports_inline_contig_alloc()) {
5448     // No allocation in the shared eden.
5449     jmp(slow_case);
5450   }
5451 
5452   NOT_LP64(get_thread(thread_reg));
5453 
5454   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5455   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5456 
5457   // calculate amount of free space
5458   subptr(t1, top);
5459   shrptr(t1, LogHeapWordSize);
5460 
5461   // Retain tlab and allocate object in shared space if
5462   // the amount free in the tlab is too large to discard.
5463   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5464   jcc(Assembler::lessEqual, discard_tlab);
5465 
5466   // Retain
5467   // %%% yuck as movptr...
5468   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5469   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5470   if (TLABStats) {
5471     // increment number of slow_allocations
5472     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5473   }
5474   jmp(try_eden);
5475 
5476   bind(discard_tlab);
5477   if (TLABStats) {
5478     // increment number of refills
5479     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5480     // accumulate wastage -- t1 is amount free in tlab
5481     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5482   }
5483 
5484   // if tlab is currently allocated (top or end != null) then
5485   // fill [top, end + alignment_reserve) with array object
5486   testptr(top, top);
5487   jcc(Assembler::zero, do_refill);
5488 
5489   // set up the mark word
5490   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5491   // set the length to the remaining space
5492   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5493   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5494   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5495   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5496   // set klass to intArrayKlass
5497   // dubious reloc why not an oop reloc?
5498   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5499   // store klass last.  concurrent gcs assumes klass length is valid if
5500   // klass field is not null.
5501   store_klass(top, t1);
5502 
5503   movptr(t1, top);
5504   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5505   incr_allocated_bytes(thread_reg, t1, 0);
5506 
5507   // refill the tlab with an eden allocation
5508   bind(do_refill);
5509   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5510   shlptr(t1, LogHeapWordSize);
5511   // allocate new tlab, address returned in top
5512   eden_allocate(top, t1, 0, t2, slow_case);
5513 
5514   // Check that t1 was preserved in eden_allocate.
5515 #ifdef ASSERT
5516   if (UseTLAB) {
5517     Label ok;
5518     Register tsize = rsi;
5519     assert_different_registers(tsize, thread_reg, t1);
5520     push(tsize);
5521     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5522     shlptr(tsize, LogHeapWordSize);
5523     cmpptr(t1, tsize);
5524     jcc(Assembler::equal, ok);
5525     STOP("assert(t1 != tlab size)");
5526     should_not_reach_here();
5527 
5528     bind(ok);
5529     pop(tsize);
5530   }
5531 #endif
5532   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5533   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5534   addptr(top, t1);
5535   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5536   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5537 
5538   if (ZeroTLAB) {
5539     // This is a fast TLAB refill, therefore the GC is not notified of it.
5540     // So compiled code must fill the new TLAB with zeroes.
5541     movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5542     zero_memory(top, t1, 0, t2);
5543   }
5544 
5545   verify_tlab();
5546   jmp(retry);
5547 
5548   return thread_reg; // for use by caller
5549 }
5550 
5551 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5552 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5553   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5554   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5555   Label done;
5556 
5557   testptr(length_in_bytes, length_in_bytes);
5558   jcc(Assembler::zero, done);
5559 
5560   // initialize topmost word, divide index by 2, check if odd and test if zero
5561   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5562 #ifdef ASSERT
5563   {
5564     Label L;
5565     testptr(length_in_bytes, BytesPerWord - 1);
5566     jcc(Assembler::zero, L);
5567     stop("length must be a multiple of BytesPerWord");
5568     bind(L);
5569   }
5570 #endif
5571   Register index = length_in_bytes;
5572   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5573   if (UseIncDec) {
5574     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5575   } else {
5576     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5577     shrptr(index, 1);
5578   }
5579 #ifndef _LP64
5580   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5581   {
5582     Label even;
5583     // note: if index was a multiple of 8, then it cannot
5584     //       be 0 now otherwise it must have been 0 before
5585     //       => if it is even, we don't need to check for 0 again
5586     jcc(Assembler::carryClear, even);
5587     // clear topmost word (no jump would be needed if conditional assignment worked here)
5588     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5589     // index could be 0 now, must check again
5590     jcc(Assembler::zero, done);
5591     bind(even);
5592   }
5593 #endif // !_LP64
5594   // initialize remaining object fields: index is a multiple of 2 now
5595   {
5596     Label loop;
5597     bind(loop);
5598     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5599     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5600     decrement(index);
5601     jcc(Assembler::notZero, loop);
5602   }
5603 
5604   bind(done);
5605 }
5606 
5607 void MacroAssembler::incr_allocated_bytes(Register thread,
5608                                           Register var_size_in_bytes,
5609                                           int con_size_in_bytes,
5610                                           Register t1) {
5611   if (!thread->is_valid()) {
5612 #ifdef _LP64
5613     thread = r15_thread;
5614 #else
5615     assert(t1->is_valid(), "need temp reg");
5616     thread = t1;
5617     get_thread(thread);
5618 #endif
5619   }
5620 
5621 #ifdef _LP64
5622   if (var_size_in_bytes->is_valid()) {
5623     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5624   } else {
5625     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5626   }
5627 #else
5628   if (var_size_in_bytes->is_valid()) {
5629     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5630   } else {
5631     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5632   }
5633   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5634 #endif
5635 }
5636 
5637 // Look up the method for a megamorphic invokeinterface call.
5638 // The target method is determined by <intf_klass, itable_index>.
5639 // The receiver klass is in recv_klass.
5640 // On success, the result will be in method_result, and execution falls through.
5641 // On failure, execution transfers to the given label.
5642 void MacroAssembler::lookup_interface_method(Register recv_klass,
5643                                              Register intf_klass,
5644                                              RegisterOrConstant itable_index,
5645                                              Register method_result,
5646                                              Register scan_temp,
5647                                              Label& L_no_such_interface) {
5648   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5649   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5650          "caller must use same register for non-constant itable index as for method");
5651 
5652   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5653   int vtable_base = in_bytes(Klass::vtable_start_offset());
5654   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5655   int scan_step   = itableOffsetEntry::size() * wordSize;
5656   int vte_size    = vtableEntry::size_in_bytes();
5657   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5658   assert(vte_size == wordSize, "else adjust times_vte_scale");
5659 
5660   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5661 
5662   // %%% Could store the aligned, prescaled offset in the klassoop.
5663   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5664 
5665   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5666   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5667   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5668 
5669   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5670   //   if (scan->interface() == intf) {
5671   //     result = (klass + scan->offset() + itable_index);
5672   //   }
5673   // }
5674   Label search, found_method;
5675 
5676   for (int peel = 1; peel >= 0; peel--) {
5677     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5678     cmpptr(intf_klass, method_result);
5679 
5680     if (peel) {
5681       jccb(Assembler::equal, found_method);
5682     } else {
5683       jccb(Assembler::notEqual, search);
5684       // (invert the test to fall through to found_method...)
5685     }
5686 
5687     if (!peel)  break;
5688 
5689     bind(search);
5690 
5691     // Check that the previous entry is non-null.  A null entry means that
5692     // the receiver class doesn't implement the interface, and wasn't the
5693     // same as when the caller was compiled.
5694     testptr(method_result, method_result);
5695     jcc(Assembler::zero, L_no_such_interface);
5696     addptr(scan_temp, scan_step);
5697   }
5698 
5699   bind(found_method);
5700 
5701   // Got a hit.
5702   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5703   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5704 }
5705 
5706 
5707 // virtual method calling
5708 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5709                                            RegisterOrConstant vtable_index,
5710                                            Register method_result) {
5711   const int base = in_bytes(Klass::vtable_start_offset());
5712   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5713   Address vtable_entry_addr(recv_klass,
5714                             vtable_index, Address::times_ptr,
5715                             base + vtableEntry::method_offset_in_bytes());
5716   movptr(method_result, vtable_entry_addr);
5717 }
5718 
5719 
5720 void MacroAssembler::check_klass_subtype(Register sub_klass,
5721                            Register super_klass,
5722                            Register temp_reg,
5723                            Label& L_success) {
5724   Label L_failure;
5725   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5726   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5727   bind(L_failure);
5728 }
5729 
5730 
5731 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5732                                                    Register super_klass,
5733                                                    Register temp_reg,
5734                                                    Label* L_success,
5735                                                    Label* L_failure,
5736                                                    Label* L_slow_path,
5737                                         RegisterOrConstant super_check_offset) {
5738   assert_different_registers(sub_klass, super_klass, temp_reg);
5739   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5740   if (super_check_offset.is_register()) {
5741     assert_different_registers(sub_klass, super_klass,
5742                                super_check_offset.as_register());
5743   } else if (must_load_sco) {
5744     assert(temp_reg != noreg, "supply either a temp or a register offset");
5745   }
5746 
5747   Label L_fallthrough;
5748   int label_nulls = 0;
5749   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5750   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5751   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5752   assert(label_nulls <= 1, "at most one NULL in the batch");
5753 
5754   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5755   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5756   Address super_check_offset_addr(super_klass, sco_offset);
5757 
5758   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5759   // range of a jccb.  If this routine grows larger, reconsider at
5760   // least some of these.
5761 #define local_jcc(assembler_cond, label)                                \
5762   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5763   else                             jcc( assembler_cond, label) /*omit semi*/
5764 
5765   // Hacked jmp, which may only be used just before L_fallthrough.
5766 #define final_jmp(label)                                                \
5767   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5768   else                            jmp(label)                /*omit semi*/
5769 
5770   // If the pointers are equal, we are done (e.g., String[] elements).
5771   // This self-check enables sharing of secondary supertype arrays among
5772   // non-primary types such as array-of-interface.  Otherwise, each such
5773   // type would need its own customized SSA.
5774   // We move this check to the front of the fast path because many
5775   // type checks are in fact trivially successful in this manner,
5776   // so we get a nicely predicted branch right at the start of the check.
5777   cmpptr(sub_klass, super_klass);
5778   local_jcc(Assembler::equal, *L_success);
5779 
5780   // Check the supertype display:
5781   if (must_load_sco) {
5782     // Positive movl does right thing on LP64.
5783     movl(temp_reg, super_check_offset_addr);
5784     super_check_offset = RegisterOrConstant(temp_reg);
5785   }
5786   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5787   cmpptr(super_klass, super_check_addr); // load displayed supertype
5788 
5789   // This check has worked decisively for primary supers.
5790   // Secondary supers are sought in the super_cache ('super_cache_addr').
5791   // (Secondary supers are interfaces and very deeply nested subtypes.)
5792   // This works in the same check above because of a tricky aliasing
5793   // between the super_cache and the primary super display elements.
5794   // (The 'super_check_addr' can address either, as the case requires.)
5795   // Note that the cache is updated below if it does not help us find
5796   // what we need immediately.
5797   // So if it was a primary super, we can just fail immediately.
5798   // Otherwise, it's the slow path for us (no success at this point).
5799 
5800   if (super_check_offset.is_register()) {
5801     local_jcc(Assembler::equal, *L_success);
5802     cmpl(super_check_offset.as_register(), sc_offset);
5803     if (L_failure == &L_fallthrough) {
5804       local_jcc(Assembler::equal, *L_slow_path);
5805     } else {
5806       local_jcc(Assembler::notEqual, *L_failure);
5807       final_jmp(*L_slow_path);
5808     }
5809   } else if (super_check_offset.as_constant() == sc_offset) {
5810     // Need a slow path; fast failure is impossible.
5811     if (L_slow_path == &L_fallthrough) {
5812       local_jcc(Assembler::equal, *L_success);
5813     } else {
5814       local_jcc(Assembler::notEqual, *L_slow_path);
5815       final_jmp(*L_success);
5816     }
5817   } else {
5818     // No slow path; it's a fast decision.
5819     if (L_failure == &L_fallthrough) {
5820       local_jcc(Assembler::equal, *L_success);
5821     } else {
5822       local_jcc(Assembler::notEqual, *L_failure);
5823       final_jmp(*L_success);
5824     }
5825   }
5826 
5827   bind(L_fallthrough);
5828 
5829 #undef local_jcc
5830 #undef final_jmp
5831 }
5832 
5833 
5834 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5835                                                    Register super_klass,
5836                                                    Register temp_reg,
5837                                                    Register temp2_reg,
5838                                                    Label* L_success,
5839                                                    Label* L_failure,
5840                                                    bool set_cond_codes) {
5841   assert_different_registers(sub_klass, super_klass, temp_reg);
5842   if (temp2_reg != noreg)
5843     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5844 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5845 
5846   Label L_fallthrough;
5847   int label_nulls = 0;
5848   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5849   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5850   assert(label_nulls <= 1, "at most one NULL in the batch");
5851 
5852   // a couple of useful fields in sub_klass:
5853   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5854   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5855   Address secondary_supers_addr(sub_klass, ss_offset);
5856   Address super_cache_addr(     sub_klass, sc_offset);
5857 
5858   // Do a linear scan of the secondary super-klass chain.
5859   // This code is rarely used, so simplicity is a virtue here.
5860   // The repne_scan instruction uses fixed registers, which we must spill.
5861   // Don't worry too much about pre-existing connections with the input regs.
5862 
5863   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5864   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5865 
5866   // Get super_klass value into rax (even if it was in rdi or rcx).
5867   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5868   if (super_klass != rax || UseCompressedOops) {
5869     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5870     mov(rax, super_klass);
5871   }
5872   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5873   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5874 
5875 #ifndef PRODUCT
5876   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5877   ExternalAddress pst_counter_addr((address) pst_counter);
5878   NOT_LP64(  incrementl(pst_counter_addr) );
5879   LP64_ONLY( lea(rcx, pst_counter_addr) );
5880   LP64_ONLY( incrementl(Address(rcx, 0)) );
5881 #endif //PRODUCT
5882 
5883   // We will consult the secondary-super array.
5884   movptr(rdi, secondary_supers_addr);
5885   // Load the array length.  (Positive movl does right thing on LP64.)
5886   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
5887   // Skip to start of data.
5888   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
5889 
5890   // Scan RCX words at [RDI] for an occurrence of RAX.
5891   // Set NZ/Z based on last compare.
5892   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
5893   // not change flags (only scas instruction which is repeated sets flags).
5894   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
5895 
5896     testptr(rax,rax); // Set Z = 0
5897     repne_scan();
5898 
5899   // Unspill the temp. registers:
5900   if (pushed_rdi)  pop(rdi);
5901   if (pushed_rcx)  pop(rcx);
5902   if (pushed_rax)  pop(rax);
5903 
5904   if (set_cond_codes) {
5905     // Special hack for the AD files:  rdi is guaranteed non-zero.
5906     assert(!pushed_rdi, "rdi must be left non-NULL");
5907     // Also, the condition codes are properly set Z/NZ on succeed/failure.
5908   }
5909 
5910   if (L_failure == &L_fallthrough)
5911         jccb(Assembler::notEqual, *L_failure);
5912   else  jcc(Assembler::notEqual, *L_failure);
5913 
5914   // Success.  Cache the super we found and proceed in triumph.
5915   movptr(super_cache_addr, super_klass);
5916 
5917   if (L_success != &L_fallthrough) {
5918     jmp(*L_success);
5919   }
5920 
5921 #undef IS_A_TEMP
5922 
5923   bind(L_fallthrough);
5924 }
5925 
5926 
5927 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
5928   if (VM_Version::supports_cmov()) {
5929     cmovl(cc, dst, src);
5930   } else {
5931     Label L;
5932     jccb(negate_condition(cc), L);
5933     movl(dst, src);
5934     bind(L);
5935   }
5936 }
5937 
5938 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
5939   if (VM_Version::supports_cmov()) {
5940     cmovl(cc, dst, src);
5941   } else {
5942     Label L;
5943     jccb(negate_condition(cc), L);
5944     movl(dst, src);
5945     bind(L);
5946   }
5947 }
5948 
5949 void MacroAssembler::verify_oop(Register reg, const char* s) {
5950   if (!VerifyOops) return;
5951 
5952   // Pass register number to verify_oop_subroutine
5953   const char* b = NULL;
5954   {
5955     ResourceMark rm;
5956     stringStream ss;
5957     ss.print("verify_oop: %s: %s", reg->name(), s);
5958     b = code_string(ss.as_string());
5959   }
5960   BLOCK_COMMENT("verify_oop {");
5961 #ifdef _LP64
5962   push(rscratch1);                    // save r10, trashed by movptr()
5963 #endif
5964   push(rax);                          // save rax,
5965   push(reg);                          // pass register argument
5966   ExternalAddress buffer((address) b);
5967   // avoid using pushptr, as it modifies scratch registers
5968   // and our contract is not to modify anything
5969   movptr(rax, buffer.addr());
5970   push(rax);
5971   // call indirectly to solve generation ordering problem
5972   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5973   call(rax);
5974   // Caller pops the arguments (oop, message) and restores rax, r10
5975   BLOCK_COMMENT("} verify_oop");
5976 }
5977 
5978 
5979 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
5980                                                       Register tmp,
5981                                                       int offset) {
5982   intptr_t value = *delayed_value_addr;
5983   if (value != 0)
5984     return RegisterOrConstant(value + offset);
5985 
5986   // load indirectly to solve generation ordering problem
5987   movptr(tmp, ExternalAddress((address) delayed_value_addr));
5988 
5989 #ifdef ASSERT
5990   { Label L;
5991     testptr(tmp, tmp);
5992     if (WizardMode) {
5993       const char* buf = NULL;
5994       {
5995         ResourceMark rm;
5996         stringStream ss;
5997         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
5998         buf = code_string(ss.as_string());
5999       }
6000       jcc(Assembler::notZero, L);
6001       STOP(buf);
6002     } else {
6003       jccb(Assembler::notZero, L);
6004       hlt();
6005     }
6006     bind(L);
6007   }
6008 #endif
6009 
6010   if (offset != 0)
6011     addptr(tmp, offset);
6012 
6013   return RegisterOrConstant(tmp);
6014 }
6015 
6016 
6017 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6018                                          int extra_slot_offset) {
6019   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6020   int stackElementSize = Interpreter::stackElementSize;
6021   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6022 #ifdef ASSERT
6023   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6024   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6025 #endif
6026   Register             scale_reg    = noreg;
6027   Address::ScaleFactor scale_factor = Address::no_scale;
6028   if (arg_slot.is_constant()) {
6029     offset += arg_slot.as_constant() * stackElementSize;
6030   } else {
6031     scale_reg    = arg_slot.as_register();
6032     scale_factor = Address::times(stackElementSize);
6033   }
6034   offset += wordSize;           // return PC is on stack
6035   return Address(rsp, scale_reg, scale_factor, offset);
6036 }
6037 
6038 
6039 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6040   if (!VerifyOops) return;
6041 
6042   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6043   // Pass register number to verify_oop_subroutine
6044   const char* b = NULL;
6045   {
6046     ResourceMark rm;
6047     stringStream ss;
6048     ss.print("verify_oop_addr: %s", s);
6049     b = code_string(ss.as_string());
6050   }
6051 #ifdef _LP64
6052   push(rscratch1);                    // save r10, trashed by movptr()
6053 #endif
6054   push(rax);                          // save rax,
6055   // addr may contain rsp so we will have to adjust it based on the push
6056   // we just did (and on 64 bit we do two pushes)
6057   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6058   // stores rax into addr which is backwards of what was intended.
6059   if (addr.uses(rsp)) {
6060     lea(rax, addr);
6061     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6062   } else {
6063     pushptr(addr);
6064   }
6065 
6066   ExternalAddress buffer((address) b);
6067   // pass msg argument
6068   // avoid using pushptr, as it modifies scratch registers
6069   // and our contract is not to modify anything
6070   movptr(rax, buffer.addr());
6071   push(rax);
6072 
6073   // call indirectly to solve generation ordering problem
6074   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6075   call(rax);
6076   // Caller pops the arguments (addr, message) and restores rax, r10.
6077 }
6078 
6079 void MacroAssembler::verify_tlab() {
6080 #ifdef ASSERT
6081   if (UseTLAB && VerifyOops) {
6082     Label next, ok;
6083     Register t1 = rsi;
6084     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6085 
6086     push(t1);
6087     NOT_LP64(push(thread_reg));
6088     NOT_LP64(get_thread(thread_reg));
6089 
6090     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6091     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6092     jcc(Assembler::aboveEqual, next);
6093     STOP("assert(top >= start)");
6094     should_not_reach_here();
6095 
6096     bind(next);
6097     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6098     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6099     jcc(Assembler::aboveEqual, ok);
6100     STOP("assert(top <= end)");
6101     should_not_reach_here();
6102 
6103     bind(ok);
6104     NOT_LP64(pop(thread_reg));
6105     pop(t1);
6106   }
6107 #endif
6108 }
6109 
6110 class ControlWord {
6111  public:
6112   int32_t _value;
6113 
6114   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6115   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6116   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6117   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6118   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6119   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6120   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6121   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6122 
6123   void print() const {
6124     // rounding control
6125     const char* rc;
6126     switch (rounding_control()) {
6127       case 0: rc = "round near"; break;
6128       case 1: rc = "round down"; break;
6129       case 2: rc = "round up  "; break;
6130       case 3: rc = "chop      "; break;
6131     };
6132     // precision control
6133     const char* pc;
6134     switch (precision_control()) {
6135       case 0: pc = "24 bits "; break;
6136       case 1: pc = "reserved"; break;
6137       case 2: pc = "53 bits "; break;
6138       case 3: pc = "64 bits "; break;
6139     };
6140     // flags
6141     char f[9];
6142     f[0] = ' ';
6143     f[1] = ' ';
6144     f[2] = (precision   ()) ? 'P' : 'p';
6145     f[3] = (underflow   ()) ? 'U' : 'u';
6146     f[4] = (overflow    ()) ? 'O' : 'o';
6147     f[5] = (zero_divide ()) ? 'Z' : 'z';
6148     f[6] = (denormalized()) ? 'D' : 'd';
6149     f[7] = (invalid     ()) ? 'I' : 'i';
6150     f[8] = '\x0';
6151     // output
6152     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6153   }
6154 
6155 };
6156 
6157 class StatusWord {
6158  public:
6159   int32_t _value;
6160 
6161   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6162   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6163   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6164   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6165   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6166   int  top() const                     { return  (_value >> 11) & 7      ; }
6167   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6168   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6169   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6170   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6171   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6172   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6173   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6174   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6175 
6176   void print() const {
6177     // condition codes
6178     char c[5];
6179     c[0] = (C3()) ? '3' : '-';
6180     c[1] = (C2()) ? '2' : '-';
6181     c[2] = (C1()) ? '1' : '-';
6182     c[3] = (C0()) ? '0' : '-';
6183     c[4] = '\x0';
6184     // flags
6185     char f[9];
6186     f[0] = (error_status()) ? 'E' : '-';
6187     f[1] = (stack_fault ()) ? 'S' : '-';
6188     f[2] = (precision   ()) ? 'P' : '-';
6189     f[3] = (underflow   ()) ? 'U' : '-';
6190     f[4] = (overflow    ()) ? 'O' : '-';
6191     f[5] = (zero_divide ()) ? 'Z' : '-';
6192     f[6] = (denormalized()) ? 'D' : '-';
6193     f[7] = (invalid     ()) ? 'I' : '-';
6194     f[8] = '\x0';
6195     // output
6196     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6197   }
6198 
6199 };
6200 
6201 class TagWord {
6202  public:
6203   int32_t _value;
6204 
6205   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6206 
6207   void print() const {
6208     printf("%04x", _value & 0xFFFF);
6209   }
6210 
6211 };
6212 
6213 class FPU_Register {
6214  public:
6215   int32_t _m0;
6216   int32_t _m1;
6217   int16_t _ex;
6218 
6219   bool is_indefinite() const           {
6220     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6221   }
6222 
6223   void print() const {
6224     char  sign = (_ex < 0) ? '-' : '+';
6225     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6226     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6227   };
6228 
6229 };
6230 
6231 class FPU_State {
6232  public:
6233   enum {
6234     register_size       = 10,
6235     number_of_registers =  8,
6236     register_mask       =  7
6237   };
6238 
6239   ControlWord  _control_word;
6240   StatusWord   _status_word;
6241   TagWord      _tag_word;
6242   int32_t      _error_offset;
6243   int32_t      _error_selector;
6244   int32_t      _data_offset;
6245   int32_t      _data_selector;
6246   int8_t       _register[register_size * number_of_registers];
6247 
6248   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6249   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6250 
6251   const char* tag_as_string(int tag) const {
6252     switch (tag) {
6253       case 0: return "valid";
6254       case 1: return "zero";
6255       case 2: return "special";
6256       case 3: return "empty";
6257     }
6258     ShouldNotReachHere();
6259     return NULL;
6260   }
6261 
6262   void print() const {
6263     // print computation registers
6264     { int t = _status_word.top();
6265       for (int i = 0; i < number_of_registers; i++) {
6266         int j = (i - t) & register_mask;
6267         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6268         st(j)->print();
6269         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6270       }
6271     }
6272     printf("\n");
6273     // print control registers
6274     printf("ctrl = "); _control_word.print(); printf("\n");
6275     printf("stat = "); _status_word .print(); printf("\n");
6276     printf("tags = "); _tag_word    .print(); printf("\n");
6277   }
6278 
6279 };
6280 
6281 class Flag_Register {
6282  public:
6283   int32_t _value;
6284 
6285   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6286   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6287   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6288   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6289   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6290   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6291   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6292 
6293   void print() const {
6294     // flags
6295     char f[8];
6296     f[0] = (overflow       ()) ? 'O' : '-';
6297     f[1] = (direction      ()) ? 'D' : '-';
6298     f[2] = (sign           ()) ? 'S' : '-';
6299     f[3] = (zero           ()) ? 'Z' : '-';
6300     f[4] = (auxiliary_carry()) ? 'A' : '-';
6301     f[5] = (parity         ()) ? 'P' : '-';
6302     f[6] = (carry          ()) ? 'C' : '-';
6303     f[7] = '\x0';
6304     // output
6305     printf("%08x  flags = %s", _value, f);
6306   }
6307 
6308 };
6309 
6310 class IU_Register {
6311  public:
6312   int32_t _value;
6313 
6314   void print() const {
6315     printf("%08x  %11d", _value, _value);
6316   }
6317 
6318 };
6319 
6320 class IU_State {
6321  public:
6322   Flag_Register _eflags;
6323   IU_Register   _rdi;
6324   IU_Register   _rsi;
6325   IU_Register   _rbp;
6326   IU_Register   _rsp;
6327   IU_Register   _rbx;
6328   IU_Register   _rdx;
6329   IU_Register   _rcx;
6330   IU_Register   _rax;
6331 
6332   void print() const {
6333     // computation registers
6334     printf("rax,  = "); _rax.print(); printf("\n");
6335     printf("rbx,  = "); _rbx.print(); printf("\n");
6336     printf("rcx  = "); _rcx.print(); printf("\n");
6337     printf("rdx  = "); _rdx.print(); printf("\n");
6338     printf("rdi  = "); _rdi.print(); printf("\n");
6339     printf("rsi  = "); _rsi.print(); printf("\n");
6340     printf("rbp,  = "); _rbp.print(); printf("\n");
6341     printf("rsp  = "); _rsp.print(); printf("\n");
6342     printf("\n");
6343     // control registers
6344     printf("flgs = "); _eflags.print(); printf("\n");
6345   }
6346 };
6347 
6348 
6349 class CPU_State {
6350  public:
6351   FPU_State _fpu_state;
6352   IU_State  _iu_state;
6353 
6354   void print() const {
6355     printf("--------------------------------------------------\n");
6356     _iu_state .print();
6357     printf("\n");
6358     _fpu_state.print();
6359     printf("--------------------------------------------------\n");
6360   }
6361 
6362 };
6363 
6364 
6365 static void _print_CPU_state(CPU_State* state) {
6366   state->print();
6367 };
6368 
6369 
6370 void MacroAssembler::print_CPU_state() {
6371   push_CPU_state();
6372   push(rsp);                // pass CPU state
6373   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6374   addptr(rsp, wordSize);       // discard argument
6375   pop_CPU_state();
6376 }
6377 
6378 
6379 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6380   static int counter = 0;
6381   FPU_State* fs = &state->_fpu_state;
6382   counter++;
6383   // For leaf calls, only verify that the top few elements remain empty.
6384   // We only need 1 empty at the top for C2 code.
6385   if( stack_depth < 0 ) {
6386     if( fs->tag_for_st(7) != 3 ) {
6387       printf("FPR7 not empty\n");
6388       state->print();
6389       assert(false, "error");
6390       return false;
6391     }
6392     return true;                // All other stack states do not matter
6393   }
6394 
6395   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6396          "bad FPU control word");
6397 
6398   // compute stack depth
6399   int i = 0;
6400   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6401   int d = i;
6402   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6403   // verify findings
6404   if (i != FPU_State::number_of_registers) {
6405     // stack not contiguous
6406     printf("%s: stack not contiguous at ST%d\n", s, i);
6407     state->print();
6408     assert(false, "error");
6409     return false;
6410   }
6411   // check if computed stack depth corresponds to expected stack depth
6412   if (stack_depth < 0) {
6413     // expected stack depth is -stack_depth or less
6414     if (d > -stack_depth) {
6415       // too many elements on the stack
6416       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6417       state->print();
6418       assert(false, "error");
6419       return false;
6420     }
6421   } else {
6422     // expected stack depth is stack_depth
6423     if (d != stack_depth) {
6424       // wrong stack depth
6425       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6426       state->print();
6427       assert(false, "error");
6428       return false;
6429     }
6430   }
6431   // everything is cool
6432   return true;
6433 }
6434 
6435 
6436 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6437   if (!VerifyFPU) return;
6438   push_CPU_state();
6439   push(rsp);                // pass CPU state
6440   ExternalAddress msg((address) s);
6441   // pass message string s
6442   pushptr(msg.addr());
6443   push(stack_depth);        // pass stack depth
6444   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6445   addptr(rsp, 3 * wordSize);   // discard arguments
6446   // check for error
6447   { Label L;
6448     testl(rax, rax);
6449     jcc(Assembler::notZero, L);
6450     int3();                  // break if error condition
6451     bind(L);
6452   }
6453   pop_CPU_state();
6454 }
6455 
6456 void MacroAssembler::restore_cpu_control_state_after_jni() {
6457   // Either restore the MXCSR register after returning from the JNI Call
6458   // or verify that it wasn't changed (with -Xcheck:jni flag).
6459   if (VM_Version::supports_sse()) {
6460     if (RestoreMXCSROnJNICalls) {
6461       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6462     } else if (CheckJNICalls) {
6463       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6464     }
6465   }
6466   if (VM_Version::supports_avx()) {
6467     // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6468     vzeroupper();
6469   }
6470 
6471 #ifndef _LP64
6472   // Either restore the x87 floating pointer control word after returning
6473   // from the JNI call or verify that it wasn't changed.
6474   if (CheckJNICalls) {
6475     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6476   }
6477 #endif // _LP64
6478 }
6479 
6480 void MacroAssembler::load_mirror(Register mirror, Register method) {
6481   // get mirror
6482   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6483   movptr(mirror, Address(method, Method::const_offset()));
6484   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6485   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6486   movptr(mirror, Address(mirror, mirror_offset));
6487 }
6488 
6489 void MacroAssembler::load_klass(Register dst, Register src) {
6490 #ifdef _LP64
6491   if (UseCompressedClassPointers) {
6492     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6493     decode_klass_not_null(dst);
6494   } else
6495 #endif
6496     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6497 }
6498 
6499 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6500   load_klass(dst, src);
6501   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6502 }
6503 
6504 void MacroAssembler::store_klass(Register dst, Register src) {
6505 #ifdef _LP64
6506   if (UseCompressedClassPointers) {
6507     encode_klass_not_null(src);
6508     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6509   } else
6510 #endif
6511     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6512 }
6513 
6514 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6515 #ifdef _LP64
6516   // FIXME: Must change all places where we try to load the klass.
6517   if (UseCompressedOops) {
6518     movl(dst, src);
6519     decode_heap_oop(dst);
6520   } else
6521 #endif
6522     movptr(dst, src);
6523 }
6524 
6525 // Doesn't do verfication, generates fixed size code
6526 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6527 #ifdef _LP64
6528   if (UseCompressedOops) {
6529     movl(dst, src);
6530     decode_heap_oop_not_null(dst);
6531   } else
6532 #endif
6533     movptr(dst, src);
6534 }
6535 
6536 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6537 #ifdef _LP64
6538   if (UseCompressedOops) {
6539     assert(!dst.uses(src), "not enough registers");
6540     encode_heap_oop(src);
6541     movl(dst, src);
6542   } else
6543 #endif
6544     movptr(dst, src);
6545 }
6546 
6547 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6548   assert_different_registers(src1, tmp);
6549 #ifdef _LP64
6550   if (UseCompressedOops) {
6551     bool did_push = false;
6552     if (tmp == noreg) {
6553       tmp = rax;
6554       push(tmp);
6555       did_push = true;
6556       assert(!src2.uses(rsp), "can't push");
6557     }
6558     load_heap_oop(tmp, src2);
6559     cmpptr(src1, tmp);
6560     if (did_push)  pop(tmp);
6561   } else
6562 #endif
6563     cmpptr(src1, src2);
6564 }
6565 
6566 // Used for storing NULLs.
6567 void MacroAssembler::store_heap_oop_null(Address dst) {
6568 #ifdef _LP64
6569   if (UseCompressedOops) {
6570     movl(dst, (int32_t)NULL_WORD);
6571   } else {
6572     movslq(dst, (int32_t)NULL_WORD);
6573   }
6574 #else
6575   movl(dst, (int32_t)NULL_WORD);
6576 #endif
6577 }
6578 
6579 #ifdef _LP64
6580 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6581   if (UseCompressedClassPointers) {
6582     // Store to klass gap in destination
6583     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6584   }
6585 }
6586 
6587 #ifdef ASSERT
6588 void MacroAssembler::verify_heapbase(const char* msg) {
6589   assert (UseCompressedOops, "should be compressed");
6590   assert (Universe::heap() != NULL, "java heap should be initialized");
6591   if (CheckCompressedOops) {
6592     Label ok;
6593     push(rscratch1); // cmpptr trashes rscratch1
6594     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6595     jcc(Assembler::equal, ok);
6596     STOP(msg);
6597     bind(ok);
6598     pop(rscratch1);
6599   }
6600 }
6601 #endif
6602 
6603 // Algorithm must match oop.inline.hpp encode_heap_oop.
6604 void MacroAssembler::encode_heap_oop(Register r) {
6605 #ifdef ASSERT
6606   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6607 #endif
6608   verify_oop(r, "broken oop in encode_heap_oop");
6609   if (Universe::narrow_oop_base() == NULL) {
6610     if (Universe::narrow_oop_shift() != 0) {
6611       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6612       shrq(r, LogMinObjAlignmentInBytes);
6613     }
6614     return;
6615   }
6616   testq(r, r);
6617   cmovq(Assembler::equal, r, r12_heapbase);
6618   subq(r, r12_heapbase);
6619   shrq(r, LogMinObjAlignmentInBytes);
6620 }
6621 
6622 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6623 #ifdef ASSERT
6624   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6625   if (CheckCompressedOops) {
6626     Label ok;
6627     testq(r, r);
6628     jcc(Assembler::notEqual, ok);
6629     STOP("null oop passed to encode_heap_oop_not_null");
6630     bind(ok);
6631   }
6632 #endif
6633   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6634   if (Universe::narrow_oop_base() != NULL) {
6635     subq(r, r12_heapbase);
6636   }
6637   if (Universe::narrow_oop_shift() != 0) {
6638     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6639     shrq(r, LogMinObjAlignmentInBytes);
6640   }
6641 }
6642 
6643 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6644 #ifdef ASSERT
6645   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6646   if (CheckCompressedOops) {
6647     Label ok;
6648     testq(src, src);
6649     jcc(Assembler::notEqual, ok);
6650     STOP("null oop passed to encode_heap_oop_not_null2");
6651     bind(ok);
6652   }
6653 #endif
6654   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6655   if (dst != src) {
6656     movq(dst, src);
6657   }
6658   if (Universe::narrow_oop_base() != NULL) {
6659     subq(dst, r12_heapbase);
6660   }
6661   if (Universe::narrow_oop_shift() != 0) {
6662     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6663     shrq(dst, LogMinObjAlignmentInBytes);
6664   }
6665 }
6666 
6667 void  MacroAssembler::decode_heap_oop(Register r) {
6668 #ifdef ASSERT
6669   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6670 #endif
6671   if (Universe::narrow_oop_base() == NULL) {
6672     if (Universe::narrow_oop_shift() != 0) {
6673       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6674       shlq(r, LogMinObjAlignmentInBytes);
6675     }
6676   } else {
6677     Label done;
6678     shlq(r, LogMinObjAlignmentInBytes);
6679     jccb(Assembler::equal, done);
6680     addq(r, r12_heapbase);
6681     bind(done);
6682   }
6683   verify_oop(r, "broken oop in decode_heap_oop");
6684 }
6685 
6686 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6687   // Note: it will change flags
6688   assert (UseCompressedOops, "should only be used for compressed headers");
6689   assert (Universe::heap() != NULL, "java heap should be initialized");
6690   // Cannot assert, unverified entry point counts instructions (see .ad file)
6691   // vtableStubs also counts instructions in pd_code_size_limit.
6692   // Also do not verify_oop as this is called by verify_oop.
6693   if (Universe::narrow_oop_shift() != 0) {
6694     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6695     shlq(r, LogMinObjAlignmentInBytes);
6696     if (Universe::narrow_oop_base() != NULL) {
6697       addq(r, r12_heapbase);
6698     }
6699   } else {
6700     assert (Universe::narrow_oop_base() == NULL, "sanity");
6701   }
6702 }
6703 
6704 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6705   // Note: it will change flags
6706   assert (UseCompressedOops, "should only be used for compressed headers");
6707   assert (Universe::heap() != NULL, "java heap should be initialized");
6708   // Cannot assert, unverified entry point counts instructions (see .ad file)
6709   // vtableStubs also counts instructions in pd_code_size_limit.
6710   // Also do not verify_oop as this is called by verify_oop.
6711   if (Universe::narrow_oop_shift() != 0) {
6712     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6713     if (LogMinObjAlignmentInBytes == Address::times_8) {
6714       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6715     } else {
6716       if (dst != src) {
6717         movq(dst, src);
6718       }
6719       shlq(dst, LogMinObjAlignmentInBytes);
6720       if (Universe::narrow_oop_base() != NULL) {
6721         addq(dst, r12_heapbase);
6722       }
6723     }
6724   } else {
6725     assert (Universe::narrow_oop_base() == NULL, "sanity");
6726     if (dst != src) {
6727       movq(dst, src);
6728     }
6729   }
6730 }
6731 
6732 void MacroAssembler::encode_klass_not_null(Register r) {
6733   if (Universe::narrow_klass_base() != NULL) {
6734     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6735     assert(r != r12_heapbase, "Encoding a klass in r12");
6736     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6737     subq(r, r12_heapbase);
6738   }
6739   if (Universe::narrow_klass_shift() != 0) {
6740     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6741     shrq(r, LogKlassAlignmentInBytes);
6742   }
6743   if (Universe::narrow_klass_base() != NULL) {
6744     reinit_heapbase();
6745   }
6746 }
6747 
6748 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6749   if (dst == src) {
6750     encode_klass_not_null(src);
6751   } else {
6752     if (Universe::narrow_klass_base() != NULL) {
6753       mov64(dst, (int64_t)Universe::narrow_klass_base());
6754       negq(dst);
6755       addq(dst, src);
6756     } else {
6757       movptr(dst, src);
6758     }
6759     if (Universe::narrow_klass_shift() != 0) {
6760       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6761       shrq(dst, LogKlassAlignmentInBytes);
6762     }
6763   }
6764 }
6765 
6766 // Function instr_size_for_decode_klass_not_null() counts the instructions
6767 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6768 // when (Universe::heap() != NULL).  Hence, if the instructions they
6769 // generate change, then this method needs to be updated.
6770 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6771   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6772   if (Universe::narrow_klass_base() != NULL) {
6773     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6774     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6775   } else {
6776     // longest load decode klass function, mov64, leaq
6777     return 16;
6778   }
6779 }
6780 
6781 // !!! If the instructions that get generated here change then function
6782 // instr_size_for_decode_klass_not_null() needs to get updated.
6783 void  MacroAssembler::decode_klass_not_null(Register r) {
6784   // Note: it will change flags
6785   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6786   assert(r != r12_heapbase, "Decoding a klass in r12");
6787   // Cannot assert, unverified entry point counts instructions (see .ad file)
6788   // vtableStubs also counts instructions in pd_code_size_limit.
6789   // Also do not verify_oop as this is called by verify_oop.
6790   if (Universe::narrow_klass_shift() != 0) {
6791     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6792     shlq(r, LogKlassAlignmentInBytes);
6793   }
6794   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6795   if (Universe::narrow_klass_base() != NULL) {
6796     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6797     addq(r, r12_heapbase);
6798     reinit_heapbase();
6799   }
6800 }
6801 
6802 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6803   // Note: it will change flags
6804   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6805   if (dst == src) {
6806     decode_klass_not_null(dst);
6807   } else {
6808     // Cannot assert, unverified entry point counts instructions (see .ad file)
6809     // vtableStubs also counts instructions in pd_code_size_limit.
6810     // Also do not verify_oop as this is called by verify_oop.
6811     mov64(dst, (int64_t)Universe::narrow_klass_base());
6812     if (Universe::narrow_klass_shift() != 0) {
6813       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6814       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6815       leaq(dst, Address(dst, src, Address::times_8, 0));
6816     } else {
6817       addq(dst, src);
6818     }
6819   }
6820 }
6821 
6822 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6823   assert (UseCompressedOops, "should only be used for compressed headers");
6824   assert (Universe::heap() != NULL, "java heap should be initialized");
6825   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6826   int oop_index = oop_recorder()->find_index(obj);
6827   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6828   mov_narrow_oop(dst, oop_index, rspec);
6829 }
6830 
6831 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6832   assert (UseCompressedOops, "should only be used for compressed headers");
6833   assert (Universe::heap() != NULL, "java heap should be initialized");
6834   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6835   int oop_index = oop_recorder()->find_index(obj);
6836   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6837   mov_narrow_oop(dst, oop_index, rspec);
6838 }
6839 
6840 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6841   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6842   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6843   int klass_index = oop_recorder()->find_index(k);
6844   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6845   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6846 }
6847 
6848 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
6849   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6850   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6851   int klass_index = oop_recorder()->find_index(k);
6852   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6853   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6854 }
6855 
6856 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
6857   assert (UseCompressedOops, "should only be used for compressed headers");
6858   assert (Universe::heap() != NULL, "java heap should be initialized");
6859   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6860   int oop_index = oop_recorder()->find_index(obj);
6861   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6862   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6863 }
6864 
6865 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
6866   assert (UseCompressedOops, "should only be used for compressed headers");
6867   assert (Universe::heap() != NULL, "java heap should be initialized");
6868   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6869   int oop_index = oop_recorder()->find_index(obj);
6870   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6871   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6872 }
6873 
6874 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
6875   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6876   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6877   int klass_index = oop_recorder()->find_index(k);
6878   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6879   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6880 }
6881 
6882 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
6883   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6884   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6885   int klass_index = oop_recorder()->find_index(k);
6886   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6887   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6888 }
6889 
6890 void MacroAssembler::reinit_heapbase() {
6891   if (UseCompressedOops || UseCompressedClassPointers) {
6892     if (Universe::heap() != NULL) {
6893       if (Universe::narrow_oop_base() == NULL) {
6894         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
6895       } else {
6896         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
6897       }
6898     } else {
6899       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6900     }
6901   }
6902 }
6903 
6904 #endif // _LP64
6905 
6906 
6907 // C2 compiled method's prolog code.
6908 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
6909 
6910   // WARNING: Initial instruction MUST be 5 bytes or longer so that
6911   // NativeJump::patch_verified_entry will be able to patch out the entry
6912   // code safely. The push to verify stack depth is ok at 5 bytes,
6913   // the frame allocation can be either 3 or 6 bytes. So if we don't do
6914   // stack bang then we must use the 6 byte frame allocation even if
6915   // we have no frame. :-(
6916   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
6917 
6918   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6919   // Remove word for return addr
6920   framesize -= wordSize;
6921   stack_bang_size -= wordSize;
6922 
6923   // Calls to C2R adapters often do not accept exceptional returns.
6924   // We require that their callers must bang for them.  But be careful, because
6925   // some VM calls (such as call site linkage) can use several kilobytes of
6926   // stack.  But the stack safety zone should account for that.
6927   // See bugs 4446381, 4468289, 4497237.
6928   if (stack_bang_size > 0) {
6929     generate_stack_overflow_check(stack_bang_size);
6930 
6931     // We always push rbp, so that on return to interpreter rbp, will be
6932     // restored correctly and we can correct the stack.
6933     push(rbp);
6934     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6935     if (PreserveFramePointer) {
6936       mov(rbp, rsp);
6937     }
6938     // Remove word for ebp
6939     framesize -= wordSize;
6940 
6941     // Create frame
6942     if (framesize) {
6943       subptr(rsp, framesize);
6944     }
6945   } else {
6946     // Create frame (force generation of a 4 byte immediate value)
6947     subptr_imm32(rsp, framesize);
6948 
6949     // Save RBP register now.
6950     framesize -= wordSize;
6951     movptr(Address(rsp, framesize), rbp);
6952     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6953     if (PreserveFramePointer) {
6954       movptr(rbp, rsp);
6955       if (framesize > 0) {
6956         addptr(rbp, framesize);
6957       }
6958     }
6959   }
6960 
6961   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
6962     framesize -= wordSize;
6963     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
6964   }
6965 
6966 #ifndef _LP64
6967   // If method sets FPU control word do it now
6968   if (fp_mode_24b) {
6969     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
6970   }
6971   if (UseSSE >= 2 && VerifyFPU) {
6972     verify_FPU(0, "FPU stack must be clean on entry");
6973   }
6974 #endif
6975 
6976 #ifdef ASSERT
6977   if (VerifyStackAtCalls) {
6978     Label L;
6979     push(rax);
6980     mov(rax, rsp);
6981     andptr(rax, StackAlignmentInBytes-1);
6982     cmpptr(rax, StackAlignmentInBytes-wordSize);
6983     pop(rax);
6984     jcc(Assembler::equal, L);
6985     STOP("Stack is not properly aligned!");
6986     bind(L);
6987   }
6988 #endif
6989 
6990 }
6991 
6992 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
6993   // cnt - number of qwords (8-byte words).
6994   // base - start address, qword aligned.
6995   // is_large - if optimizers know cnt is larger than InitArrayShortSize
6996   assert(base==rdi, "base register must be edi for rep stos");
6997   assert(tmp==rax,   "tmp register must be eax for rep stos");
6998   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
6999   assert(InitArrayShortSize % BytesPerLong == 0,
7000     "InitArrayShortSize should be the multiple of BytesPerLong");
7001 
7002   Label DONE;
7003 
7004   xorptr(tmp, tmp);
7005 
7006   if (!is_large) {
7007     Label LOOP, LONG;
7008     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7009     jccb(Assembler::greater, LONG);
7010 
7011     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7012 
7013     decrement(cnt);
7014     jccb(Assembler::negative, DONE); // Zero length
7015 
7016     // Use individual pointer-sized stores for small counts:
7017     BIND(LOOP);
7018     movptr(Address(base, cnt, Address::times_ptr), tmp);
7019     decrement(cnt);
7020     jccb(Assembler::greaterEqual, LOOP);
7021     jmpb(DONE);
7022 
7023     BIND(LONG);
7024   }
7025 
7026   // Use longer rep-prefixed ops for non-small counts:
7027   if (UseFastStosb) {
7028     shlptr(cnt, 3); // convert to number of bytes
7029     rep_stosb();
7030   } else {
7031     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7032     rep_stos();
7033   }
7034 
7035   BIND(DONE);
7036 }
7037 
7038 #ifdef COMPILER2
7039 
7040 // IndexOf for constant substrings with size >= 8 chars
7041 // which don't need to be loaded through stack.
7042 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7043                                       Register cnt1, Register cnt2,
7044                                       int int_cnt2,  Register result,
7045                                       XMMRegister vec, Register tmp,
7046                                       int ae) {
7047   ShortBranchVerifier sbv(this);
7048   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7049   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7050   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7051 
7052   // This method uses the pcmpestri instruction with bound registers
7053   //   inputs:
7054   //     xmm - substring
7055   //     rax - substring length (elements count)
7056   //     mem - scanned string
7057   //     rdx - string length (elements count)
7058   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7059   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7060   //   outputs:
7061   //     rcx - matched index in string
7062   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7063   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7064   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7065   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7066   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7067 
7068   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7069         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7070         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7071 
7072   // Note, inline_string_indexOf() generates checks:
7073   // if (substr.count > string.count) return -1;
7074   // if (substr.count == 0) return 0;
7075   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7076 
7077   // Load substring.
7078   if (ae == StrIntrinsicNode::UL) {
7079     pmovzxbw(vec, Address(str2, 0));
7080   } else {
7081     movdqu(vec, Address(str2, 0));
7082   }
7083   movl(cnt2, int_cnt2);
7084   movptr(result, str1); // string addr
7085 
7086   if (int_cnt2 > stride) {
7087     jmpb(SCAN_TO_SUBSTR);
7088 
7089     // Reload substr for rescan, this code
7090     // is executed only for large substrings (> 8 chars)
7091     bind(RELOAD_SUBSTR);
7092     if (ae == StrIntrinsicNode::UL) {
7093       pmovzxbw(vec, Address(str2, 0));
7094     } else {
7095       movdqu(vec, Address(str2, 0));
7096     }
7097     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7098 
7099     bind(RELOAD_STR);
7100     // We came here after the beginning of the substring was
7101     // matched but the rest of it was not so we need to search
7102     // again. Start from the next element after the previous match.
7103 
7104     // cnt2 is number of substring reminding elements and
7105     // cnt1 is number of string reminding elements when cmp failed.
7106     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7107     subl(cnt1, cnt2);
7108     addl(cnt1, int_cnt2);
7109     movl(cnt2, int_cnt2); // Now restore cnt2
7110 
7111     decrementl(cnt1);     // Shift to next element
7112     cmpl(cnt1, cnt2);
7113     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7114 
7115     addptr(result, (1<<scale1));
7116 
7117   } // (int_cnt2 > 8)
7118 
7119   // Scan string for start of substr in 16-byte vectors
7120   bind(SCAN_TO_SUBSTR);
7121   pcmpestri(vec, Address(result, 0), mode);
7122   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7123   subl(cnt1, stride);
7124   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7125   cmpl(cnt1, cnt2);
7126   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7127   addptr(result, 16);
7128   jmpb(SCAN_TO_SUBSTR);
7129 
7130   // Found a potential substr
7131   bind(FOUND_CANDIDATE);
7132   // Matched whole vector if first element matched (tmp(rcx) == 0).
7133   if (int_cnt2 == stride) {
7134     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7135   } else { // int_cnt2 > 8
7136     jccb(Assembler::overflow, FOUND_SUBSTR);
7137   }
7138   // After pcmpestri tmp(rcx) contains matched element index
7139   // Compute start addr of substr
7140   lea(result, Address(result, tmp, scale1));
7141 
7142   // Make sure string is still long enough
7143   subl(cnt1, tmp);
7144   cmpl(cnt1, cnt2);
7145   if (int_cnt2 == stride) {
7146     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7147   } else { // int_cnt2 > 8
7148     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7149   }
7150   // Left less then substring.
7151 
7152   bind(RET_NOT_FOUND);
7153   movl(result, -1);
7154   jmp(EXIT);
7155 
7156   if (int_cnt2 > stride) {
7157     // This code is optimized for the case when whole substring
7158     // is matched if its head is matched.
7159     bind(MATCH_SUBSTR_HEAD);
7160     pcmpestri(vec, Address(result, 0), mode);
7161     // Reload only string if does not match
7162     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7163 
7164     Label CONT_SCAN_SUBSTR;
7165     // Compare the rest of substring (> 8 chars).
7166     bind(FOUND_SUBSTR);
7167     // First 8 chars are already matched.
7168     negptr(cnt2);
7169     addptr(cnt2, stride);
7170 
7171     bind(SCAN_SUBSTR);
7172     subl(cnt1, stride);
7173     cmpl(cnt2, -stride); // Do not read beyond substring
7174     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7175     // Back-up strings to avoid reading beyond substring:
7176     // cnt1 = cnt1 - cnt2 + 8
7177     addl(cnt1, cnt2); // cnt2 is negative
7178     addl(cnt1, stride);
7179     movl(cnt2, stride); negptr(cnt2);
7180     bind(CONT_SCAN_SUBSTR);
7181     if (int_cnt2 < (int)G) {
7182       int tail_off1 = int_cnt2<<scale1;
7183       int tail_off2 = int_cnt2<<scale2;
7184       if (ae == StrIntrinsicNode::UL) {
7185         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7186       } else {
7187         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7188       }
7189       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7190     } else {
7191       // calculate index in register to avoid integer overflow (int_cnt2*2)
7192       movl(tmp, int_cnt2);
7193       addptr(tmp, cnt2);
7194       if (ae == StrIntrinsicNode::UL) {
7195         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7196       } else {
7197         movdqu(vec, Address(str2, tmp, scale2, 0));
7198       }
7199       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7200     }
7201     // Need to reload strings pointers if not matched whole vector
7202     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7203     addptr(cnt2, stride);
7204     jcc(Assembler::negative, SCAN_SUBSTR);
7205     // Fall through if found full substring
7206 
7207   } // (int_cnt2 > 8)
7208 
7209   bind(RET_FOUND);
7210   // Found result if we matched full small substring.
7211   // Compute substr offset
7212   subptr(result, str1);
7213   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7214     shrl(result, 1); // index
7215   }
7216   bind(EXIT);
7217 
7218 } // string_indexofC8
7219 
7220 // Small strings are loaded through stack if they cross page boundary.
7221 void MacroAssembler::string_indexof(Register str1, Register str2,
7222                                     Register cnt1, Register cnt2,
7223                                     int int_cnt2,  Register result,
7224                                     XMMRegister vec, Register tmp,
7225                                     int ae) {
7226   ShortBranchVerifier sbv(this);
7227   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7228   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7229   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7230 
7231   //
7232   // int_cnt2 is length of small (< 8 chars) constant substring
7233   // or (-1) for non constant substring in which case its length
7234   // is in cnt2 register.
7235   //
7236   // Note, inline_string_indexOf() generates checks:
7237   // if (substr.count > string.count) return -1;
7238   // if (substr.count == 0) return 0;
7239   //
7240   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7241   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7242   // This method uses the pcmpestri instruction with bound registers
7243   //   inputs:
7244   //     xmm - substring
7245   //     rax - substring length (elements count)
7246   //     mem - scanned string
7247   //     rdx - string length (elements count)
7248   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7249   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7250   //   outputs:
7251   //     rcx - matched index in string
7252   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7253   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7254   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7255   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7256 
7257   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7258         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7259         FOUND_CANDIDATE;
7260 
7261   { //========================================================
7262     // We don't know where these strings are located
7263     // and we can't read beyond them. Load them through stack.
7264     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7265 
7266     movptr(tmp, rsp); // save old SP
7267 
7268     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7269       if (int_cnt2 == (1>>scale2)) { // One byte
7270         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7271         load_unsigned_byte(result, Address(str2, 0));
7272         movdl(vec, result); // move 32 bits
7273       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7274         // Not enough header space in 32-bit VM: 12+3 = 15.
7275         movl(result, Address(str2, -1));
7276         shrl(result, 8);
7277         movdl(vec, result); // move 32 bits
7278       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7279         load_unsigned_short(result, Address(str2, 0));
7280         movdl(vec, result); // move 32 bits
7281       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7282         movdl(vec, Address(str2, 0)); // move 32 bits
7283       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7284         movq(vec, Address(str2, 0));  // move 64 bits
7285       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7286         // Array header size is 12 bytes in 32-bit VM
7287         // + 6 bytes for 3 chars == 18 bytes,
7288         // enough space to load vec and shift.
7289         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7290         if (ae == StrIntrinsicNode::UL) {
7291           int tail_off = int_cnt2-8;
7292           pmovzxbw(vec, Address(str2, tail_off));
7293           psrldq(vec, -2*tail_off);
7294         }
7295         else {
7296           int tail_off = int_cnt2*(1<<scale2);
7297           movdqu(vec, Address(str2, tail_off-16));
7298           psrldq(vec, 16-tail_off);
7299         }
7300       }
7301     } else { // not constant substring
7302       cmpl(cnt2, stride);
7303       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7304 
7305       // We can read beyond string if srt+16 does not cross page boundary
7306       // since heaps are aligned and mapped by pages.
7307       assert(os::vm_page_size() < (int)G, "default page should be small");
7308       movl(result, str2); // We need only low 32 bits
7309       andl(result, (os::vm_page_size()-1));
7310       cmpl(result, (os::vm_page_size()-16));
7311       jccb(Assembler::belowEqual, CHECK_STR);
7312 
7313       // Move small strings to stack to allow load 16 bytes into vec.
7314       subptr(rsp, 16);
7315       int stk_offset = wordSize-(1<<scale2);
7316       push(cnt2);
7317 
7318       bind(COPY_SUBSTR);
7319       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7320         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7321         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7322       } else if (ae == StrIntrinsicNode::UU) {
7323         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7324         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7325       }
7326       decrement(cnt2);
7327       jccb(Assembler::notZero, COPY_SUBSTR);
7328 
7329       pop(cnt2);
7330       movptr(str2, rsp);  // New substring address
7331     } // non constant
7332 
7333     bind(CHECK_STR);
7334     cmpl(cnt1, stride);
7335     jccb(Assembler::aboveEqual, BIG_STRINGS);
7336 
7337     // Check cross page boundary.
7338     movl(result, str1); // We need only low 32 bits
7339     andl(result, (os::vm_page_size()-1));
7340     cmpl(result, (os::vm_page_size()-16));
7341     jccb(Assembler::belowEqual, BIG_STRINGS);
7342 
7343     subptr(rsp, 16);
7344     int stk_offset = -(1<<scale1);
7345     if (int_cnt2 < 0) { // not constant
7346       push(cnt2);
7347       stk_offset += wordSize;
7348     }
7349     movl(cnt2, cnt1);
7350 
7351     bind(COPY_STR);
7352     if (ae == StrIntrinsicNode::LL) {
7353       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7354       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7355     } else {
7356       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7357       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7358     }
7359     decrement(cnt2);
7360     jccb(Assembler::notZero, COPY_STR);
7361 
7362     if (int_cnt2 < 0) { // not constant
7363       pop(cnt2);
7364     }
7365     movptr(str1, rsp);  // New string address
7366 
7367     bind(BIG_STRINGS);
7368     // Load substring.
7369     if (int_cnt2 < 0) { // -1
7370       if (ae == StrIntrinsicNode::UL) {
7371         pmovzxbw(vec, Address(str2, 0));
7372       } else {
7373         movdqu(vec, Address(str2, 0));
7374       }
7375       push(cnt2);       // substr count
7376       push(str2);       // substr addr
7377       push(str1);       // string addr
7378     } else {
7379       // Small (< 8 chars) constant substrings are loaded already.
7380       movl(cnt2, int_cnt2);
7381     }
7382     push(tmp);  // original SP
7383 
7384   } // Finished loading
7385 
7386   //========================================================
7387   // Start search
7388   //
7389 
7390   movptr(result, str1); // string addr
7391 
7392   if (int_cnt2  < 0) {  // Only for non constant substring
7393     jmpb(SCAN_TO_SUBSTR);
7394 
7395     // SP saved at sp+0
7396     // String saved at sp+1*wordSize
7397     // Substr saved at sp+2*wordSize
7398     // Substr count saved at sp+3*wordSize
7399 
7400     // Reload substr for rescan, this code
7401     // is executed only for large substrings (> 8 chars)
7402     bind(RELOAD_SUBSTR);
7403     movptr(str2, Address(rsp, 2*wordSize));
7404     movl(cnt2, Address(rsp, 3*wordSize));
7405     if (ae == StrIntrinsicNode::UL) {
7406       pmovzxbw(vec, Address(str2, 0));
7407     } else {
7408       movdqu(vec, Address(str2, 0));
7409     }
7410     // We came here after the beginning of the substring was
7411     // matched but the rest of it was not so we need to search
7412     // again. Start from the next element after the previous match.
7413     subptr(str1, result); // Restore counter
7414     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7415       shrl(str1, 1);
7416     }
7417     addl(cnt1, str1);
7418     decrementl(cnt1);   // Shift to next element
7419     cmpl(cnt1, cnt2);
7420     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7421 
7422     addptr(result, (1<<scale1));
7423   } // non constant
7424 
7425   // Scan string for start of substr in 16-byte vectors
7426   bind(SCAN_TO_SUBSTR);
7427   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7428   pcmpestri(vec, Address(result, 0), mode);
7429   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7430   subl(cnt1, stride);
7431   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7432   cmpl(cnt1, cnt2);
7433   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7434   addptr(result, 16);
7435 
7436   bind(ADJUST_STR);
7437   cmpl(cnt1, stride); // Do not read beyond string
7438   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7439   // Back-up string to avoid reading beyond string.
7440   lea(result, Address(result, cnt1, scale1, -16));
7441   movl(cnt1, stride);
7442   jmpb(SCAN_TO_SUBSTR);
7443 
7444   // Found a potential substr
7445   bind(FOUND_CANDIDATE);
7446   // After pcmpestri tmp(rcx) contains matched element index
7447 
7448   // Make sure string is still long enough
7449   subl(cnt1, tmp);
7450   cmpl(cnt1, cnt2);
7451   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7452   // Left less then substring.
7453 
7454   bind(RET_NOT_FOUND);
7455   movl(result, -1);
7456   jmpb(CLEANUP);
7457 
7458   bind(FOUND_SUBSTR);
7459   // Compute start addr of substr
7460   lea(result, Address(result, tmp, scale1));
7461   if (int_cnt2 > 0) { // Constant substring
7462     // Repeat search for small substring (< 8 chars)
7463     // from new point without reloading substring.
7464     // Have to check that we don't read beyond string.
7465     cmpl(tmp, stride-int_cnt2);
7466     jccb(Assembler::greater, ADJUST_STR);
7467     // Fall through if matched whole substring.
7468   } else { // non constant
7469     assert(int_cnt2 == -1, "should be != 0");
7470 
7471     addl(tmp, cnt2);
7472     // Found result if we matched whole substring.
7473     cmpl(tmp, stride);
7474     jccb(Assembler::lessEqual, RET_FOUND);
7475 
7476     // Repeat search for small substring (<= 8 chars)
7477     // from new point 'str1' without reloading substring.
7478     cmpl(cnt2, stride);
7479     // Have to check that we don't read beyond string.
7480     jccb(Assembler::lessEqual, ADJUST_STR);
7481 
7482     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7483     // Compare the rest of substring (> 8 chars).
7484     movptr(str1, result);
7485 
7486     cmpl(tmp, cnt2);
7487     // First 8 chars are already matched.
7488     jccb(Assembler::equal, CHECK_NEXT);
7489 
7490     bind(SCAN_SUBSTR);
7491     pcmpestri(vec, Address(str1, 0), mode);
7492     // Need to reload strings pointers if not matched whole vector
7493     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7494 
7495     bind(CHECK_NEXT);
7496     subl(cnt2, stride);
7497     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7498     addptr(str1, 16);
7499     if (ae == StrIntrinsicNode::UL) {
7500       addptr(str2, 8);
7501     } else {
7502       addptr(str2, 16);
7503     }
7504     subl(cnt1, stride);
7505     cmpl(cnt2, stride); // Do not read beyond substring
7506     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7507     // Back-up strings to avoid reading beyond substring.
7508 
7509     if (ae == StrIntrinsicNode::UL) {
7510       lea(str2, Address(str2, cnt2, scale2, -8));
7511       lea(str1, Address(str1, cnt2, scale1, -16));
7512     } else {
7513       lea(str2, Address(str2, cnt2, scale2, -16));
7514       lea(str1, Address(str1, cnt2, scale1, -16));
7515     }
7516     subl(cnt1, cnt2);
7517     movl(cnt2, stride);
7518     addl(cnt1, stride);
7519     bind(CONT_SCAN_SUBSTR);
7520     if (ae == StrIntrinsicNode::UL) {
7521       pmovzxbw(vec, Address(str2, 0));
7522     } else {
7523       movdqu(vec, Address(str2, 0));
7524     }
7525     jmp(SCAN_SUBSTR);
7526 
7527     bind(RET_FOUND_LONG);
7528     movptr(str1, Address(rsp, wordSize));
7529   } // non constant
7530 
7531   bind(RET_FOUND);
7532   // Compute substr offset
7533   subptr(result, str1);
7534   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7535     shrl(result, 1); // index
7536   }
7537   bind(CLEANUP);
7538   pop(rsp); // restore SP
7539 
7540 } // string_indexof
7541 
7542 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7543                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7544   ShortBranchVerifier sbv(this);
7545   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7546   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7547 
7548   int stride = 8;
7549 
7550   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7551         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7552         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7553         FOUND_SEQ_CHAR, DONE_LABEL;
7554 
7555   movptr(result, str1);
7556   if (UseAVX >= 2) {
7557     cmpl(cnt1, stride);
7558     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7559     cmpl(cnt1, 2*stride);
7560     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7561     movdl(vec1, ch);
7562     vpbroadcastw(vec1, vec1);
7563     vpxor(vec2, vec2);
7564     movl(tmp, cnt1);
7565     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7566     andl(cnt1,0x0000000F);  //tail count (in chars)
7567 
7568     bind(SCAN_TO_16_CHAR_LOOP);
7569     vmovdqu(vec3, Address(result, 0));
7570     vpcmpeqw(vec3, vec3, vec1, 1);
7571     vptest(vec2, vec3);
7572     jcc(Assembler::carryClear, FOUND_CHAR);
7573     addptr(result, 32);
7574     subl(tmp, 2*stride);
7575     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7576     jmp(SCAN_TO_8_CHAR);
7577     bind(SCAN_TO_8_CHAR_INIT);
7578     movdl(vec1, ch);
7579     pshuflw(vec1, vec1, 0x00);
7580     pshufd(vec1, vec1, 0);
7581     pxor(vec2, vec2);
7582   }
7583   bind(SCAN_TO_8_CHAR);
7584   cmpl(cnt1, stride);
7585   if (UseAVX >= 2) {
7586     jcc(Assembler::less, SCAN_TO_CHAR);
7587   } else {
7588     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7589     movdl(vec1, ch);
7590     pshuflw(vec1, vec1, 0x00);
7591     pshufd(vec1, vec1, 0);
7592     pxor(vec2, vec2);
7593   }
7594   movl(tmp, cnt1);
7595   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7596   andl(cnt1,0x00000007);  //tail count (in chars)
7597 
7598   bind(SCAN_TO_8_CHAR_LOOP);
7599   movdqu(vec3, Address(result, 0));
7600   pcmpeqw(vec3, vec1);
7601   ptest(vec2, vec3);
7602   jcc(Assembler::carryClear, FOUND_CHAR);
7603   addptr(result, 16);
7604   subl(tmp, stride);
7605   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7606   bind(SCAN_TO_CHAR);
7607   testl(cnt1, cnt1);
7608   jcc(Assembler::zero, RET_NOT_FOUND);
7609   bind(SCAN_TO_CHAR_LOOP);
7610   load_unsigned_short(tmp, Address(result, 0));
7611   cmpl(ch, tmp);
7612   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7613   addptr(result, 2);
7614   subl(cnt1, 1);
7615   jccb(Assembler::zero, RET_NOT_FOUND);
7616   jmp(SCAN_TO_CHAR_LOOP);
7617 
7618   bind(RET_NOT_FOUND);
7619   movl(result, -1);
7620   jmpb(DONE_LABEL);
7621 
7622   bind(FOUND_CHAR);
7623   if (UseAVX >= 2) {
7624     vpmovmskb(tmp, vec3);
7625   } else {
7626     pmovmskb(tmp, vec3);
7627   }
7628   bsfl(ch, tmp);
7629   addl(result, ch);
7630 
7631   bind(FOUND_SEQ_CHAR);
7632   subptr(result, str1);
7633   shrl(result, 1);
7634 
7635   bind(DONE_LABEL);
7636 } // string_indexof_char
7637 
7638 // helper function for string_compare
7639 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7640                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7641                                         Address::ScaleFactor scale2, Register index, int ae) {
7642   if (ae == StrIntrinsicNode::LL) {
7643     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7644     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7645   } else if (ae == StrIntrinsicNode::UU) {
7646     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7647     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7648   } else {
7649     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7650     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7651   }
7652 }
7653 
7654 // Compare strings, used for char[] and byte[].
7655 void MacroAssembler::string_compare(Register str1, Register str2,
7656                                     Register cnt1, Register cnt2, Register result,
7657                                     XMMRegister vec1, int ae) {
7658   ShortBranchVerifier sbv(this);
7659   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7660   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7661   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7662   int stride2x2 = 0x40;
7663   Address::ScaleFactor scale = Address::no_scale;
7664   Address::ScaleFactor scale1 = Address::no_scale;
7665   Address::ScaleFactor scale2 = Address::no_scale;
7666 
7667   if (ae != StrIntrinsicNode::LL) {
7668     stride2x2 = 0x20;
7669   }
7670 
7671   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7672     shrl(cnt2, 1);
7673   }
7674   // Compute the minimum of the string lengths and the
7675   // difference of the string lengths (stack).
7676   // Do the conditional move stuff
7677   movl(result, cnt1);
7678   subl(cnt1, cnt2);
7679   push(cnt1);
7680   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7681 
7682   // Is the minimum length zero?
7683   testl(cnt2, cnt2);
7684   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7685   if (ae == StrIntrinsicNode::LL) {
7686     // Load first bytes
7687     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7688     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7689   } else if (ae == StrIntrinsicNode::UU) {
7690     // Load first characters
7691     load_unsigned_short(result, Address(str1, 0));
7692     load_unsigned_short(cnt1, Address(str2, 0));
7693   } else {
7694     load_unsigned_byte(result, Address(str1, 0));
7695     load_unsigned_short(cnt1, Address(str2, 0));
7696   }
7697   subl(result, cnt1);
7698   jcc(Assembler::notZero,  POP_LABEL);
7699 
7700   if (ae == StrIntrinsicNode::UU) {
7701     // Divide length by 2 to get number of chars
7702     shrl(cnt2, 1);
7703   }
7704   cmpl(cnt2, 1);
7705   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7706 
7707   // Check if the strings start at the same location and setup scale and stride
7708   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7709     cmpptr(str1, str2);
7710     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7711     if (ae == StrIntrinsicNode::LL) {
7712       scale = Address::times_1;
7713       stride = 16;
7714     } else {
7715       scale = Address::times_2;
7716       stride = 8;
7717     }
7718   } else {
7719     scale1 = Address::times_1;
7720     scale2 = Address::times_2;
7721     // scale not used
7722     stride = 8;
7723   }
7724 
7725   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7726     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7727     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7728     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7729     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7730     Label COMPARE_TAIL_LONG;
7731     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7732 
7733     int pcmpmask = 0x19;
7734     if (ae == StrIntrinsicNode::LL) {
7735       pcmpmask &= ~0x01;
7736     }
7737 
7738     // Setup to compare 16-chars (32-bytes) vectors,
7739     // start from first character again because it has aligned address.
7740     if (ae == StrIntrinsicNode::LL) {
7741       stride2 = 32;
7742     } else {
7743       stride2 = 16;
7744     }
7745     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7746       adr_stride = stride << scale;
7747     } else {
7748       adr_stride1 = 8;  //stride << scale1;
7749       adr_stride2 = 16; //stride << scale2;
7750     }
7751 
7752     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7753     // rax and rdx are used by pcmpestri as elements counters
7754     movl(result, cnt2);
7755     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7756     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7757 
7758     // fast path : compare first 2 8-char vectors.
7759     bind(COMPARE_16_CHARS);
7760     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7761       movdqu(vec1, Address(str1, 0));
7762     } else {
7763       pmovzxbw(vec1, Address(str1, 0));
7764     }
7765     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7766     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7767 
7768     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7769       movdqu(vec1, Address(str1, adr_stride));
7770       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7771     } else {
7772       pmovzxbw(vec1, Address(str1, adr_stride1));
7773       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7774     }
7775     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7776     addl(cnt1, stride);
7777 
7778     // Compare the characters at index in cnt1
7779     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7780     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7781     subl(result, cnt2);
7782     jmp(POP_LABEL);
7783 
7784     // Setup the registers to start vector comparison loop
7785     bind(COMPARE_WIDE_VECTORS);
7786     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7787       lea(str1, Address(str1, result, scale));
7788       lea(str2, Address(str2, result, scale));
7789     } else {
7790       lea(str1, Address(str1, result, scale1));
7791       lea(str2, Address(str2, result, scale2));
7792     }
7793     subl(result, stride2);
7794     subl(cnt2, stride2);
7795     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7796     negptr(result);
7797 
7798     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7799     bind(COMPARE_WIDE_VECTORS_LOOP);
7800 
7801 #ifdef _LP64
7802     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7803       cmpl(cnt2, stride2x2);
7804       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7805       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7806       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7807 
7808       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7809       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7810         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7811         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7812       } else {
7813         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7814         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7815       }
7816       kortestql(k7, k7);
7817       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7818       addptr(result, stride2x2);  // update since we already compared at this addr
7819       subl(cnt2, stride2x2);      // and sub the size too
7820       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7821 
7822       vpxor(vec1, vec1);
7823       jmpb(COMPARE_WIDE_TAIL);
7824     }//if (VM_Version::supports_avx512vlbw())
7825 #endif // _LP64
7826 
7827 
7828     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7829     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7830       vmovdqu(vec1, Address(str1, result, scale));
7831       vpxor(vec1, Address(str2, result, scale));
7832     } else {
7833       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7834       vpxor(vec1, Address(str2, result, scale2));
7835     }
7836     vptest(vec1, vec1);
7837     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7838     addptr(result, stride2);
7839     subl(cnt2, stride2);
7840     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7841     // clean upper bits of YMM registers
7842     vpxor(vec1, vec1);
7843 
7844     // compare wide vectors tail
7845     bind(COMPARE_WIDE_TAIL);
7846     testptr(result, result);
7847     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7848 
7849     movl(result, stride2);
7850     movl(cnt2, result);
7851     negptr(result);
7852     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7853 
7854     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7855     bind(VECTOR_NOT_EQUAL);
7856     // clean upper bits of YMM registers
7857     vpxor(vec1, vec1);
7858     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7859       lea(str1, Address(str1, result, scale));
7860       lea(str2, Address(str2, result, scale));
7861     } else {
7862       lea(str1, Address(str1, result, scale1));
7863       lea(str2, Address(str2, result, scale2));
7864     }
7865     jmp(COMPARE_16_CHARS);
7866 
7867     // Compare tail chars, length between 1 to 15 chars
7868     bind(COMPARE_TAIL_LONG);
7869     movl(cnt2, result);
7870     cmpl(cnt2, stride);
7871     jcc(Assembler::less, COMPARE_SMALL_STR);
7872 
7873     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7874       movdqu(vec1, Address(str1, 0));
7875     } else {
7876       pmovzxbw(vec1, Address(str1, 0));
7877     }
7878     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7879     jcc(Assembler::below, COMPARE_INDEX_CHAR);
7880     subptr(cnt2, stride);
7881     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7882     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7883       lea(str1, Address(str1, result, scale));
7884       lea(str2, Address(str2, result, scale));
7885     } else {
7886       lea(str1, Address(str1, result, scale1));
7887       lea(str2, Address(str2, result, scale2));
7888     }
7889     negptr(cnt2);
7890     jmpb(WHILE_HEAD_LABEL);
7891 
7892     bind(COMPARE_SMALL_STR);
7893   } else if (UseSSE42Intrinsics) {
7894     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7895     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
7896     int pcmpmask = 0x19;
7897     // Setup to compare 8-char (16-byte) vectors,
7898     // start from first character again because it has aligned address.
7899     movl(result, cnt2);
7900     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
7901     if (ae == StrIntrinsicNode::LL) {
7902       pcmpmask &= ~0x01;
7903     }
7904     jcc(Assembler::zero, COMPARE_TAIL);
7905     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7906       lea(str1, Address(str1, result, scale));
7907       lea(str2, Address(str2, result, scale));
7908     } else {
7909       lea(str1, Address(str1, result, scale1));
7910       lea(str2, Address(str2, result, scale2));
7911     }
7912     negptr(result);
7913 
7914     // pcmpestri
7915     //   inputs:
7916     //     vec1- substring
7917     //     rax - negative string length (elements count)
7918     //     mem - scanned string
7919     //     rdx - string length (elements count)
7920     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
7921     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
7922     //   outputs:
7923     //     rcx - first mismatched element index
7924     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7925 
7926     bind(COMPARE_WIDE_VECTORS);
7927     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7928       movdqu(vec1, Address(str1, result, scale));
7929       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7930     } else {
7931       pmovzxbw(vec1, Address(str1, result, scale1));
7932       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7933     }
7934     // After pcmpestri cnt1(rcx) contains mismatched element index
7935 
7936     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
7937     addptr(result, stride);
7938     subptr(cnt2, stride);
7939     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
7940 
7941     // compare wide vectors tail
7942     testptr(result, result);
7943     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7944 
7945     movl(cnt2, stride);
7946     movl(result, stride);
7947     negptr(result);
7948     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7949       movdqu(vec1, Address(str1, result, scale));
7950       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7951     } else {
7952       pmovzxbw(vec1, Address(str1, result, scale1));
7953       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7954     }
7955     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
7956 
7957     // Mismatched characters in the vectors
7958     bind(VECTOR_NOT_EQUAL);
7959     addptr(cnt1, result);
7960     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7961     subl(result, cnt2);
7962     jmpb(POP_LABEL);
7963 
7964     bind(COMPARE_TAIL); // limit is zero
7965     movl(cnt2, result);
7966     // Fallthru to tail compare
7967   }
7968   // Shift str2 and str1 to the end of the arrays, negate min
7969   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7970     lea(str1, Address(str1, cnt2, scale));
7971     lea(str2, Address(str2, cnt2, scale));
7972   } else {
7973     lea(str1, Address(str1, cnt2, scale1));
7974     lea(str2, Address(str2, cnt2, scale2));
7975   }
7976   decrementl(cnt2);  // first character was compared already
7977   negptr(cnt2);
7978 
7979   // Compare the rest of the elements
7980   bind(WHILE_HEAD_LABEL);
7981   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
7982   subl(result, cnt1);
7983   jccb(Assembler::notZero, POP_LABEL);
7984   increment(cnt2);
7985   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
7986 
7987   // Strings are equal up to min length.  Return the length difference.
7988   bind(LENGTH_DIFF_LABEL);
7989   pop(result);
7990   if (ae == StrIntrinsicNode::UU) {
7991     // Divide diff by 2 to get number of chars
7992     sarl(result, 1);
7993   }
7994   jmpb(DONE_LABEL);
7995 
7996 #ifdef _LP64
7997   if (VM_Version::supports_avx512vlbw()) {
7998 
7999     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8000 
8001     kmovql(cnt1, k7);
8002     notq(cnt1);
8003     bsfq(cnt2, cnt1);
8004     if (ae != StrIntrinsicNode::LL) {
8005       // Divide diff by 2 to get number of chars
8006       sarl(cnt2, 1);
8007     }
8008     addq(result, cnt2);
8009     if (ae == StrIntrinsicNode::LL) {
8010       load_unsigned_byte(cnt1, Address(str2, result));
8011       load_unsigned_byte(result, Address(str1, result));
8012     } else if (ae == StrIntrinsicNode::UU) {
8013       load_unsigned_short(cnt1, Address(str2, result, scale));
8014       load_unsigned_short(result, Address(str1, result, scale));
8015     } else {
8016       load_unsigned_short(cnt1, Address(str2, result, scale2));
8017       load_unsigned_byte(result, Address(str1, result, scale1));
8018     }
8019     subl(result, cnt1);
8020     jmpb(POP_LABEL);
8021   }//if (VM_Version::supports_avx512vlbw())
8022 #endif // _LP64
8023 
8024   // Discard the stored length difference
8025   bind(POP_LABEL);
8026   pop(cnt1);
8027 
8028   // That's it
8029   bind(DONE_LABEL);
8030   if(ae == StrIntrinsicNode::UL) {
8031     negl(result);
8032   }
8033 
8034 }
8035 
8036 // Search for Non-ASCII character (Negative byte value) in a byte array,
8037 // return true if it has any and false otherwise.
8038 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
8039 //   @HotSpotIntrinsicCandidate
8040 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
8041 //     for (int i = off; i < off + len; i++) {
8042 //       if (ba[i] < 0) {
8043 //         return true;
8044 //       }
8045 //     }
8046 //     return false;
8047 //   }
8048 void MacroAssembler::has_negatives(Register ary1, Register len,
8049   Register result, Register tmp1,
8050   XMMRegister vec1, XMMRegister vec2) {
8051   // rsi: byte array
8052   // rcx: len
8053   // rax: result
8054   ShortBranchVerifier sbv(this);
8055   assert_different_registers(ary1, len, result, tmp1);
8056   assert_different_registers(vec1, vec2);
8057   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8058 
8059   // len == 0
8060   testl(len, len);
8061   jcc(Assembler::zero, FALSE_LABEL);
8062 
8063   if ((UseAVX > 2) && // AVX512
8064     VM_Version::supports_avx512vlbw() &&
8065     VM_Version::supports_bmi2()) {
8066 
8067     set_vector_masking();  // opening of the stub context for programming mask registers
8068 
8069     Label test_64_loop, test_tail;
8070     Register tmp3_aliased = len;
8071 
8072     movl(tmp1, len);
8073     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
8074 
8075     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
8076     andl(len, ~(64 - 1));    // vector count (in chars)
8077     jccb(Assembler::zero, test_tail);
8078 
8079     lea(ary1, Address(ary1, len, Address::times_1));
8080     negptr(len);
8081 
8082     bind(test_64_loop);
8083     // Check whether our 64 elements of size byte contain negatives
8084     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
8085     kortestql(k2, k2);
8086     jcc(Assembler::notZero, TRUE_LABEL);
8087 
8088     addptr(len, 64);
8089     jccb(Assembler::notZero, test_64_loop);
8090 
8091 
8092     bind(test_tail);
8093     // bail out when there is nothing to be done
8094     testl(tmp1, -1);
8095     jcc(Assembler::zero, FALSE_LABEL);
8096 
8097     // Save k1
8098     kmovql(k3, k1);
8099 
8100     // ~(~0 << len) applied up to two times (for 32-bit scenario)
8101 #ifdef _LP64
8102     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
8103     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
8104     notq(tmp3_aliased);
8105     kmovql(k1, tmp3_aliased);
8106 #else
8107     Label k_init;
8108     jmp(k_init);
8109 
8110     // We could not read 64-bits from a general purpose register thus we move
8111     // data required to compose 64 1's to the instruction stream
8112     // We emit 64 byte wide series of elements from 0..63 which later on would
8113     // be used as a compare targets with tail count contained in tmp1 register.
8114     // Result would be a k1 register having tmp1 consecutive number or 1
8115     // counting from least significant bit.
8116     address tmp = pc();
8117     emit_int64(0x0706050403020100);
8118     emit_int64(0x0F0E0D0C0B0A0908);
8119     emit_int64(0x1716151413121110);
8120     emit_int64(0x1F1E1D1C1B1A1918);
8121     emit_int64(0x2726252423222120);
8122     emit_int64(0x2F2E2D2C2B2A2928);
8123     emit_int64(0x3736353433323130);
8124     emit_int64(0x3F3E3D3C3B3A3938);
8125 
8126     bind(k_init);
8127     lea(len, InternalAddress(tmp));
8128     // create mask to test for negative byte inside a vector
8129     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
8130     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
8131 
8132 #endif
8133     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
8134     ktestq(k2, k1);
8135     // Restore k1
8136     kmovql(k1, k3);
8137     jcc(Assembler::notZero, TRUE_LABEL);
8138 
8139     jmp(FALSE_LABEL);
8140 
8141     clear_vector_masking();   // closing of the stub context for programming mask registers
8142   }
8143   else {
8144     movl(result, len); // copy
8145 
8146     if (UseAVX == 2 && UseSSE >= 2) {
8147       // With AVX2, use 32-byte vector compare
8148       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8149 
8150       // Compare 32-byte vectors
8151       andl(result, 0x0000001f);  //   tail count (in bytes)
8152       andl(len, 0xffffffe0);   // vector count (in bytes)
8153       jccb(Assembler::zero, COMPARE_TAIL);
8154 
8155       lea(ary1, Address(ary1, len, Address::times_1));
8156       negptr(len);
8157 
8158       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8159       movdl(vec2, tmp1);
8160       vpbroadcastd(vec2, vec2);
8161 
8162       bind(COMPARE_WIDE_VECTORS);
8163       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8164       vptest(vec1, vec2);
8165       jccb(Assembler::notZero, TRUE_LABEL);
8166       addptr(len, 32);
8167       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8168 
8169       testl(result, result);
8170       jccb(Assembler::zero, FALSE_LABEL);
8171 
8172       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8173       vptest(vec1, vec2);
8174       jccb(Assembler::notZero, TRUE_LABEL);
8175       jmpb(FALSE_LABEL);
8176 
8177       bind(COMPARE_TAIL); // len is zero
8178       movl(len, result);
8179       // Fallthru to tail compare
8180     }
8181     else if (UseSSE42Intrinsics) {
8182       assert(UseSSE >= 4, "SSE4 must be  for SSE4.2 intrinsics to be available");
8183       // With SSE4.2, use double quad vector compare
8184       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8185 
8186       // Compare 16-byte vectors
8187       andl(result, 0x0000000f);  //   tail count (in bytes)
8188       andl(len, 0xfffffff0);   // vector count (in bytes)
8189       jccb(Assembler::zero, COMPARE_TAIL);
8190 
8191       lea(ary1, Address(ary1, len, Address::times_1));
8192       negptr(len);
8193 
8194       movl(tmp1, 0x80808080);
8195       movdl(vec2, tmp1);
8196       pshufd(vec2, vec2, 0);
8197 
8198       bind(COMPARE_WIDE_VECTORS);
8199       movdqu(vec1, Address(ary1, len, Address::times_1));
8200       ptest(vec1, vec2);
8201       jccb(Assembler::notZero, TRUE_LABEL);
8202       addptr(len, 16);
8203       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8204 
8205       testl(result, result);
8206       jccb(Assembler::zero, FALSE_LABEL);
8207 
8208       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8209       ptest(vec1, vec2);
8210       jccb(Assembler::notZero, TRUE_LABEL);
8211       jmpb(FALSE_LABEL);
8212 
8213       bind(COMPARE_TAIL); // len is zero
8214       movl(len, result);
8215       // Fallthru to tail compare
8216     }
8217   }
8218   // Compare 4-byte vectors
8219   andl(len, 0xfffffffc); // vector count (in bytes)
8220   jccb(Assembler::zero, COMPARE_CHAR);
8221 
8222   lea(ary1, Address(ary1, len, Address::times_1));
8223   negptr(len);
8224 
8225   bind(COMPARE_VECTORS);
8226   movl(tmp1, Address(ary1, len, Address::times_1));
8227   andl(tmp1, 0x80808080);
8228   jccb(Assembler::notZero, TRUE_LABEL);
8229   addptr(len, 4);
8230   jcc(Assembler::notZero, COMPARE_VECTORS);
8231 
8232   // Compare trailing char (final 2 bytes), if any
8233   bind(COMPARE_CHAR);
8234   testl(result, 0x2);   // tail  char
8235   jccb(Assembler::zero, COMPARE_BYTE);
8236   load_unsigned_short(tmp1, Address(ary1, 0));
8237   andl(tmp1, 0x00008080);
8238   jccb(Assembler::notZero, TRUE_LABEL);
8239   subptr(result, 2);
8240   lea(ary1, Address(ary1, 2));
8241 
8242   bind(COMPARE_BYTE);
8243   testl(result, 0x1);   // tail  byte
8244   jccb(Assembler::zero, FALSE_LABEL);
8245   load_unsigned_byte(tmp1, Address(ary1, 0));
8246   andl(tmp1, 0x00000080);
8247   jccb(Assembler::notEqual, TRUE_LABEL);
8248   jmpb(FALSE_LABEL);
8249 
8250   bind(TRUE_LABEL);
8251   movl(result, 1);   // return true
8252   jmpb(DONE);
8253 
8254   bind(FALSE_LABEL);
8255   xorl(result, result); // return false
8256 
8257   // That's it
8258   bind(DONE);
8259   if (UseAVX >= 2 && UseSSE >= 2) {
8260     // clean upper bits of YMM registers
8261     vpxor(vec1, vec1);
8262     vpxor(vec2, vec2);
8263   }
8264 }
8265 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8266 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8267                                    Register limit, Register result, Register chr,
8268                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8269   ShortBranchVerifier sbv(this);
8270   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8271 
8272   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8273   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8274 
8275   if (is_array_equ) {
8276     // Check the input args
8277     cmpptr(ary1, ary2);
8278     jcc(Assembler::equal, TRUE_LABEL);
8279 
8280     // Need additional checks for arrays_equals.
8281     testptr(ary1, ary1);
8282     jcc(Assembler::zero, FALSE_LABEL);
8283     testptr(ary2, ary2);
8284     jcc(Assembler::zero, FALSE_LABEL);
8285 
8286     // Check the lengths
8287     movl(limit, Address(ary1, length_offset));
8288     cmpl(limit, Address(ary2, length_offset));
8289     jcc(Assembler::notEqual, FALSE_LABEL);
8290   }
8291 
8292   // count == 0
8293   testl(limit, limit);
8294   jcc(Assembler::zero, TRUE_LABEL);
8295 
8296   if (is_array_equ) {
8297     // Load array address
8298     lea(ary1, Address(ary1, base_offset));
8299     lea(ary2, Address(ary2, base_offset));
8300   }
8301 
8302   if (is_array_equ && is_char) {
8303     // arrays_equals when used for char[].
8304     shll(limit, 1);      // byte count != 0
8305   }
8306   movl(result, limit); // copy
8307 
8308   if (UseAVX >= 2) {
8309     // With AVX2, use 32-byte vector compare
8310     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8311 
8312     // Compare 32-byte vectors
8313     andl(result, 0x0000001f);  //   tail count (in bytes)
8314     andl(limit, 0xffffffe0);   // vector count (in bytes)
8315     jcc(Assembler::zero, COMPARE_TAIL);
8316 
8317     lea(ary1, Address(ary1, limit, Address::times_1));
8318     lea(ary2, Address(ary2, limit, Address::times_1));
8319     negptr(limit);
8320 
8321     bind(COMPARE_WIDE_VECTORS);
8322 
8323 #ifdef _LP64
8324     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8325       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8326 
8327       cmpl(limit, -64);
8328       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8329 
8330       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8331 
8332       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8333       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8334       kortestql(k7, k7);
8335       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8336       addptr(limit, 64);  // update since we already compared at this addr
8337       cmpl(limit, -64);
8338       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8339 
8340       // At this point we may still need to compare -limit+result bytes.
8341       // We could execute the next two instruction and just continue via non-wide path:
8342       //  cmpl(limit, 0);
8343       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8344       // But since we stopped at the points ary{1,2}+limit which are
8345       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8346       // (|limit| <= 32 and result < 32),
8347       // we may just compare the last 64 bytes.
8348       //
8349       addptr(result, -64);   // it is safe, bc we just came from this area
8350       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8351       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8352       kortestql(k7, k7);
8353       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8354 
8355       jmp(TRUE_LABEL);
8356 
8357       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8358 
8359     }//if (VM_Version::supports_avx512vlbw())
8360 #endif //_LP64
8361 
8362     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8363     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8364     vpxor(vec1, vec2);
8365 
8366     vptest(vec1, vec1);
8367     jcc(Assembler::notZero, FALSE_LABEL);
8368     addptr(limit, 32);
8369     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8370 
8371     testl(result, result);
8372     jcc(Assembler::zero, TRUE_LABEL);
8373 
8374     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8375     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8376     vpxor(vec1, vec2);
8377 
8378     vptest(vec1, vec1);
8379     jccb(Assembler::notZero, FALSE_LABEL);
8380     jmpb(TRUE_LABEL);
8381 
8382     bind(COMPARE_TAIL); // limit is zero
8383     movl(limit, result);
8384     // Fallthru to tail compare
8385   } else if (UseSSE42Intrinsics) {
8386     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8387     // With SSE4.2, use double quad vector compare
8388     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8389 
8390     // Compare 16-byte vectors
8391     andl(result, 0x0000000f);  //   tail count (in bytes)
8392     andl(limit, 0xfffffff0);   // vector count (in bytes)
8393     jcc(Assembler::zero, COMPARE_TAIL);
8394 
8395     lea(ary1, Address(ary1, limit, Address::times_1));
8396     lea(ary2, Address(ary2, limit, Address::times_1));
8397     negptr(limit);
8398 
8399     bind(COMPARE_WIDE_VECTORS);
8400     movdqu(vec1, Address(ary1, limit, Address::times_1));
8401     movdqu(vec2, Address(ary2, limit, Address::times_1));
8402     pxor(vec1, vec2);
8403 
8404     ptest(vec1, vec1);
8405     jcc(Assembler::notZero, FALSE_LABEL);
8406     addptr(limit, 16);
8407     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8408 
8409     testl(result, result);
8410     jcc(Assembler::zero, TRUE_LABEL);
8411 
8412     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8413     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8414     pxor(vec1, vec2);
8415 
8416     ptest(vec1, vec1);
8417     jccb(Assembler::notZero, FALSE_LABEL);
8418     jmpb(TRUE_LABEL);
8419 
8420     bind(COMPARE_TAIL); // limit is zero
8421     movl(limit, result);
8422     // Fallthru to tail compare
8423   }
8424 
8425   // Compare 4-byte vectors
8426   andl(limit, 0xfffffffc); // vector count (in bytes)
8427   jccb(Assembler::zero, COMPARE_CHAR);
8428 
8429   lea(ary1, Address(ary1, limit, Address::times_1));
8430   lea(ary2, Address(ary2, limit, Address::times_1));
8431   negptr(limit);
8432 
8433   bind(COMPARE_VECTORS);
8434   movl(chr, Address(ary1, limit, Address::times_1));
8435   cmpl(chr, Address(ary2, limit, Address::times_1));
8436   jccb(Assembler::notEqual, FALSE_LABEL);
8437   addptr(limit, 4);
8438   jcc(Assembler::notZero, COMPARE_VECTORS);
8439 
8440   // Compare trailing char (final 2 bytes), if any
8441   bind(COMPARE_CHAR);
8442   testl(result, 0x2);   // tail  char
8443   jccb(Assembler::zero, COMPARE_BYTE);
8444   load_unsigned_short(chr, Address(ary1, 0));
8445   load_unsigned_short(limit, Address(ary2, 0));
8446   cmpl(chr, limit);
8447   jccb(Assembler::notEqual, FALSE_LABEL);
8448 
8449   if (is_array_equ && is_char) {
8450     bind(COMPARE_BYTE);
8451   } else {
8452     lea(ary1, Address(ary1, 2));
8453     lea(ary2, Address(ary2, 2));
8454 
8455     bind(COMPARE_BYTE);
8456     testl(result, 0x1);   // tail  byte
8457     jccb(Assembler::zero, TRUE_LABEL);
8458     load_unsigned_byte(chr, Address(ary1, 0));
8459     load_unsigned_byte(limit, Address(ary2, 0));
8460     cmpl(chr, limit);
8461     jccb(Assembler::notEqual, FALSE_LABEL);
8462   }
8463   bind(TRUE_LABEL);
8464   movl(result, 1);   // return true
8465   jmpb(DONE);
8466 
8467   bind(FALSE_LABEL);
8468   xorl(result, result); // return false
8469 
8470   // That's it
8471   bind(DONE);
8472   if (UseAVX >= 2) {
8473     // clean upper bits of YMM registers
8474     vpxor(vec1, vec1);
8475     vpxor(vec2, vec2);
8476   }
8477 }
8478 
8479 #endif
8480 
8481 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8482                                    Register to, Register value, Register count,
8483                                    Register rtmp, XMMRegister xtmp) {
8484   ShortBranchVerifier sbv(this);
8485   assert_different_registers(to, value, count, rtmp);
8486   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8487   Label L_fill_2_bytes, L_fill_4_bytes;
8488 
8489   int shift = -1;
8490   switch (t) {
8491     case T_BYTE:
8492       shift = 2;
8493       break;
8494     case T_SHORT:
8495       shift = 1;
8496       break;
8497     case T_INT:
8498       shift = 0;
8499       break;
8500     default: ShouldNotReachHere();
8501   }
8502 
8503   if (t == T_BYTE) {
8504     andl(value, 0xff);
8505     movl(rtmp, value);
8506     shll(rtmp, 8);
8507     orl(value, rtmp);
8508   }
8509   if (t == T_SHORT) {
8510     andl(value, 0xffff);
8511   }
8512   if (t == T_BYTE || t == T_SHORT) {
8513     movl(rtmp, value);
8514     shll(rtmp, 16);
8515     orl(value, rtmp);
8516   }
8517 
8518   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8519   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8520   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8521     // align source address at 4 bytes address boundary
8522     if (t == T_BYTE) {
8523       // One byte misalignment happens only for byte arrays
8524       testptr(to, 1);
8525       jccb(Assembler::zero, L_skip_align1);
8526       movb(Address(to, 0), value);
8527       increment(to);
8528       decrement(count);
8529       BIND(L_skip_align1);
8530     }
8531     // Two bytes misalignment happens only for byte and short (char) arrays
8532     testptr(to, 2);
8533     jccb(Assembler::zero, L_skip_align2);
8534     movw(Address(to, 0), value);
8535     addptr(to, 2);
8536     subl(count, 1<<(shift-1));
8537     BIND(L_skip_align2);
8538   }
8539   if (UseSSE < 2) {
8540     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8541     // Fill 32-byte chunks
8542     subl(count, 8 << shift);
8543     jcc(Assembler::less, L_check_fill_8_bytes);
8544     align(16);
8545 
8546     BIND(L_fill_32_bytes_loop);
8547 
8548     for (int i = 0; i < 32; i += 4) {
8549       movl(Address(to, i), value);
8550     }
8551 
8552     addptr(to, 32);
8553     subl(count, 8 << shift);
8554     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8555     BIND(L_check_fill_8_bytes);
8556     addl(count, 8 << shift);
8557     jccb(Assembler::zero, L_exit);
8558     jmpb(L_fill_8_bytes);
8559 
8560     //
8561     // length is too short, just fill qwords
8562     //
8563     BIND(L_fill_8_bytes_loop);
8564     movl(Address(to, 0), value);
8565     movl(Address(to, 4), value);
8566     addptr(to, 8);
8567     BIND(L_fill_8_bytes);
8568     subl(count, 1 << (shift + 1));
8569     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8570     // fall through to fill 4 bytes
8571   } else {
8572     Label L_fill_32_bytes;
8573     if (!UseUnalignedLoadStores) {
8574       // align to 8 bytes, we know we are 4 byte aligned to start
8575       testptr(to, 4);
8576       jccb(Assembler::zero, L_fill_32_bytes);
8577       movl(Address(to, 0), value);
8578       addptr(to, 4);
8579       subl(count, 1<<shift);
8580     }
8581     BIND(L_fill_32_bytes);
8582     {
8583       assert( UseSSE >= 2, "supported cpu only" );
8584       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8585       if (UseAVX > 2) {
8586         movl(rtmp, 0xffff);
8587         kmovwl(k1, rtmp);
8588       }
8589       movdl(xtmp, value);
8590       if (UseAVX > 2 && UseUnalignedLoadStores) {
8591         // Fill 64-byte chunks
8592         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8593         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8594 
8595         subl(count, 16 << shift);
8596         jcc(Assembler::less, L_check_fill_32_bytes);
8597         align(16);
8598 
8599         BIND(L_fill_64_bytes_loop);
8600         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8601         addptr(to, 64);
8602         subl(count, 16 << shift);
8603         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8604 
8605         BIND(L_check_fill_32_bytes);
8606         addl(count, 8 << shift);
8607         jccb(Assembler::less, L_check_fill_8_bytes);
8608         vmovdqu(Address(to, 0), xtmp);
8609         addptr(to, 32);
8610         subl(count, 8 << shift);
8611 
8612         BIND(L_check_fill_8_bytes);
8613       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8614         // Fill 64-byte chunks
8615         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8616         vpbroadcastd(xtmp, xtmp);
8617 
8618         subl(count, 16 << shift);
8619         jcc(Assembler::less, L_check_fill_32_bytes);
8620         align(16);
8621 
8622         BIND(L_fill_64_bytes_loop);
8623         vmovdqu(Address(to, 0), xtmp);
8624         vmovdqu(Address(to, 32), xtmp);
8625         addptr(to, 64);
8626         subl(count, 16 << shift);
8627         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8628 
8629         BIND(L_check_fill_32_bytes);
8630         addl(count, 8 << shift);
8631         jccb(Assembler::less, L_check_fill_8_bytes);
8632         vmovdqu(Address(to, 0), xtmp);
8633         addptr(to, 32);
8634         subl(count, 8 << shift);
8635 
8636         BIND(L_check_fill_8_bytes);
8637         // clean upper bits of YMM registers
8638         movdl(xtmp, value);
8639         pshufd(xtmp, xtmp, 0);
8640       } else {
8641         // Fill 32-byte chunks
8642         pshufd(xtmp, xtmp, 0);
8643 
8644         subl(count, 8 << shift);
8645         jcc(Assembler::less, L_check_fill_8_bytes);
8646         align(16);
8647 
8648         BIND(L_fill_32_bytes_loop);
8649 
8650         if (UseUnalignedLoadStores) {
8651           movdqu(Address(to, 0), xtmp);
8652           movdqu(Address(to, 16), xtmp);
8653         } else {
8654           movq(Address(to, 0), xtmp);
8655           movq(Address(to, 8), xtmp);
8656           movq(Address(to, 16), xtmp);
8657           movq(Address(to, 24), xtmp);
8658         }
8659 
8660         addptr(to, 32);
8661         subl(count, 8 << shift);
8662         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8663 
8664         BIND(L_check_fill_8_bytes);
8665       }
8666       addl(count, 8 << shift);
8667       jccb(Assembler::zero, L_exit);
8668       jmpb(L_fill_8_bytes);
8669 
8670       //
8671       // length is too short, just fill qwords
8672       //
8673       BIND(L_fill_8_bytes_loop);
8674       movq(Address(to, 0), xtmp);
8675       addptr(to, 8);
8676       BIND(L_fill_8_bytes);
8677       subl(count, 1 << (shift + 1));
8678       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8679     }
8680   }
8681   // fill trailing 4 bytes
8682   BIND(L_fill_4_bytes);
8683   testl(count, 1<<shift);
8684   jccb(Assembler::zero, L_fill_2_bytes);
8685   movl(Address(to, 0), value);
8686   if (t == T_BYTE || t == T_SHORT) {
8687     addptr(to, 4);
8688     BIND(L_fill_2_bytes);
8689     // fill trailing 2 bytes
8690     testl(count, 1<<(shift-1));
8691     jccb(Assembler::zero, L_fill_byte);
8692     movw(Address(to, 0), value);
8693     if (t == T_BYTE) {
8694       addptr(to, 2);
8695       BIND(L_fill_byte);
8696       // fill trailing byte
8697       testl(count, 1);
8698       jccb(Assembler::zero, L_exit);
8699       movb(Address(to, 0), value);
8700     } else {
8701       BIND(L_fill_byte);
8702     }
8703   } else {
8704     BIND(L_fill_2_bytes);
8705   }
8706   BIND(L_exit);
8707 }
8708 
8709 // encode char[] to byte[] in ISO_8859_1
8710    //@HotSpotIntrinsicCandidate
8711    //private static int implEncodeISOArray(byte[] sa, int sp,
8712    //byte[] da, int dp, int len) {
8713    //  int i = 0;
8714    //  for (; i < len; i++) {
8715    //    char c = StringUTF16.getChar(sa, sp++);
8716    //    if (c > '\u00FF')
8717    //      break;
8718    //    da[dp++] = (byte)c;
8719    //  }
8720    //  return i;
8721    //}
8722 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8723   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8724   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8725   Register tmp5, Register result) {
8726 
8727   // rsi: src
8728   // rdi: dst
8729   // rdx: len
8730   // rcx: tmp5
8731   // rax: result
8732   ShortBranchVerifier sbv(this);
8733   assert_different_registers(src, dst, len, tmp5, result);
8734   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8735 
8736   // set result
8737   xorl(result, result);
8738   // check for zero length
8739   testl(len, len);
8740   jcc(Assembler::zero, L_done);
8741 
8742   movl(result, len);
8743 
8744   // Setup pointers
8745   lea(src, Address(src, len, Address::times_2)); // char[]
8746   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8747   negptr(len);
8748 
8749   if (UseSSE42Intrinsics || UseAVX >= 2) {
8750     assert(UseSSE42Intrinsics ? UseSSE >= 4 : true, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8751     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8752     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8753 
8754     if (UseAVX >= 2) {
8755       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8756       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8757       movdl(tmp1Reg, tmp5);
8758       vpbroadcastd(tmp1Reg, tmp1Reg);
8759       jmp(L_chars_32_check);
8760 
8761       bind(L_copy_32_chars);
8762       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8763       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8764       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8765       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8766       jccb(Assembler::notZero, L_copy_32_chars_exit);
8767       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8768       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8769       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8770 
8771       bind(L_chars_32_check);
8772       addptr(len, 32);
8773       jcc(Assembler::lessEqual, L_copy_32_chars);
8774 
8775       bind(L_copy_32_chars_exit);
8776       subptr(len, 16);
8777       jccb(Assembler::greater, L_copy_16_chars_exit);
8778 
8779     } else if (UseSSE42Intrinsics) {
8780       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8781       movdl(tmp1Reg, tmp5);
8782       pshufd(tmp1Reg, tmp1Reg, 0);
8783       jmpb(L_chars_16_check);
8784     }
8785 
8786     bind(L_copy_16_chars);
8787     if (UseAVX >= 2) {
8788       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8789       vptest(tmp2Reg, tmp1Reg);
8790       jcc(Assembler::notZero, L_copy_16_chars_exit);
8791       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8792       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8793     } else {
8794       if (UseAVX > 0) {
8795         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8796         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8797         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8798       } else {
8799         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8800         por(tmp2Reg, tmp3Reg);
8801         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8802         por(tmp2Reg, tmp4Reg);
8803       }
8804       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8805       jccb(Assembler::notZero, L_copy_16_chars_exit);
8806       packuswb(tmp3Reg, tmp4Reg);
8807     }
8808     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8809 
8810     bind(L_chars_16_check);
8811     addptr(len, 16);
8812     jcc(Assembler::lessEqual, L_copy_16_chars);
8813 
8814     bind(L_copy_16_chars_exit);
8815     if (UseAVX >= 2) {
8816       // clean upper bits of YMM registers
8817       vpxor(tmp2Reg, tmp2Reg);
8818       vpxor(tmp3Reg, tmp3Reg);
8819       vpxor(tmp4Reg, tmp4Reg);
8820       movdl(tmp1Reg, tmp5);
8821       pshufd(tmp1Reg, tmp1Reg, 0);
8822     }
8823     subptr(len, 8);
8824     jccb(Assembler::greater, L_copy_8_chars_exit);
8825 
8826     bind(L_copy_8_chars);
8827     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8828     ptest(tmp3Reg, tmp1Reg);
8829     jccb(Assembler::notZero, L_copy_8_chars_exit);
8830     packuswb(tmp3Reg, tmp1Reg);
8831     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8832     addptr(len, 8);
8833     jccb(Assembler::lessEqual, L_copy_8_chars);
8834 
8835     bind(L_copy_8_chars_exit);
8836     subptr(len, 8);
8837     jccb(Assembler::zero, L_done);
8838   }
8839 
8840   bind(L_copy_1_char);
8841   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8842   testl(tmp5, 0xff00);      // check if Unicode char
8843   jccb(Assembler::notZero, L_copy_1_char_exit);
8844   movb(Address(dst, len, Address::times_1, 0), tmp5);
8845   addptr(len, 1);
8846   jccb(Assembler::less, L_copy_1_char);
8847 
8848   bind(L_copy_1_char_exit);
8849   addptr(result, len); // len is negative count of not processed elements
8850 
8851   bind(L_done);
8852 }
8853 
8854 #ifdef _LP64
8855 /**
8856  * Helper for multiply_to_len().
8857  */
8858 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8859   addq(dest_lo, src1);
8860   adcq(dest_hi, 0);
8861   addq(dest_lo, src2);
8862   adcq(dest_hi, 0);
8863 }
8864 
8865 /**
8866  * Multiply 64 bit by 64 bit first loop.
8867  */
8868 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8869                                            Register y, Register y_idx, Register z,
8870                                            Register carry, Register product,
8871                                            Register idx, Register kdx) {
8872   //
8873   //  jlong carry, x[], y[], z[];
8874   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8875   //    huge_128 product = y[idx] * x[xstart] + carry;
8876   //    z[kdx] = (jlong)product;
8877   //    carry  = (jlong)(product >>> 64);
8878   //  }
8879   //  z[xstart] = carry;
8880   //
8881 
8882   Label L_first_loop, L_first_loop_exit;
8883   Label L_one_x, L_one_y, L_multiply;
8884 
8885   decrementl(xstart);
8886   jcc(Assembler::negative, L_one_x);
8887 
8888   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8889   rorq(x_xstart, 32); // convert big-endian to little-endian
8890 
8891   bind(L_first_loop);
8892   decrementl(idx);
8893   jcc(Assembler::negative, L_first_loop_exit);
8894   decrementl(idx);
8895   jcc(Assembler::negative, L_one_y);
8896   movq(y_idx, Address(y, idx, Address::times_4,  0));
8897   rorq(y_idx, 32); // convert big-endian to little-endian
8898   bind(L_multiply);
8899   movq(product, x_xstart);
8900   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8901   addq(product, carry);
8902   adcq(rdx, 0);
8903   subl(kdx, 2);
8904   movl(Address(z, kdx, Address::times_4,  4), product);
8905   shrq(product, 32);
8906   movl(Address(z, kdx, Address::times_4,  0), product);
8907   movq(carry, rdx);
8908   jmp(L_first_loop);
8909 
8910   bind(L_one_y);
8911   movl(y_idx, Address(y,  0));
8912   jmp(L_multiply);
8913 
8914   bind(L_one_x);
8915   movl(x_xstart, Address(x,  0));
8916   jmp(L_first_loop);
8917 
8918   bind(L_first_loop_exit);
8919 }
8920 
8921 /**
8922  * Multiply 64 bit by 64 bit and add 128 bit.
8923  */
8924 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8925                                             Register yz_idx, Register idx,
8926                                             Register carry, Register product, int offset) {
8927   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8928   //     z[kdx] = (jlong)product;
8929 
8930   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8931   rorq(yz_idx, 32); // convert big-endian to little-endian
8932   movq(product, x_xstart);
8933   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8934   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8935   rorq(yz_idx, 32); // convert big-endian to little-endian
8936 
8937   add2_with_carry(rdx, product, carry, yz_idx);
8938 
8939   movl(Address(z, idx, Address::times_4,  offset+4), product);
8940   shrq(product, 32);
8941   movl(Address(z, idx, Address::times_4,  offset), product);
8942 
8943 }
8944 
8945 /**
8946  * Multiply 128 bit by 128 bit. Unrolled inner loop.
8947  */
8948 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
8949                                              Register yz_idx, Register idx, Register jdx,
8950                                              Register carry, Register product,
8951                                              Register carry2) {
8952   //   jlong carry, x[], y[], z[];
8953   //   int kdx = ystart+1;
8954   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8955   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
8956   //     z[kdx+idx+1] = (jlong)product;
8957   //     jlong carry2  = (jlong)(product >>> 64);
8958   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
8959   //     z[kdx+idx] = (jlong)product;
8960   //     carry  = (jlong)(product >>> 64);
8961   //   }
8962   //   idx += 2;
8963   //   if (idx > 0) {
8964   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
8965   //     z[kdx+idx] = (jlong)product;
8966   //     carry  = (jlong)(product >>> 64);
8967   //   }
8968   //
8969 
8970   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8971 
8972   movl(jdx, idx);
8973   andl(jdx, 0xFFFFFFFC);
8974   shrl(jdx, 2);
8975 
8976   bind(L_third_loop);
8977   subl(jdx, 1);
8978   jcc(Assembler::negative, L_third_loop_exit);
8979   subl(idx, 4);
8980 
8981   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
8982   movq(carry2, rdx);
8983 
8984   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
8985   movq(carry, rdx);
8986   jmp(L_third_loop);
8987 
8988   bind (L_third_loop_exit);
8989 
8990   andl (idx, 0x3);
8991   jcc(Assembler::zero, L_post_third_loop_done);
8992 
8993   Label L_check_1;
8994   subl(idx, 2);
8995   jcc(Assembler::negative, L_check_1);
8996 
8997   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
8998   movq(carry, rdx);
8999 
9000   bind (L_check_1);
9001   addl (idx, 0x2);
9002   andl (idx, 0x1);
9003   subl(idx, 1);
9004   jcc(Assembler::negative, L_post_third_loop_done);
9005 
9006   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9007   movq(product, x_xstart);
9008   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9009   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9010 
9011   add2_with_carry(rdx, product, yz_idx, carry);
9012 
9013   movl(Address(z, idx, Address::times_4,  0), product);
9014   shrq(product, 32);
9015 
9016   shlq(rdx, 32);
9017   orq(product, rdx);
9018   movq(carry, product);
9019 
9020   bind(L_post_third_loop_done);
9021 }
9022 
9023 /**
9024  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9025  *
9026  */
9027 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9028                                                   Register carry, Register carry2,
9029                                                   Register idx, Register jdx,
9030                                                   Register yz_idx1, Register yz_idx2,
9031                                                   Register tmp, Register tmp3, Register tmp4) {
9032   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9033 
9034   //   jlong carry, x[], y[], z[];
9035   //   int kdx = ystart+1;
9036   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9037   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9038   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9039   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9040   //     carry  = (jlong)(tmp4 >>> 64);
9041   //     z[kdx+idx+1] = (jlong)tmp3;
9042   //     z[kdx+idx] = (jlong)tmp4;
9043   //   }
9044   //   idx += 2;
9045   //   if (idx > 0) {
9046   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9047   //     z[kdx+idx] = (jlong)yz_idx1;
9048   //     carry  = (jlong)(yz_idx1 >>> 64);
9049   //   }
9050   //
9051 
9052   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9053 
9054   movl(jdx, idx);
9055   andl(jdx, 0xFFFFFFFC);
9056   shrl(jdx, 2);
9057 
9058   bind(L_third_loop);
9059   subl(jdx, 1);
9060   jcc(Assembler::negative, L_third_loop_exit);
9061   subl(idx, 4);
9062 
9063   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9064   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9065   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9066   rorxq(yz_idx2, yz_idx2, 32);
9067 
9068   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9069   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9070 
9071   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9072   rorxq(yz_idx1, yz_idx1, 32);
9073   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9074   rorxq(yz_idx2, yz_idx2, 32);
9075 
9076   if (VM_Version::supports_adx()) {
9077     adcxq(tmp3, carry);
9078     adoxq(tmp3, yz_idx1);
9079 
9080     adcxq(tmp4, tmp);
9081     adoxq(tmp4, yz_idx2);
9082 
9083     movl(carry, 0); // does not affect flags
9084     adcxq(carry2, carry);
9085     adoxq(carry2, carry);
9086   } else {
9087     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9088     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9089   }
9090   movq(carry, carry2);
9091 
9092   movl(Address(z, idx, Address::times_4, 12), tmp3);
9093   shrq(tmp3, 32);
9094   movl(Address(z, idx, Address::times_4,  8), tmp3);
9095 
9096   movl(Address(z, idx, Address::times_4,  4), tmp4);
9097   shrq(tmp4, 32);
9098   movl(Address(z, idx, Address::times_4,  0), tmp4);
9099 
9100   jmp(L_third_loop);
9101 
9102   bind (L_third_loop_exit);
9103 
9104   andl (idx, 0x3);
9105   jcc(Assembler::zero, L_post_third_loop_done);
9106 
9107   Label L_check_1;
9108   subl(idx, 2);
9109   jcc(Assembler::negative, L_check_1);
9110 
9111   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9112   rorxq(yz_idx1, yz_idx1, 32);
9113   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9114   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9115   rorxq(yz_idx2, yz_idx2, 32);
9116 
9117   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9118 
9119   movl(Address(z, idx, Address::times_4,  4), tmp3);
9120   shrq(tmp3, 32);
9121   movl(Address(z, idx, Address::times_4,  0), tmp3);
9122   movq(carry, tmp4);
9123 
9124   bind (L_check_1);
9125   addl (idx, 0x2);
9126   andl (idx, 0x1);
9127   subl(idx, 1);
9128   jcc(Assembler::negative, L_post_third_loop_done);
9129   movl(tmp4, Address(y, idx, Address::times_4,  0));
9130   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9131   movl(tmp4, Address(z, idx, Address::times_4,  0));
9132 
9133   add2_with_carry(carry2, tmp3, tmp4, carry);
9134 
9135   movl(Address(z, idx, Address::times_4,  0), tmp3);
9136   shrq(tmp3, 32);
9137 
9138   shlq(carry2, 32);
9139   orq(tmp3, carry2);
9140   movq(carry, tmp3);
9141 
9142   bind(L_post_third_loop_done);
9143 }
9144 
9145 /**
9146  * Code for BigInteger::multiplyToLen() instrinsic.
9147  *
9148  * rdi: x
9149  * rax: xlen
9150  * rsi: y
9151  * rcx: ylen
9152  * r8:  z
9153  * r11: zlen
9154  * r12: tmp1
9155  * r13: tmp2
9156  * r14: tmp3
9157  * r15: tmp4
9158  * rbx: tmp5
9159  *
9160  */
9161 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9162                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9163   ShortBranchVerifier sbv(this);
9164   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9165 
9166   push(tmp1);
9167   push(tmp2);
9168   push(tmp3);
9169   push(tmp4);
9170   push(tmp5);
9171 
9172   push(xlen);
9173   push(zlen);
9174 
9175   const Register idx = tmp1;
9176   const Register kdx = tmp2;
9177   const Register xstart = tmp3;
9178 
9179   const Register y_idx = tmp4;
9180   const Register carry = tmp5;
9181   const Register product  = xlen;
9182   const Register x_xstart = zlen;  // reuse register
9183 
9184   // First Loop.
9185   //
9186   //  final static long LONG_MASK = 0xffffffffL;
9187   //  int xstart = xlen - 1;
9188   //  int ystart = ylen - 1;
9189   //  long carry = 0;
9190   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9191   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9192   //    z[kdx] = (int)product;
9193   //    carry = product >>> 32;
9194   //  }
9195   //  z[xstart] = (int)carry;
9196   //
9197 
9198   movl(idx, ylen);      // idx = ylen;
9199   movl(kdx, zlen);      // kdx = xlen+ylen;
9200   xorq(carry, carry);   // carry = 0;
9201 
9202   Label L_done;
9203 
9204   movl(xstart, xlen);
9205   decrementl(xstart);
9206   jcc(Assembler::negative, L_done);
9207 
9208   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9209 
9210   Label L_second_loop;
9211   testl(kdx, kdx);
9212   jcc(Assembler::zero, L_second_loop);
9213 
9214   Label L_carry;
9215   subl(kdx, 1);
9216   jcc(Assembler::zero, L_carry);
9217 
9218   movl(Address(z, kdx, Address::times_4,  0), carry);
9219   shrq(carry, 32);
9220   subl(kdx, 1);
9221 
9222   bind(L_carry);
9223   movl(Address(z, kdx, Address::times_4,  0), carry);
9224 
9225   // Second and third (nested) loops.
9226   //
9227   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9228   //   carry = 0;
9229   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9230   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9231   //                    (z[k] & LONG_MASK) + carry;
9232   //     z[k] = (int)product;
9233   //     carry = product >>> 32;
9234   //   }
9235   //   z[i] = (int)carry;
9236   // }
9237   //
9238   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9239 
9240   const Register jdx = tmp1;
9241 
9242   bind(L_second_loop);
9243   xorl(carry, carry);    // carry = 0;
9244   movl(jdx, ylen);       // j = ystart+1
9245 
9246   subl(xstart, 1);       // i = xstart-1;
9247   jcc(Assembler::negative, L_done);
9248 
9249   push (z);
9250 
9251   Label L_last_x;
9252   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9253   subl(xstart, 1);       // i = xstart-1;
9254   jcc(Assembler::negative, L_last_x);
9255 
9256   if (UseBMI2Instructions) {
9257     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9258     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9259   } else {
9260     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9261     rorq(x_xstart, 32);  // convert big-endian to little-endian
9262   }
9263 
9264   Label L_third_loop_prologue;
9265   bind(L_third_loop_prologue);
9266 
9267   push (x);
9268   push (xstart);
9269   push (ylen);
9270 
9271 
9272   if (UseBMI2Instructions) {
9273     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9274   } else { // !UseBMI2Instructions
9275     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9276   }
9277 
9278   pop(ylen);
9279   pop(xlen);
9280   pop(x);
9281   pop(z);
9282 
9283   movl(tmp3, xlen);
9284   addl(tmp3, 1);
9285   movl(Address(z, tmp3, Address::times_4,  0), carry);
9286   subl(tmp3, 1);
9287   jccb(Assembler::negative, L_done);
9288 
9289   shrq(carry, 32);
9290   movl(Address(z, tmp3, Address::times_4,  0), carry);
9291   jmp(L_second_loop);
9292 
9293   // Next infrequent code is moved outside loops.
9294   bind(L_last_x);
9295   if (UseBMI2Instructions) {
9296     movl(rdx, Address(x,  0));
9297   } else {
9298     movl(x_xstart, Address(x,  0));
9299   }
9300   jmp(L_third_loop_prologue);
9301 
9302   bind(L_done);
9303 
9304   pop(zlen);
9305   pop(xlen);
9306 
9307   pop(tmp5);
9308   pop(tmp4);
9309   pop(tmp3);
9310   pop(tmp2);
9311   pop(tmp1);
9312 }
9313 
9314 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9315   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9316   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9317   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9318   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9319   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9320   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9321   Label SAME_TILL_END, DONE;
9322   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9323 
9324   //scale is in rcx in both Win64 and Unix
9325   ShortBranchVerifier sbv(this);
9326 
9327   shlq(length);
9328   xorq(result, result);
9329 
9330   if ((UseAVX > 2) &&
9331       VM_Version::supports_avx512vlbw()) {
9332     set_vector_masking();  // opening of the stub context for programming mask registers
9333     cmpq(length, 64);
9334     jcc(Assembler::less, VECTOR32_TAIL);
9335     movq(tmp1, length);
9336     andq(tmp1, 0x3F);      // tail count
9337     andq(length, ~(0x3F)); //vector count
9338 
9339     bind(VECTOR64_LOOP);
9340     // AVX512 code to compare 64 byte vectors.
9341     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9342     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9343     kortestql(k7, k7);
9344     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9345     addq(result, 64);
9346     subq(length, 64);
9347     jccb(Assembler::notZero, VECTOR64_LOOP);
9348 
9349     //bind(VECTOR64_TAIL);
9350     testq(tmp1, tmp1);
9351     jcc(Assembler::zero, SAME_TILL_END);
9352 
9353     bind(VECTOR64_TAIL);
9354     // AVX512 code to compare upto 63 byte vectors.
9355     // Save k1
9356     kmovql(k3, k1);
9357     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9358     shlxq(tmp2, tmp2, tmp1);
9359     notq(tmp2);
9360     kmovql(k1, tmp2);
9361 
9362     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9363     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9364 
9365     ktestql(k7, k1);
9366     // Restore k1
9367     kmovql(k1, k3);
9368     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9369 
9370     bind(VECTOR64_NOT_EQUAL);
9371     kmovql(tmp1, k7);
9372     notq(tmp1);
9373     tzcntq(tmp1, tmp1);
9374     addq(result, tmp1);
9375     shrq(result);
9376     jmp(DONE);
9377     bind(VECTOR32_TAIL);
9378     clear_vector_masking();   // closing of the stub context for programming mask registers
9379   }
9380 
9381   cmpq(length, 8);
9382   jcc(Assembler::equal, VECTOR8_LOOP);
9383   jcc(Assembler::less, VECTOR4_TAIL);
9384 
9385   if (UseAVX >= 2) {
9386 
9387     cmpq(length, 16);
9388     jcc(Assembler::equal, VECTOR16_LOOP);
9389     jcc(Assembler::less, VECTOR8_LOOP);
9390 
9391     cmpq(length, 32);
9392     jccb(Assembler::less, VECTOR16_TAIL);
9393 
9394     subq(length, 32);
9395     bind(VECTOR32_LOOP);
9396     vmovdqu(rymm0, Address(obja, result));
9397     vmovdqu(rymm1, Address(objb, result));
9398     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9399     vptest(rymm2, rymm2);
9400     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9401     addq(result, 32);
9402     subq(length, 32);
9403     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9404     addq(length, 32);
9405     jcc(Assembler::equal, SAME_TILL_END);
9406     //falling through if less than 32 bytes left //close the branch here.
9407 
9408     bind(VECTOR16_TAIL);
9409     cmpq(length, 16);
9410     jccb(Assembler::less, VECTOR8_TAIL);
9411     bind(VECTOR16_LOOP);
9412     movdqu(rymm0, Address(obja, result));
9413     movdqu(rymm1, Address(objb, result));
9414     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9415     ptest(rymm2, rymm2);
9416     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9417     addq(result, 16);
9418     subq(length, 16);
9419     jcc(Assembler::equal, SAME_TILL_END);
9420     //falling through if less than 16 bytes left
9421   } else {//regular intrinsics
9422 
9423     cmpq(length, 16);
9424     jccb(Assembler::less, VECTOR8_TAIL);
9425 
9426     subq(length, 16);
9427     bind(VECTOR16_LOOP);
9428     movdqu(rymm0, Address(obja, result));
9429     movdqu(rymm1, Address(objb, result));
9430     pxor(rymm0, rymm1);
9431     ptest(rymm0, rymm0);
9432     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9433     addq(result, 16);
9434     subq(length, 16);
9435     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9436     addq(length, 16);
9437     jcc(Assembler::equal, SAME_TILL_END);
9438     //falling through if less than 16 bytes left
9439   }
9440 
9441   bind(VECTOR8_TAIL);
9442   cmpq(length, 8);
9443   jccb(Assembler::less, VECTOR4_TAIL);
9444   bind(VECTOR8_LOOP);
9445   movq(tmp1, Address(obja, result));
9446   movq(tmp2, Address(objb, result));
9447   xorq(tmp1, tmp2);
9448   testq(tmp1, tmp1);
9449   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9450   addq(result, 8);
9451   subq(length, 8);
9452   jcc(Assembler::equal, SAME_TILL_END);
9453   //falling through if less than 8 bytes left
9454 
9455   bind(VECTOR4_TAIL);
9456   cmpq(length, 4);
9457   jccb(Assembler::less, BYTES_TAIL);
9458   bind(VECTOR4_LOOP);
9459   movl(tmp1, Address(obja, result));
9460   xorl(tmp1, Address(objb, result));
9461   testl(tmp1, tmp1);
9462   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9463   addq(result, 4);
9464   subq(length, 4);
9465   jcc(Assembler::equal, SAME_TILL_END);
9466   //falling through if less than 4 bytes left
9467 
9468   bind(BYTES_TAIL);
9469   bind(BYTES_LOOP);
9470   load_unsigned_byte(tmp1, Address(obja, result));
9471   load_unsigned_byte(tmp2, Address(objb, result));
9472   xorl(tmp1, tmp2);
9473   testl(tmp1, tmp1);
9474   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9475   decq(length);
9476   jccb(Assembler::zero, SAME_TILL_END);
9477   incq(result);
9478   load_unsigned_byte(tmp1, Address(obja, result));
9479   load_unsigned_byte(tmp2, Address(objb, result));
9480   xorl(tmp1, tmp2);
9481   testl(tmp1, tmp1);
9482   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9483   decq(length);
9484   jccb(Assembler::zero, SAME_TILL_END);
9485   incq(result);
9486   load_unsigned_byte(tmp1, Address(obja, result));
9487   load_unsigned_byte(tmp2, Address(objb, result));
9488   xorl(tmp1, tmp2);
9489   testl(tmp1, tmp1);
9490   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9491   jmpb(SAME_TILL_END);
9492 
9493   if (UseAVX >= 2) {
9494     bind(VECTOR32_NOT_EQUAL);
9495     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9496     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9497     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9498     vpmovmskb(tmp1, rymm0);
9499     bsfq(tmp1, tmp1);
9500     addq(result, tmp1);
9501     shrq(result);
9502     jmpb(DONE);
9503   }
9504 
9505   bind(VECTOR16_NOT_EQUAL);
9506   if (UseAVX >= 2) {
9507     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9508     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9509     pxor(rymm0, rymm2);
9510   } else {
9511     pcmpeqb(rymm2, rymm2);
9512     pxor(rymm0, rymm1);
9513     pcmpeqb(rymm0, rymm1);
9514     pxor(rymm0, rymm2);
9515   }
9516   pmovmskb(tmp1, rymm0);
9517   bsfq(tmp1, tmp1);
9518   addq(result, tmp1);
9519   shrq(result);
9520   jmpb(DONE);
9521 
9522   bind(VECTOR8_NOT_EQUAL);
9523   bind(VECTOR4_NOT_EQUAL);
9524   bsfq(tmp1, tmp1);
9525   shrq(tmp1, 3);
9526   addq(result, tmp1);
9527   bind(BYTES_NOT_EQUAL);
9528   shrq(result);
9529   jmpb(DONE);
9530 
9531   bind(SAME_TILL_END);
9532   mov64(result, -1);
9533 
9534   bind(DONE);
9535 }
9536 
9537 //Helper functions for square_to_len()
9538 
9539 /**
9540  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9541  * Preserves x and z and modifies rest of the registers.
9542  */
9543 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9544   // Perform square and right shift by 1
9545   // Handle odd xlen case first, then for even xlen do the following
9546   // jlong carry = 0;
9547   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9548   //     huge_128 product = x[j:j+1] * x[j:j+1];
9549   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9550   //     z[i+2:i+3] = (jlong)(product >>> 1);
9551   //     carry = (jlong)product;
9552   // }
9553 
9554   xorq(tmp5, tmp5);     // carry
9555   xorq(rdxReg, rdxReg);
9556   xorl(tmp1, tmp1);     // index for x
9557   xorl(tmp4, tmp4);     // index for z
9558 
9559   Label L_first_loop, L_first_loop_exit;
9560 
9561   testl(xlen, 1);
9562   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9563 
9564   // Square and right shift by 1 the odd element using 32 bit multiply
9565   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9566   imulq(raxReg, raxReg);
9567   shrq(raxReg, 1);
9568   adcq(tmp5, 0);
9569   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9570   incrementl(tmp1);
9571   addl(tmp4, 2);
9572 
9573   // Square and  right shift by 1 the rest using 64 bit multiply
9574   bind(L_first_loop);
9575   cmpptr(tmp1, xlen);
9576   jccb(Assembler::equal, L_first_loop_exit);
9577 
9578   // Square
9579   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9580   rorq(raxReg, 32);    // convert big-endian to little-endian
9581   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9582 
9583   // Right shift by 1 and save carry
9584   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9585   rcrq(rdxReg, 1);
9586   rcrq(raxReg, 1);
9587   adcq(tmp5, 0);
9588 
9589   // Store result in z
9590   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9591   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9592 
9593   // Update indices for x and z
9594   addl(tmp1, 2);
9595   addl(tmp4, 4);
9596   jmp(L_first_loop);
9597 
9598   bind(L_first_loop_exit);
9599 }
9600 
9601 
9602 /**
9603  * Perform the following multiply add operation using BMI2 instructions
9604  * carry:sum = sum + op1*op2 + carry
9605  * op2 should be in rdx
9606  * op2 is preserved, all other registers are modified
9607  */
9608 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9609   // assert op2 is rdx
9610   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9611   addq(sum, carry);
9612   adcq(tmp2, 0);
9613   addq(sum, op1);
9614   adcq(tmp2, 0);
9615   movq(carry, tmp2);
9616 }
9617 
9618 /**
9619  * Perform the following multiply add operation:
9620  * carry:sum = sum + op1*op2 + carry
9621  * Preserves op1, op2 and modifies rest of registers
9622  */
9623 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9624   // rdx:rax = op1 * op2
9625   movq(raxReg, op2);
9626   mulq(op1);
9627 
9628   //  rdx:rax = sum + carry + rdx:rax
9629   addq(sum, carry);
9630   adcq(rdxReg, 0);
9631   addq(sum, raxReg);
9632   adcq(rdxReg, 0);
9633 
9634   // carry:sum = rdx:sum
9635   movq(carry, rdxReg);
9636 }
9637 
9638 /**
9639  * Add 64 bit long carry into z[] with carry propogation.
9640  * Preserves z and carry register values and modifies rest of registers.
9641  *
9642  */
9643 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9644   Label L_fourth_loop, L_fourth_loop_exit;
9645 
9646   movl(tmp1, 1);
9647   subl(zlen, 2);
9648   addq(Address(z, zlen, Address::times_4, 0), carry);
9649 
9650   bind(L_fourth_loop);
9651   jccb(Assembler::carryClear, L_fourth_loop_exit);
9652   subl(zlen, 2);
9653   jccb(Assembler::negative, L_fourth_loop_exit);
9654   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9655   jmp(L_fourth_loop);
9656   bind(L_fourth_loop_exit);
9657 }
9658 
9659 /**
9660  * Shift z[] left by 1 bit.
9661  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9662  *
9663  */
9664 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9665 
9666   Label L_fifth_loop, L_fifth_loop_exit;
9667 
9668   // Fifth loop
9669   // Perform primitiveLeftShift(z, zlen, 1)
9670 
9671   const Register prev_carry = tmp1;
9672   const Register new_carry = tmp4;
9673   const Register value = tmp2;
9674   const Register zidx = tmp3;
9675 
9676   // int zidx, carry;
9677   // long value;
9678   // carry = 0;
9679   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9680   //    (carry:value)  = (z[i] << 1) | carry ;
9681   //    z[i] = value;
9682   // }
9683 
9684   movl(zidx, zlen);
9685   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9686 
9687   bind(L_fifth_loop);
9688   decl(zidx);  // Use decl to preserve carry flag
9689   decl(zidx);
9690   jccb(Assembler::negative, L_fifth_loop_exit);
9691 
9692   if (UseBMI2Instructions) {
9693      movq(value, Address(z, zidx, Address::times_4, 0));
9694      rclq(value, 1);
9695      rorxq(value, value, 32);
9696      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9697   }
9698   else {
9699     // clear new_carry
9700     xorl(new_carry, new_carry);
9701 
9702     // Shift z[i] by 1, or in previous carry and save new carry
9703     movq(value, Address(z, zidx, Address::times_4, 0));
9704     shlq(value, 1);
9705     adcl(new_carry, 0);
9706 
9707     orq(value, prev_carry);
9708     rorq(value, 0x20);
9709     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9710 
9711     // Set previous carry = new carry
9712     movl(prev_carry, new_carry);
9713   }
9714   jmp(L_fifth_loop);
9715 
9716   bind(L_fifth_loop_exit);
9717 }
9718 
9719 
9720 /**
9721  * Code for BigInteger::squareToLen() intrinsic
9722  *
9723  * rdi: x
9724  * rsi: len
9725  * r8:  z
9726  * rcx: zlen
9727  * r12: tmp1
9728  * r13: tmp2
9729  * r14: tmp3
9730  * r15: tmp4
9731  * rbx: tmp5
9732  *
9733  */
9734 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) {
9735 
9736   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;
9737   push(tmp1);
9738   push(tmp2);
9739   push(tmp3);
9740   push(tmp4);
9741   push(tmp5);
9742 
9743   // First loop
9744   // Store the squares, right shifted one bit (i.e., divided by 2).
9745   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9746 
9747   // Add in off-diagonal sums.
9748   //
9749   // Second, third (nested) and fourth loops.
9750   // zlen +=2;
9751   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9752   //    carry = 0;
9753   //    long op2 = x[xidx:xidx+1];
9754   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9755   //       k -= 2;
9756   //       long op1 = x[j:j+1];
9757   //       long sum = z[k:k+1];
9758   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9759   //       z[k:k+1] = sum;
9760   //    }
9761   //    add_one_64(z, k, carry, tmp_regs);
9762   // }
9763 
9764   const Register carry = tmp5;
9765   const Register sum = tmp3;
9766   const Register op1 = tmp4;
9767   Register op2 = tmp2;
9768 
9769   push(zlen);
9770   push(len);
9771   addl(zlen,2);
9772   bind(L_second_loop);
9773   xorq(carry, carry);
9774   subl(zlen, 4);
9775   subl(len, 2);
9776   push(zlen);
9777   push(len);
9778   cmpl(len, 0);
9779   jccb(Assembler::lessEqual, L_second_loop_exit);
9780 
9781   // Multiply an array by one 64 bit long.
9782   if (UseBMI2Instructions) {
9783     op2 = rdxReg;
9784     movq(op2, Address(x, len, Address::times_4,  0));
9785     rorxq(op2, op2, 32);
9786   }
9787   else {
9788     movq(op2, Address(x, len, Address::times_4,  0));
9789     rorq(op2, 32);
9790   }
9791 
9792   bind(L_third_loop);
9793   decrementl(len);
9794   jccb(Assembler::negative, L_third_loop_exit);
9795   decrementl(len);
9796   jccb(Assembler::negative, L_last_x);
9797 
9798   movq(op1, Address(x, len, Address::times_4,  0));
9799   rorq(op1, 32);
9800 
9801   bind(L_multiply);
9802   subl(zlen, 2);
9803   movq(sum, Address(z, zlen, Address::times_4,  0));
9804 
9805   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9806   if (UseBMI2Instructions) {
9807     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9808   }
9809   else {
9810     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9811   }
9812 
9813   movq(Address(z, zlen, Address::times_4, 0), sum);
9814 
9815   jmp(L_third_loop);
9816   bind(L_third_loop_exit);
9817 
9818   // Fourth loop
9819   // Add 64 bit long carry into z with carry propogation.
9820   // Uses offsetted zlen.
9821   add_one_64(z, zlen, carry, tmp1);
9822 
9823   pop(len);
9824   pop(zlen);
9825   jmp(L_second_loop);
9826 
9827   // Next infrequent code is moved outside loops.
9828   bind(L_last_x);
9829   movl(op1, Address(x, 0));
9830   jmp(L_multiply);
9831 
9832   bind(L_second_loop_exit);
9833   pop(len);
9834   pop(zlen);
9835   pop(len);
9836   pop(zlen);
9837 
9838   // Fifth loop
9839   // Shift z left 1 bit.
9840   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9841 
9842   // z[zlen-1] |= x[len-1] & 1;
9843   movl(tmp3, Address(x, len, Address::times_4, -4));
9844   andl(tmp3, 1);
9845   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9846 
9847   pop(tmp5);
9848   pop(tmp4);
9849   pop(tmp3);
9850   pop(tmp2);
9851   pop(tmp1);
9852 }
9853 
9854 /**
9855  * Helper function for mul_add()
9856  * Multiply the in[] by int k and add to out[] starting at offset offs using
9857  * 128 bit by 32 bit multiply and return the carry in tmp5.
9858  * Only quad int aligned length of in[] is operated on in this function.
9859  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9860  * This function preserves out, in and k registers.
9861  * len and offset point to the appropriate index in "in" & "out" correspondingly
9862  * tmp5 has the carry.
9863  * other registers are temporary and are modified.
9864  *
9865  */
9866 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9867   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9868   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9869 
9870   Label L_first_loop, L_first_loop_exit;
9871 
9872   movl(tmp1, len);
9873   shrl(tmp1, 2);
9874 
9875   bind(L_first_loop);
9876   subl(tmp1, 1);
9877   jccb(Assembler::negative, L_first_loop_exit);
9878 
9879   subl(len, 4);
9880   subl(offset, 4);
9881 
9882   Register op2 = tmp2;
9883   const Register sum = tmp3;
9884   const Register op1 = tmp4;
9885   const Register carry = tmp5;
9886 
9887   if (UseBMI2Instructions) {
9888     op2 = rdxReg;
9889   }
9890 
9891   movq(op1, Address(in, len, Address::times_4,  8));
9892   rorq(op1, 32);
9893   movq(sum, Address(out, offset, Address::times_4,  8));
9894   rorq(sum, 32);
9895   if (UseBMI2Instructions) {
9896     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9897   }
9898   else {
9899     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9900   }
9901   // Store back in big endian from little endian
9902   rorq(sum, 0x20);
9903   movq(Address(out, offset, Address::times_4,  8), sum);
9904 
9905   movq(op1, Address(in, len, Address::times_4,  0));
9906   rorq(op1, 32);
9907   movq(sum, Address(out, offset, Address::times_4,  0));
9908   rorq(sum, 32);
9909   if (UseBMI2Instructions) {
9910     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9911   }
9912   else {
9913     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9914   }
9915   // Store back in big endian from little endian
9916   rorq(sum, 0x20);
9917   movq(Address(out, offset, Address::times_4,  0), sum);
9918 
9919   jmp(L_first_loop);
9920   bind(L_first_loop_exit);
9921 }
9922 
9923 /**
9924  * Code for BigInteger::mulAdd() intrinsic
9925  *
9926  * rdi: out
9927  * rsi: in
9928  * r11: offs (out.length - offset)
9929  * rcx: len
9930  * r8:  k
9931  * r12: tmp1
9932  * r13: tmp2
9933  * r14: tmp3
9934  * r15: tmp4
9935  * rbx: tmp5
9936  * Multiply the in[] by word k and add to out[], return the carry in rax
9937  */
9938 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9939    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9940    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9941 
9942   Label L_carry, L_last_in, L_done;
9943 
9944 // carry = 0;
9945 // for (int j=len-1; j >= 0; j--) {
9946 //    long product = (in[j] & LONG_MASK) * kLong +
9947 //                   (out[offs] & LONG_MASK) + carry;
9948 //    out[offs--] = (int)product;
9949 //    carry = product >>> 32;
9950 // }
9951 //
9952   push(tmp1);
9953   push(tmp2);
9954   push(tmp3);
9955   push(tmp4);
9956   push(tmp5);
9957 
9958   Register op2 = tmp2;
9959   const Register sum = tmp3;
9960   const Register op1 = tmp4;
9961   const Register carry =  tmp5;
9962 
9963   if (UseBMI2Instructions) {
9964     op2 = rdxReg;
9965     movl(op2, k);
9966   }
9967   else {
9968     movl(op2, k);
9969   }
9970 
9971   xorq(carry, carry);
9972 
9973   //First loop
9974 
9975   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9976   //The carry is in tmp5
9977   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9978 
9979   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9980   decrementl(len);
9981   jccb(Assembler::negative, L_carry);
9982   decrementl(len);
9983   jccb(Assembler::negative, L_last_in);
9984 
9985   movq(op1, Address(in, len, Address::times_4,  0));
9986   rorq(op1, 32);
9987 
9988   subl(offs, 2);
9989   movq(sum, Address(out, offs, Address::times_4,  0));
9990   rorq(sum, 32);
9991 
9992   if (UseBMI2Instructions) {
9993     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9994   }
9995   else {
9996     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9997   }
9998 
9999   // Store back in big endian from little endian
10000   rorq(sum, 0x20);
10001   movq(Address(out, offs, Address::times_4,  0), sum);
10002 
10003   testl(len, len);
10004   jccb(Assembler::zero, L_carry);
10005 
10006   //Multiply the last in[] entry, if any
10007   bind(L_last_in);
10008   movl(op1, Address(in, 0));
10009   movl(sum, Address(out, offs, Address::times_4,  -4));
10010 
10011   movl(raxReg, k);
10012   mull(op1); //tmp4 * eax -> edx:eax
10013   addl(sum, carry);
10014   adcl(rdxReg, 0);
10015   addl(sum, raxReg);
10016   adcl(rdxReg, 0);
10017   movl(carry, rdxReg);
10018 
10019   movl(Address(out, offs, Address::times_4,  -4), sum);
10020 
10021   bind(L_carry);
10022   //return tmp5/carry as carry in rax
10023   movl(rax, carry);
10024 
10025   bind(L_done);
10026   pop(tmp5);
10027   pop(tmp4);
10028   pop(tmp3);
10029   pop(tmp2);
10030   pop(tmp1);
10031 }
10032 #endif
10033 
10034 /**
10035  * Emits code to update CRC-32 with a byte value according to constants in table
10036  *
10037  * @param [in,out]crc   Register containing the crc.
10038  * @param [in]val       Register containing the byte to fold into the CRC.
10039  * @param [in]table     Register containing the table of crc constants.
10040  *
10041  * uint32_t crc;
10042  * val = crc_table[(val ^ crc) & 0xFF];
10043  * crc = val ^ (crc >> 8);
10044  *
10045  */
10046 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10047   xorl(val, crc);
10048   andl(val, 0xFF);
10049   shrl(crc, 8); // unsigned shift
10050   xorl(crc, Address(table, val, Address::times_4, 0));
10051 }
10052 
10053 /**
10054  * Fold 128-bit data chunk
10055  */
10056 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10057   if (UseAVX > 0) {
10058     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10059     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10060     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10061     pxor(xcrc, xtmp);
10062   } else {
10063     movdqa(xtmp, xcrc);
10064     pclmulhdq(xtmp, xK);   // [123:64]
10065     pclmulldq(xcrc, xK);   // [63:0]
10066     pxor(xcrc, xtmp);
10067     movdqu(xtmp, Address(buf, offset));
10068     pxor(xcrc, xtmp);
10069   }
10070 }
10071 
10072 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10073   if (UseAVX > 0) {
10074     vpclmulhdq(xtmp, xK, xcrc);
10075     vpclmulldq(xcrc, xK, xcrc);
10076     pxor(xcrc, xbuf);
10077     pxor(xcrc, xtmp);
10078   } else {
10079     movdqa(xtmp, xcrc);
10080     pclmulhdq(xtmp, xK);
10081     pclmulldq(xcrc, xK);
10082     pxor(xcrc, xbuf);
10083     pxor(xcrc, xtmp);
10084   }
10085 }
10086 
10087 /**
10088  * 8-bit folds to compute 32-bit CRC
10089  *
10090  * uint64_t xcrc;
10091  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10092  */
10093 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10094   movdl(tmp, xcrc);
10095   andl(tmp, 0xFF);
10096   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10097   psrldq(xcrc, 1); // unsigned shift one byte
10098   pxor(xcrc, xtmp);
10099 }
10100 
10101 /**
10102  * uint32_t crc;
10103  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10104  */
10105 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10106   movl(tmp, crc);
10107   andl(tmp, 0xFF);
10108   shrl(crc, 8);
10109   xorl(crc, Address(table, tmp, Address::times_4, 0));
10110 }
10111 
10112 /**
10113  * @param crc   register containing existing CRC (32-bit)
10114  * @param buf   register pointing to input byte buffer (byte*)
10115  * @param len   register containing number of bytes
10116  * @param table register that will contain address of CRC table
10117  * @param tmp   scratch register
10118  */
10119 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10120   assert_different_registers(crc, buf, len, table, tmp, rax);
10121 
10122   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10123   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10124 
10125   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10126   // context for the registers used, where all instructions below are using 128-bit mode
10127   // On EVEX without VL and BW, these instructions will all be AVX.
10128   if (VM_Version::supports_avx512vlbw()) {
10129     movl(tmp, 0xffff);
10130     kmovwl(k1, tmp);
10131   }
10132 
10133   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10134   notl(crc); // ~crc
10135   cmpl(len, 16);
10136   jcc(Assembler::less, L_tail);
10137 
10138   // Align buffer to 16 bytes
10139   movl(tmp, buf);
10140   andl(tmp, 0xF);
10141   jccb(Assembler::zero, L_aligned);
10142   subl(tmp,  16);
10143   addl(len, tmp);
10144 
10145   align(4);
10146   BIND(L_align_loop);
10147   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10148   update_byte_crc32(crc, rax, table);
10149   increment(buf);
10150   incrementl(tmp);
10151   jccb(Assembler::less, L_align_loop);
10152 
10153   BIND(L_aligned);
10154   movl(tmp, len); // save
10155   shrl(len, 4);
10156   jcc(Assembler::zero, L_tail_restore);
10157 
10158   // Fold crc into first bytes of vector
10159   movdqa(xmm1, Address(buf, 0));
10160   movdl(rax, xmm1);
10161   xorl(crc, rax);
10162   pinsrd(xmm1, crc, 0);
10163   addptr(buf, 16);
10164   subl(len, 4); // len > 0
10165   jcc(Assembler::less, L_fold_tail);
10166 
10167   movdqa(xmm2, Address(buf,  0));
10168   movdqa(xmm3, Address(buf, 16));
10169   movdqa(xmm4, Address(buf, 32));
10170   addptr(buf, 48);
10171   subl(len, 3);
10172   jcc(Assembler::lessEqual, L_fold_512b);
10173 
10174   // Fold total 512 bits of polynomial on each iteration,
10175   // 128 bits per each of 4 parallel streams.
10176   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10177 
10178   align(32);
10179   BIND(L_fold_512b_loop);
10180   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10181   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10182   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10183   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10184   addptr(buf, 64);
10185   subl(len, 4);
10186   jcc(Assembler::greater, L_fold_512b_loop);
10187 
10188   // Fold 512 bits to 128 bits.
10189   BIND(L_fold_512b);
10190   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10191   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10192   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10193   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10194 
10195   // Fold the rest of 128 bits data chunks
10196   BIND(L_fold_tail);
10197   addl(len, 3);
10198   jccb(Assembler::lessEqual, L_fold_128b);
10199   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10200 
10201   BIND(L_fold_tail_loop);
10202   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10203   addptr(buf, 16);
10204   decrementl(len);
10205   jccb(Assembler::greater, L_fold_tail_loop);
10206 
10207   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10208   BIND(L_fold_128b);
10209   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10210   if (UseAVX > 0) {
10211     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10212     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10213     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10214   } else {
10215     movdqa(xmm2, xmm0);
10216     pclmulqdq(xmm2, xmm1, 0x1);
10217     movdqa(xmm3, xmm0);
10218     pand(xmm3, xmm2);
10219     pclmulqdq(xmm0, xmm3, 0x1);
10220   }
10221   psrldq(xmm1, 8);
10222   psrldq(xmm2, 4);
10223   pxor(xmm0, xmm1);
10224   pxor(xmm0, xmm2);
10225 
10226   // 8 8-bit folds to compute 32-bit CRC.
10227   for (int j = 0; j < 4; j++) {
10228     fold_8bit_crc32(xmm0, table, xmm1, rax);
10229   }
10230   movdl(crc, xmm0); // mov 32 bits to general register
10231   for (int j = 0; j < 4; j++) {
10232     fold_8bit_crc32(crc, table, rax);
10233   }
10234 
10235   BIND(L_tail_restore);
10236   movl(len, tmp); // restore
10237   BIND(L_tail);
10238   andl(len, 0xf);
10239   jccb(Assembler::zero, L_exit);
10240 
10241   // Fold the rest of bytes
10242   align(4);
10243   BIND(L_tail_loop);
10244   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10245   update_byte_crc32(crc, rax, table);
10246   increment(buf);
10247   decrementl(len);
10248   jccb(Assembler::greater, L_tail_loop);
10249 
10250   BIND(L_exit);
10251   notl(crc); // ~c
10252 }
10253 
10254 #ifdef _LP64
10255 // S. Gueron / Information Processing Letters 112 (2012) 184
10256 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10257 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10258 // Output: the 64-bit carry-less product of B * CONST
10259 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10260                                      Register tmp1, Register tmp2, Register tmp3) {
10261   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10262   if (n > 0) {
10263     addq(tmp3, n * 256 * 8);
10264   }
10265   //    Q1 = TABLEExt[n][B & 0xFF];
10266   movl(tmp1, in);
10267   andl(tmp1, 0x000000FF);
10268   shll(tmp1, 3);
10269   addq(tmp1, tmp3);
10270   movq(tmp1, Address(tmp1, 0));
10271 
10272   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10273   movl(tmp2, in);
10274   shrl(tmp2, 8);
10275   andl(tmp2, 0x000000FF);
10276   shll(tmp2, 3);
10277   addq(tmp2, tmp3);
10278   movq(tmp2, Address(tmp2, 0));
10279 
10280   shlq(tmp2, 8);
10281   xorq(tmp1, tmp2);
10282 
10283   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10284   movl(tmp2, in);
10285   shrl(tmp2, 16);
10286   andl(tmp2, 0x000000FF);
10287   shll(tmp2, 3);
10288   addq(tmp2, tmp3);
10289   movq(tmp2, Address(tmp2, 0));
10290 
10291   shlq(tmp2, 16);
10292   xorq(tmp1, tmp2);
10293 
10294   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10295   shrl(in, 24);
10296   andl(in, 0x000000FF);
10297   shll(in, 3);
10298   addq(in, tmp3);
10299   movq(in, Address(in, 0));
10300 
10301   shlq(in, 24);
10302   xorq(in, tmp1);
10303   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10304 }
10305 
10306 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10307                                       Register in_out,
10308                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10309                                       XMMRegister w_xtmp2,
10310                                       Register tmp1,
10311                                       Register n_tmp2, Register n_tmp3) {
10312   if (is_pclmulqdq_supported) {
10313     movdl(w_xtmp1, in_out); // modified blindly
10314 
10315     movl(tmp1, const_or_pre_comp_const_index);
10316     movdl(w_xtmp2, tmp1);
10317     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10318 
10319     movdq(in_out, w_xtmp1);
10320   } else {
10321     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10322   }
10323 }
10324 
10325 // Recombination Alternative 2: No bit-reflections
10326 // T1 = (CRC_A * U1) << 1
10327 // T2 = (CRC_B * U2) << 1
10328 // C1 = T1 >> 32
10329 // C2 = T2 >> 32
10330 // T1 = T1 & 0xFFFFFFFF
10331 // T2 = T2 & 0xFFFFFFFF
10332 // T1 = CRC32(0, T1)
10333 // T2 = CRC32(0, T2)
10334 // C1 = C1 ^ T1
10335 // C2 = C2 ^ T2
10336 // CRC = C1 ^ C2 ^ CRC_C
10337 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,
10338                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10339                                      Register tmp1, Register tmp2,
10340                                      Register n_tmp3) {
10341   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10342   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10343   shlq(in_out, 1);
10344   movl(tmp1, in_out);
10345   shrq(in_out, 32);
10346   xorl(tmp2, tmp2);
10347   crc32(tmp2, tmp1, 4);
10348   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10349   shlq(in1, 1);
10350   movl(tmp1, in1);
10351   shrq(in1, 32);
10352   xorl(tmp2, tmp2);
10353   crc32(tmp2, tmp1, 4);
10354   xorl(in1, tmp2);
10355   xorl(in_out, in1);
10356   xorl(in_out, in2);
10357 }
10358 
10359 // Set N to predefined value
10360 // Subtract from a lenght of a buffer
10361 // execute in a loop:
10362 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10363 // for i = 1 to N do
10364 //  CRC_A = CRC32(CRC_A, A[i])
10365 //  CRC_B = CRC32(CRC_B, B[i])
10366 //  CRC_C = CRC32(CRC_C, C[i])
10367 // end for
10368 // Recombine
10369 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,
10370                                        Register in_out1, Register in_out2, Register in_out3,
10371                                        Register tmp1, Register tmp2, Register tmp3,
10372                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10373                                        Register tmp4, Register tmp5,
10374                                        Register n_tmp6) {
10375   Label L_processPartitions;
10376   Label L_processPartition;
10377   Label L_exit;
10378 
10379   bind(L_processPartitions);
10380   cmpl(in_out1, 3 * size);
10381   jcc(Assembler::less, L_exit);
10382     xorl(tmp1, tmp1);
10383     xorl(tmp2, tmp2);
10384     movq(tmp3, in_out2);
10385     addq(tmp3, size);
10386 
10387     bind(L_processPartition);
10388       crc32(in_out3, Address(in_out2, 0), 8);
10389       crc32(tmp1, Address(in_out2, size), 8);
10390       crc32(tmp2, Address(in_out2, size * 2), 8);
10391       addq(in_out2, 8);
10392       cmpq(in_out2, tmp3);
10393       jcc(Assembler::less, L_processPartition);
10394     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10395             w_xtmp1, w_xtmp2, w_xtmp3,
10396             tmp4, tmp5,
10397             n_tmp6);
10398     addq(in_out2, 2 * size);
10399     subl(in_out1, 3 * size);
10400     jmp(L_processPartitions);
10401 
10402   bind(L_exit);
10403 }
10404 #else
10405 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10406                                      Register tmp1, Register tmp2, Register tmp3,
10407                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10408   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10409   if (n > 0) {
10410     addl(tmp3, n * 256 * 8);
10411   }
10412   //    Q1 = TABLEExt[n][B & 0xFF];
10413   movl(tmp1, in_out);
10414   andl(tmp1, 0x000000FF);
10415   shll(tmp1, 3);
10416   addl(tmp1, tmp3);
10417   movq(xtmp1, Address(tmp1, 0));
10418 
10419   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10420   movl(tmp2, in_out);
10421   shrl(tmp2, 8);
10422   andl(tmp2, 0x000000FF);
10423   shll(tmp2, 3);
10424   addl(tmp2, tmp3);
10425   movq(xtmp2, Address(tmp2, 0));
10426 
10427   psllq(xtmp2, 8);
10428   pxor(xtmp1, xtmp2);
10429 
10430   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10431   movl(tmp2, in_out);
10432   shrl(tmp2, 16);
10433   andl(tmp2, 0x000000FF);
10434   shll(tmp2, 3);
10435   addl(tmp2, tmp3);
10436   movq(xtmp2, Address(tmp2, 0));
10437 
10438   psllq(xtmp2, 16);
10439   pxor(xtmp1, xtmp2);
10440 
10441   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10442   shrl(in_out, 24);
10443   andl(in_out, 0x000000FF);
10444   shll(in_out, 3);
10445   addl(in_out, tmp3);
10446   movq(xtmp2, Address(in_out, 0));
10447 
10448   psllq(xtmp2, 24);
10449   pxor(xtmp1, xtmp2); // Result in CXMM
10450   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10451 }
10452 
10453 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10454                                       Register in_out,
10455                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10456                                       XMMRegister w_xtmp2,
10457                                       Register tmp1,
10458                                       Register n_tmp2, Register n_tmp3) {
10459   if (is_pclmulqdq_supported) {
10460     movdl(w_xtmp1, in_out);
10461 
10462     movl(tmp1, const_or_pre_comp_const_index);
10463     movdl(w_xtmp2, tmp1);
10464     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10465     // Keep result in XMM since GPR is 32 bit in length
10466   } else {
10467     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10468   }
10469 }
10470 
10471 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,
10472                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10473                                      Register tmp1, Register tmp2,
10474                                      Register n_tmp3) {
10475   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10476   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10477 
10478   psllq(w_xtmp1, 1);
10479   movdl(tmp1, w_xtmp1);
10480   psrlq(w_xtmp1, 32);
10481   movdl(in_out, w_xtmp1);
10482 
10483   xorl(tmp2, tmp2);
10484   crc32(tmp2, tmp1, 4);
10485   xorl(in_out, tmp2);
10486 
10487   psllq(w_xtmp2, 1);
10488   movdl(tmp1, w_xtmp2);
10489   psrlq(w_xtmp2, 32);
10490   movdl(in1, w_xtmp2);
10491 
10492   xorl(tmp2, tmp2);
10493   crc32(tmp2, tmp1, 4);
10494   xorl(in1, tmp2);
10495   xorl(in_out, in1);
10496   xorl(in_out, in2);
10497 }
10498 
10499 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,
10500                                        Register in_out1, Register in_out2, Register in_out3,
10501                                        Register tmp1, Register tmp2, Register tmp3,
10502                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10503                                        Register tmp4, Register tmp5,
10504                                        Register n_tmp6) {
10505   Label L_processPartitions;
10506   Label L_processPartition;
10507   Label L_exit;
10508 
10509   bind(L_processPartitions);
10510   cmpl(in_out1, 3 * size);
10511   jcc(Assembler::less, L_exit);
10512     xorl(tmp1, tmp1);
10513     xorl(tmp2, tmp2);
10514     movl(tmp3, in_out2);
10515     addl(tmp3, size);
10516 
10517     bind(L_processPartition);
10518       crc32(in_out3, Address(in_out2, 0), 4);
10519       crc32(tmp1, Address(in_out2, size), 4);
10520       crc32(tmp2, Address(in_out2, size*2), 4);
10521       crc32(in_out3, Address(in_out2, 0+4), 4);
10522       crc32(tmp1, Address(in_out2, size+4), 4);
10523       crc32(tmp2, Address(in_out2, size*2+4), 4);
10524       addl(in_out2, 8);
10525       cmpl(in_out2, tmp3);
10526       jcc(Assembler::less, L_processPartition);
10527 
10528         push(tmp3);
10529         push(in_out1);
10530         push(in_out2);
10531         tmp4 = tmp3;
10532         tmp5 = in_out1;
10533         n_tmp6 = in_out2;
10534 
10535       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10536             w_xtmp1, w_xtmp2, w_xtmp3,
10537             tmp4, tmp5,
10538             n_tmp6);
10539 
10540         pop(in_out2);
10541         pop(in_out1);
10542         pop(tmp3);
10543 
10544     addl(in_out2, 2 * size);
10545     subl(in_out1, 3 * size);
10546     jmp(L_processPartitions);
10547 
10548   bind(L_exit);
10549 }
10550 #endif //LP64
10551 
10552 #ifdef _LP64
10553 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10554 // Input: A buffer I of L bytes.
10555 // Output: the CRC32C value of the buffer.
10556 // Notations:
10557 // Write L = 24N + r, with N = floor (L/24).
10558 // r = L mod 24 (0 <= r < 24).
10559 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10560 // N quadwords, and R consists of r bytes.
10561 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10562 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10563 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10564 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10565 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10566                                           Register tmp1, Register tmp2, Register tmp3,
10567                                           Register tmp4, Register tmp5, Register tmp6,
10568                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10569                                           bool is_pclmulqdq_supported) {
10570   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10571   Label L_wordByWord;
10572   Label L_byteByByteProlog;
10573   Label L_byteByByte;
10574   Label L_exit;
10575 
10576   if (is_pclmulqdq_supported ) {
10577     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10578     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10579 
10580     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10581     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10582 
10583     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10584     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10585     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10586   } else {
10587     const_or_pre_comp_const_index[0] = 1;
10588     const_or_pre_comp_const_index[1] = 0;
10589 
10590     const_or_pre_comp_const_index[2] = 3;
10591     const_or_pre_comp_const_index[3] = 2;
10592 
10593     const_or_pre_comp_const_index[4] = 5;
10594     const_or_pre_comp_const_index[5] = 4;
10595    }
10596   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10597                     in2, in1, in_out,
10598                     tmp1, tmp2, tmp3,
10599                     w_xtmp1, w_xtmp2, w_xtmp3,
10600                     tmp4, tmp5,
10601                     tmp6);
10602   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10603                     in2, in1, in_out,
10604                     tmp1, tmp2, tmp3,
10605                     w_xtmp1, w_xtmp2, w_xtmp3,
10606                     tmp4, tmp5,
10607                     tmp6);
10608   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10609                     in2, in1, in_out,
10610                     tmp1, tmp2, tmp3,
10611                     w_xtmp1, w_xtmp2, w_xtmp3,
10612                     tmp4, tmp5,
10613                     tmp6);
10614   movl(tmp1, in2);
10615   andl(tmp1, 0x00000007);
10616   negl(tmp1);
10617   addl(tmp1, in2);
10618   addq(tmp1, in1);
10619 
10620   BIND(L_wordByWord);
10621   cmpq(in1, tmp1);
10622   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10623     crc32(in_out, Address(in1, 0), 4);
10624     addq(in1, 4);
10625     jmp(L_wordByWord);
10626 
10627   BIND(L_byteByByteProlog);
10628   andl(in2, 0x00000007);
10629   movl(tmp2, 1);
10630 
10631   BIND(L_byteByByte);
10632   cmpl(tmp2, in2);
10633   jccb(Assembler::greater, L_exit);
10634     crc32(in_out, Address(in1, 0), 1);
10635     incq(in1);
10636     incl(tmp2);
10637     jmp(L_byteByByte);
10638 
10639   BIND(L_exit);
10640 }
10641 #else
10642 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10643                                           Register tmp1, Register  tmp2, Register tmp3,
10644                                           Register tmp4, Register  tmp5, Register tmp6,
10645                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10646                                           bool is_pclmulqdq_supported) {
10647   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10648   Label L_wordByWord;
10649   Label L_byteByByteProlog;
10650   Label L_byteByByte;
10651   Label L_exit;
10652 
10653   if (is_pclmulqdq_supported) {
10654     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10655     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10656 
10657     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10658     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10659 
10660     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10661     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10662   } else {
10663     const_or_pre_comp_const_index[0] = 1;
10664     const_or_pre_comp_const_index[1] = 0;
10665 
10666     const_or_pre_comp_const_index[2] = 3;
10667     const_or_pre_comp_const_index[3] = 2;
10668 
10669     const_or_pre_comp_const_index[4] = 5;
10670     const_or_pre_comp_const_index[5] = 4;
10671   }
10672   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10673                     in2, in1, in_out,
10674                     tmp1, tmp2, tmp3,
10675                     w_xtmp1, w_xtmp2, w_xtmp3,
10676                     tmp4, tmp5,
10677                     tmp6);
10678   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10679                     in2, in1, in_out,
10680                     tmp1, tmp2, tmp3,
10681                     w_xtmp1, w_xtmp2, w_xtmp3,
10682                     tmp4, tmp5,
10683                     tmp6);
10684   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10685                     in2, in1, in_out,
10686                     tmp1, tmp2, tmp3,
10687                     w_xtmp1, w_xtmp2, w_xtmp3,
10688                     tmp4, tmp5,
10689                     tmp6);
10690   movl(tmp1, in2);
10691   andl(tmp1, 0x00000007);
10692   negl(tmp1);
10693   addl(tmp1, in2);
10694   addl(tmp1, in1);
10695 
10696   BIND(L_wordByWord);
10697   cmpl(in1, tmp1);
10698   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10699     crc32(in_out, Address(in1,0), 4);
10700     addl(in1, 4);
10701     jmp(L_wordByWord);
10702 
10703   BIND(L_byteByByteProlog);
10704   andl(in2, 0x00000007);
10705   movl(tmp2, 1);
10706 
10707   BIND(L_byteByByte);
10708   cmpl(tmp2, in2);
10709   jccb(Assembler::greater, L_exit);
10710     movb(tmp1, Address(in1, 0));
10711     crc32(in_out, tmp1, 1);
10712     incl(in1);
10713     incl(tmp2);
10714     jmp(L_byteByByte);
10715 
10716   BIND(L_exit);
10717 }
10718 #endif // LP64
10719 #undef BIND
10720 #undef BLOCK_COMMENT
10721 
10722 // Compress char[] array to byte[].
10723 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10724 //   @HotSpotIntrinsicCandidate
10725 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10726 //     for (int i = 0; i < len; i++) {
10727 //       int c = src[srcOff++];
10728 //       if (c >>> 8 != 0) {
10729 //         return 0;
10730 //       }
10731 //       dst[dstOff++] = (byte)c;
10732 //     }
10733 //     return len;
10734 //   }
10735 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10736   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10737   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10738   Register tmp5, Register result) {
10739   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10740 
10741   // rsi: src
10742   // rdi: dst
10743   // rdx: len
10744   // rcx: tmp5
10745   // rax: result
10746 
10747   // rsi holds start addr of source char[] to be compressed
10748   // rdi holds start addr of destination byte[]
10749   // rdx holds length
10750 
10751   assert(len != result, "");
10752 
10753   // save length for return
10754   push(len);
10755 
10756   if ((UseAVX > 2) && // AVX512
10757     VM_Version::supports_avx512vlbw() &&
10758     VM_Version::supports_bmi2()) {
10759 
10760     set_vector_masking();  // opening of the stub context for programming mask registers
10761 
10762     Label copy_32_loop, copy_loop_tail, copy_just_portion_of_candidates;
10763 
10764     // alignement
10765     Label post_alignement;
10766 
10767     // if length of the string is less than 16, handle it in an old fashioned
10768     // way
10769     testl(len, -32);
10770     jcc(Assembler::zero, below_threshold);
10771 
10772     // First check whether a character is compressable ( <= 0xFF).
10773     // Create mask to test for Unicode chars inside zmm vector
10774     movl(result, 0x00FF);
10775     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10776 
10777     testl(len, -64);
10778     jcc(Assembler::zero, post_alignement);
10779 
10780     // Save k1
10781     kmovql(k3, k1);
10782 
10783     movl(tmp5, dst);
10784     andl(tmp5, (64 - 1));
10785     negl(tmp5);
10786     andl(tmp5, (64 - 1));
10787 
10788     // bail out when there is nothing to be done
10789     testl(tmp5, 0xFFFFFFFF);
10790     jcc(Assembler::zero, post_alignement);
10791 
10792     // ~(~0 << len), where len is the # of remaining elements to process
10793     movl(result, 0xFFFFFFFF);
10794     shlxl(result, result, tmp5);
10795     notl(result);
10796 
10797     kmovdl(k1, result);
10798 
10799     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10800     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10801     ktestd(k2, k1);
10802     jcc(Assembler::carryClear, copy_just_portion_of_candidates);
10803 
10804     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10805 
10806     addptr(src, tmp5);
10807     addptr(src, tmp5);
10808     addptr(dst, tmp5);
10809     subl(len, tmp5);
10810 
10811     bind(post_alignement);
10812     // end of alignement
10813 
10814     movl(tmp5, len);
10815     andl(tmp5, (32 - 1));   // tail count (in chars)
10816     andl(len, ~(32 - 1));    // vector count (in chars)
10817     jcc(Assembler::zero, copy_loop_tail);
10818 
10819     lea(src, Address(src, len, Address::times_2));
10820     lea(dst, Address(dst, len, Address::times_1));
10821     negptr(len);
10822 
10823     bind(copy_32_loop);
10824     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10825     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10826     kortestdl(k2, k2);
10827     jcc(Assembler::carryClear, copy_just_portion_of_candidates);
10828 
10829     // All elements in current processed chunk are valid candidates for
10830     // compression. Write a truncated byte elements to the memory.
10831     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10832     addptr(len, 32);
10833     jcc(Assembler::notZero, copy_32_loop);
10834 
10835     bind(copy_loop_tail);
10836     // bail out when there is nothing to be done
10837     testl(tmp5, 0xFFFFFFFF);
10838     jcc(Assembler::zero, return_length);
10839 
10840     // Save k1
10841     kmovql(k3, k1);
10842 
10843     movl(len, tmp5);
10844 
10845     // ~(~0 << len), where len is the # of remaining elements to process
10846     movl(result, 0xFFFFFFFF);
10847     shlxl(result, result, len);
10848     notl(result);
10849 
10850     kmovdl(k1, result);
10851 
10852     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10853     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10854     ktestd(k2, k1);
10855     jcc(Assembler::carryClear, copy_just_portion_of_candidates);
10856 
10857     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10858     // Restore k1
10859     kmovql(k1, k3);
10860 
10861     jmp(return_length);
10862 
10863     bind(copy_just_portion_of_candidates);
10864     kmovdl(tmp5, k2);
10865     tzcntl(tmp5, tmp5);
10866 
10867     // ~(~0 << tmp5), where tmp5 is a number of elements in an array from the
10868     // result to the first element larger than 0xFF
10869     movl(result, 0xFFFFFFFF);
10870     shlxl(result, result, tmp5);
10871     notl(result);
10872 
10873     kmovdl(k1, result);
10874 
10875     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10876     // Restore k1
10877     kmovql(k1, k3);
10878 
10879     jmp(return_zero);
10880 
10881     clear_vector_masking();   // closing of the stub context for programming mask registers
10882   }
10883   if (UseSSE42Intrinsics) {
10884     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
10885     Label copy_32_loop, copy_16, copy_tail;
10886 
10887     bind(below_threshold);
10888 
10889     movl(result, len);
10890 
10891     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10892 
10893     // vectored compression
10894     andl(len, 0xfffffff0);    // vector count (in chars)
10895     andl(result, 0x0000000f);    // tail count (in chars)
10896     testl(len, len);
10897     jccb(Assembler::zero, copy_16);
10898 
10899     // compress 16 chars per iter
10900     movdl(tmp1Reg, tmp5);
10901     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10902     pxor(tmp4Reg, tmp4Reg);
10903 
10904     lea(src, Address(src, len, Address::times_2));
10905     lea(dst, Address(dst, len, Address::times_1));
10906     negptr(len);
10907 
10908     bind(copy_32_loop);
10909     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10910     por(tmp4Reg, tmp2Reg);
10911     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10912     por(tmp4Reg, tmp3Reg);
10913     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10914     jcc(Assembler::notZero, return_zero);
10915     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10916     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10917     addptr(len, 16);
10918     jcc(Assembler::notZero, copy_32_loop);
10919 
10920     // compress next vector of 8 chars (if any)
10921     bind(copy_16);
10922     movl(len, result);
10923     andl(len, 0xfffffff8);    // vector count (in chars)
10924     andl(result, 0x00000007);    // tail count (in chars)
10925     testl(len, len);
10926     jccb(Assembler::zero, copy_tail);
10927 
10928     movdl(tmp1Reg, tmp5);
10929     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10930     pxor(tmp3Reg, tmp3Reg);
10931 
10932     movdqu(tmp2Reg, Address(src, 0));
10933     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10934     jccb(Assembler::notZero, return_zero);
10935     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10936     movq(Address(dst, 0), tmp2Reg);
10937     addptr(src, 16);
10938     addptr(dst, 8);
10939 
10940     bind(copy_tail);
10941     movl(len, result);
10942   }
10943   // compress 1 char per iter
10944   testl(len, len);
10945   jccb(Assembler::zero, return_length);
10946   lea(src, Address(src, len, Address::times_2));
10947   lea(dst, Address(dst, len, Address::times_1));
10948   negptr(len);
10949 
10950   bind(copy_chars_loop);
10951   load_unsigned_short(result, Address(src, len, Address::times_2));
10952   testl(result, 0xff00);      // check if Unicode char
10953   jccb(Assembler::notZero, return_zero);
10954   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10955   increment(len);
10956   jcc(Assembler::notZero, copy_chars_loop);
10957 
10958   // if compression succeeded, return length
10959   bind(return_length);
10960   pop(result);
10961   jmpb(done);
10962 
10963   // if compression failed, return 0
10964   bind(return_zero);
10965   xorl(result, result);
10966   addptr(rsp, wordSize);
10967 
10968   bind(done);
10969 }
10970 
10971 // Inflate byte[] array to char[].
10972 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
10973 //   @HotSpotIntrinsicCandidate
10974 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
10975 //     for (int i = 0; i < len; i++) {
10976 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
10977 //     }
10978 //   }
10979 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10980   XMMRegister tmp1, Register tmp2) {
10981   Label copy_chars_loop, done, below_threshold;
10982   // rsi: src
10983   // rdi: dst
10984   // rdx: len
10985   // rcx: tmp2
10986 
10987   // rsi holds start addr of source byte[] to be inflated
10988   // rdi holds start addr of destination char[]
10989   // rdx holds length
10990   assert_different_registers(src, dst, len, tmp2);
10991 
10992   if ((UseAVX > 2) && // AVX512
10993     VM_Version::supports_avx512vlbw() &&
10994     VM_Version::supports_bmi2()) {
10995 
10996     set_vector_masking();  // opening of the stub context for programming mask registers
10997 
10998     Label copy_32_loop, copy_tail;
10999     Register tmp3_aliased = len;
11000 
11001     // if length of the string is less than 16, handle it in an old fashioned
11002     // way
11003     testl(len, -16);
11004     jcc(Assembler::zero, below_threshold);
11005 
11006     // In order to use only one arithmetic operation for the main loop we use
11007     // this pre-calculation
11008     movl(tmp2, len);
11009     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
11010     andl(len, -32);     // vector count
11011     jccb(Assembler::zero, copy_tail);
11012 
11013     lea(src, Address(src, len, Address::times_1));
11014     lea(dst, Address(dst, len, Address::times_2));
11015     negptr(len);
11016 
11017 
11018     // inflate 32 chars per iter
11019     bind(copy_32_loop);
11020     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
11021     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
11022     addptr(len, 32);
11023     jcc(Assembler::notZero, copy_32_loop);
11024 
11025     bind(copy_tail);
11026     // bail out when there is nothing to be done
11027     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
11028     jcc(Assembler::zero, done);
11029 
11030     // Save k1
11031     kmovql(k2, k1);
11032 
11033     // ~(~0 << length), where length is the # of remaining elements to process
11034     movl(tmp3_aliased, -1);
11035     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
11036     notl(tmp3_aliased);
11037     kmovdl(k1, tmp3_aliased);
11038     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
11039     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
11040 
11041     // Restore k1
11042     kmovql(k1, k2);
11043     jmp(done);
11044 
11045     clear_vector_masking();   // closing of the stub context for programming mask registers
11046   }
11047   if (UseSSE42Intrinsics) {
11048     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
11049     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
11050 
11051     movl(tmp2, len);
11052 
11053     if (UseAVX > 1) {
11054       andl(tmp2, (16 - 1));
11055       andl(len, -16);
11056       jccb(Assembler::zero, copy_new_tail);
11057     } else {
11058       andl(tmp2, 0x00000007);   // tail count (in chars)
11059       andl(len, 0xfffffff8);    // vector count (in chars)
11060       jccb(Assembler::zero, copy_tail);
11061     }
11062 
11063     // vectored inflation
11064     lea(src, Address(src, len, Address::times_1));
11065     lea(dst, Address(dst, len, Address::times_2));
11066     negptr(len);
11067 
11068     if (UseAVX > 1) {
11069       bind(copy_16_loop);
11070       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
11071       vmovdqu(Address(dst, len, Address::times_2), tmp1);
11072       addptr(len, 16);
11073       jcc(Assembler::notZero, copy_16_loop);
11074 
11075       bind(below_threshold);
11076       bind(copy_new_tail);
11077       if (UseAVX > 2) {
11078         movl(tmp2, len);
11079       }
11080       else {
11081         movl(len, tmp2);
11082       }
11083       andl(tmp2, 0x00000007);
11084       andl(len, 0xFFFFFFF8);
11085       jccb(Assembler::zero, copy_tail);
11086 
11087       pmovzxbw(tmp1, Address(src, 0));
11088       movdqu(Address(dst, 0), tmp1);
11089       addptr(src, 8);
11090       addptr(dst, 2 * 8);
11091 
11092       jmp(copy_tail, true);
11093     }
11094 
11095     // inflate 8 chars per iter
11096     bind(copy_8_loop);
11097     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
11098     movdqu(Address(dst, len, Address::times_2), tmp1);
11099     addptr(len, 8);
11100     jcc(Assembler::notZero, copy_8_loop);
11101 
11102     bind(copy_tail);
11103     movl(len, tmp2);
11104 
11105     cmpl(len, 4);
11106     jccb(Assembler::less, copy_bytes);
11107 
11108     movdl(tmp1, Address(src, 0));  // load 4 byte chars
11109     pmovzxbw(tmp1, tmp1);
11110     movq(Address(dst, 0), tmp1);
11111     subptr(len, 4);
11112     addptr(src, 4);
11113     addptr(dst, 8);
11114 
11115     bind(copy_bytes);
11116   }
11117   testl(len, len);
11118   jccb(Assembler::zero, done);
11119   lea(src, Address(src, len, Address::times_1));
11120   lea(dst, Address(dst, len, Address::times_2));
11121   negptr(len);
11122 
11123   // inflate 1 char per iter
11124   bind(copy_chars_loop);
11125   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11126   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11127   increment(len);
11128   jcc(Assembler::notZero, copy_chars_loop);
11129 
11130   bind(done);
11131 }
11132 
11133 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11134   switch (cond) {
11135     // Note some conditions are synonyms for others
11136     case Assembler::zero:         return Assembler::notZero;
11137     case Assembler::notZero:      return Assembler::zero;
11138     case Assembler::less:         return Assembler::greaterEqual;
11139     case Assembler::lessEqual:    return Assembler::greater;
11140     case Assembler::greater:      return Assembler::lessEqual;
11141     case Assembler::greaterEqual: return Assembler::less;
11142     case Assembler::below:        return Assembler::aboveEqual;
11143     case Assembler::belowEqual:   return Assembler::above;
11144     case Assembler::above:        return Assembler::belowEqual;
11145     case Assembler::aboveEqual:   return Assembler::below;
11146     case Assembler::overflow:     return Assembler::noOverflow;
11147     case Assembler::noOverflow:   return Assembler::overflow;
11148     case Assembler::negative:     return Assembler::positive;
11149     case Assembler::positive:     return Assembler::negative;
11150     case Assembler::parity:       return Assembler::noParity;
11151     case Assembler::noParity:     return Assembler::parity;
11152   }
11153   ShouldNotReachHere(); return Assembler::overflow;
11154 }
11155 
11156 SkipIfEqual::SkipIfEqual(
11157     MacroAssembler* masm, const bool* flag_addr, bool value) {
11158   _masm = masm;
11159   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11160   _masm->jcc(Assembler::equal, _label);
11161 }
11162 
11163 SkipIfEqual::~SkipIfEqual() {
11164   _masm->bind(_label);
11165 }
11166 
11167 // 32-bit Windows has its own fast-path implementation
11168 // of get_thread
11169 #if !defined(WIN32) || defined(_LP64)
11170 
11171 // This is simply a call to Thread::current()
11172 void MacroAssembler::get_thread(Register thread) {
11173   if (thread != rax) {
11174     push(rax);
11175   }
11176   LP64_ONLY(push(rdi);)
11177   LP64_ONLY(push(rsi);)
11178   push(rdx);
11179   push(rcx);
11180 #ifdef _LP64
11181   push(r8);
11182   push(r9);
11183   push(r10);
11184   push(r11);
11185 #endif
11186 
11187   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11188 
11189 #ifdef _LP64
11190   pop(r11);
11191   pop(r10);
11192   pop(r9);
11193   pop(r8);
11194 #endif
11195   pop(rcx);
11196   pop(rdx);
11197   LP64_ONLY(pop(rsi);)
11198   LP64_ONLY(pop(rdi);)
11199   if (thread != rax) {
11200     mov(thread, rax);
11201     pop(rax);
11202   }
11203 }
11204 
11205 #endif