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