1 /*
   2  * Copyright (c) 1997, 2025, 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 "asm/assembler.hpp"
  26 #include "asm/assembler.inline.hpp"
  27 #include "code/aotCodeCache.hpp"
  28 #include "code/compiledIC.hpp"
  29 #include "compiler/compiler_globals.hpp"
  30 #include "compiler/disassembler.hpp"
  31 #include "crc32c.h"
  32 #include "gc/shared/barrierSet.hpp"
  33 #include "gc/shared/barrierSetAssembler.hpp"
  34 #include "gc/shared/collectedHeap.inline.hpp"
  35 #include "gc/shared/tlab_globals.hpp"
  36 #include "interpreter/bytecodeHistogram.hpp"
  37 #include "interpreter/interpreter.hpp"
  38 #include "interpreter/interpreterRuntime.hpp"
  39 #include "jvm.h"
  40 #include "memory/resourceArea.hpp"
  41 #include "memory/universe.hpp"
  42 #include "oops/accessDecorators.hpp"
  43 #include "oops/compressedKlass.inline.hpp"
  44 #include "oops/compressedOops.inline.hpp"
  45 #include "oops/klass.inline.hpp"
  46 #include "prims/methodHandles.hpp"
  47 #include "runtime/continuation.hpp"
  48 #include "runtime/interfaceSupport.inline.hpp"
  49 #include "runtime/javaThread.hpp"
  50 #include "runtime/jniHandles.hpp"
  51 #include "runtime/objectMonitor.hpp"
  52 #include "runtime/os.hpp"
  53 #include "runtime/safepoint.hpp"
  54 #include "runtime/safepointMechanism.hpp"
  55 #include "runtime/sharedRuntime.hpp"
  56 #include "runtime/stubRoutines.hpp"
  57 #include "utilities/checkedCast.hpp"
  58 #include "utilities/macros.hpp"
  59 
  60 #ifdef PRODUCT
  61 #define BLOCK_COMMENT(str) /* nothing */
  62 #define STOP(error) stop(error)
  63 #else
  64 #define BLOCK_COMMENT(str) block_comment(str)
  65 #define STOP(error) block_comment(error); stop(error)
  66 #endif
  67 
  68 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  69 
  70 #ifdef ASSERT
  71 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  72 #endif
  73 
  74 static const Assembler::Condition reverse[] = {
  75     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  76     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  77     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  78     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  79     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  80     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  81     Assembler::above          /* belowEqual    = 0x6 */ ,
  82     Assembler::belowEqual     /* above         = 0x7 */ ,
  83     Assembler::positive       /* negative      = 0x8 */ ,
  84     Assembler::negative       /* positive      = 0x9 */ ,
  85     Assembler::noParity       /* parity        = 0xa */ ,
  86     Assembler::parity         /* noParity      = 0xb */ ,
  87     Assembler::greaterEqual   /* less          = 0xc */ ,
  88     Assembler::less           /* greaterEqual  = 0xd */ ,
  89     Assembler::greater        /* lessEqual     = 0xe */ ,
  90     Assembler::lessEqual      /* greater       = 0xf, */
  91 
  92 };
  93 
  94 
  95 // Implementation of MacroAssembler
  96 
  97 Address MacroAssembler::as_Address(AddressLiteral adr) {
  98   // amd64 always does this as a pc-rel
  99   // we can be absolute or disp based on the instruction type
 100   // jmp/call are displacements others are absolute
 101   assert(!adr.is_lval(), "must be rval");
 102   assert(reachable(adr), "must be");
 103   return Address(checked_cast<int32_t>(adr.target() - pc()), adr.target(), adr.reloc());
 104 
 105 }
 106 
 107 Address MacroAssembler::as_Address(ArrayAddress adr, Register rscratch) {
 108   AddressLiteral base = adr.base();
 109   lea(rscratch, base);
 110   Address index = adr.index();
 111   assert(index._disp == 0, "must not have disp"); // maybe it can?
 112   Address array(rscratch, index._index, index._scale, index._disp);
 113   return array;
 114 }
 115 
 116 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 117   Label L, E;
 118 
 119 #ifdef _WIN64
 120   // Windows always allocates space for it's register args
 121   assert(num_args <= 4, "only register arguments supported");
 122   subq(rsp,  frame::arg_reg_save_area_bytes);
 123 #endif
 124 
 125   // Align stack if necessary
 126   testl(rsp, 15);
 127   jcc(Assembler::zero, L);
 128 
 129   subq(rsp, 8);
 130   call(RuntimeAddress(entry_point));
 131   addq(rsp, 8);
 132   jmp(E);
 133 
 134   bind(L);
 135   call(RuntimeAddress(entry_point));
 136 
 137   bind(E);
 138 
 139 #ifdef _WIN64
 140   // restore stack pointer
 141   addq(rsp, frame::arg_reg_save_area_bytes);
 142 #endif
 143 }
 144 
 145 void MacroAssembler::cmp64(Register src1, AddressLiteral src2, Register rscratch) {
 146   assert(!src2.is_lval(), "should use cmpptr");
 147   assert(rscratch != noreg || always_reachable(src2), "missing");
 148 
 149   if (reachable(src2)) {
 150     cmpq(src1, as_Address(src2));
 151   } else {
 152     lea(rscratch, src2);
 153     Assembler::cmpq(src1, Address(rscratch, 0));
 154   }
 155 }
 156 
 157 int MacroAssembler::corrected_idivq(Register reg) {
 158   // Full implementation of Java ldiv and lrem; checks for special
 159   // case as described in JVM spec., p.243 & p.271.  The function
 160   // returns the (pc) offset of the idivl instruction - may be needed
 161   // for implicit exceptions.
 162   //
 163   //         normal case                           special case
 164   //
 165   // input : rax: dividend                         min_long
 166   //         reg: divisor   (may not be eax/edx)   -1
 167   //
 168   // output: rax: quotient  (= rax idiv reg)       min_long
 169   //         rdx: remainder (= rax irem reg)       0
 170   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 171   static const int64_t min_long = 0x8000000000000000;
 172   Label normal_case, special_case;
 173 
 174   // check for special case
 175   cmp64(rax, ExternalAddress((address) &min_long), rdx /*rscratch*/);
 176   jcc(Assembler::notEqual, normal_case);
 177   xorl(rdx, rdx); // prepare rdx for possible special case (where
 178                   // remainder = 0)
 179   cmpq(reg, -1);
 180   jcc(Assembler::equal, special_case);
 181 
 182   // handle normal case
 183   bind(normal_case);
 184   cdqq();
 185   int idivq_offset = offset();
 186   idivq(reg);
 187 
 188   // normal and special case exit
 189   bind(special_case);
 190 
 191   return idivq_offset;
 192 }
 193 
 194 void MacroAssembler::decrementq(Register reg, int value) {
 195   if (value == min_jint) { subq(reg, value); return; }
 196   if (value <  0) { incrementq(reg, -value); return; }
 197   if (value == 0) {                        ; return; }
 198   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 199   /* else */      { subq(reg, value)       ; return; }
 200 }
 201 
 202 void MacroAssembler::decrementq(Address dst, int value) {
 203   if (value == min_jint) { subq(dst, value); return; }
 204   if (value <  0) { incrementq(dst, -value); return; }
 205   if (value == 0) {                        ; return; }
 206   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 207   /* else */      { subq(dst, value)       ; return; }
 208 }
 209 
 210 void MacroAssembler::incrementq(AddressLiteral dst, Register rscratch) {
 211   assert(rscratch != noreg || always_reachable(dst), "missing");
 212 
 213   if (reachable(dst)) {
 214     incrementq(as_Address(dst));
 215   } else {
 216     lea(rscratch, dst);
 217     incrementq(Address(rscratch, 0));
 218   }
 219 }
 220 
 221 void MacroAssembler::incrementq(Register reg, int value) {
 222   if (value == min_jint) { addq(reg, value); return; }
 223   if (value <  0) { decrementq(reg, -value); return; }
 224   if (value == 0) {                        ; return; }
 225   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 226   /* else */      { addq(reg, value)       ; return; }
 227 }
 228 
 229 void MacroAssembler::incrementq(Address dst, int value) {
 230   if (value == min_jint) { addq(dst, value); return; }
 231   if (value <  0) { decrementq(dst, -value); return; }
 232   if (value == 0) {                        ; return; }
 233   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 234   /* else */      { addq(dst, value)       ; return; }
 235 }
 236 
 237 // 32bit can do a case table jump in one instruction but we no longer allow the base
 238 // to be installed in the Address class
 239 void MacroAssembler::jump(ArrayAddress entry, Register rscratch) {
 240   lea(rscratch, entry.base());
 241   Address dispatch = entry.index();
 242   assert(dispatch._base == noreg, "must be");
 243   dispatch._base = rscratch;
 244   jmp(dispatch);
 245 }
 246 
 247 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 248   ShouldNotReachHere(); // 64bit doesn't use two regs
 249   cmpq(x_lo, y_lo);
 250 }
 251 
 252 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 253   mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 254 }
 255 
 256 void MacroAssembler::lea(Address dst, AddressLiteral adr, Register rscratch) {
 257   lea(rscratch, adr);
 258   movptr(dst, rscratch);
 259 }
 260 
 261 void MacroAssembler::leave() {
 262   // %%% is this really better? Why not on 32bit too?
 263   emit_int8((unsigned char)0xC9); // LEAVE
 264 }
 265 
 266 void MacroAssembler::lneg(Register hi, Register lo) {
 267   ShouldNotReachHere(); // 64bit doesn't use two regs
 268   negq(lo);
 269 }
 270 
 271 void MacroAssembler::movoop(Register dst, jobject obj) {
 272   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 273 }
 274 
 275 void MacroAssembler::movoop(Address dst, jobject obj, Register rscratch) {
 276   mov_literal64(rscratch, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 277   movq(dst, rscratch);
 278 }
 279 
 280 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 281   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 282 }
 283 
 284 void MacroAssembler::mov_metadata(Address dst, Metadata* obj, Register rscratch) {
 285   mov_literal64(rscratch, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 286   movq(dst, rscratch);
 287 }
 288 
 289 void MacroAssembler::movptr(Register dst, AddressLiteral src) {
 290   if (src.is_lval()) {
 291     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 292   } else {
 293     if (reachable(src)) {
 294       movq(dst, as_Address(src));
 295     } else {
 296       lea(dst, src);
 297       movq(dst, Address(dst, 0));
 298     }
 299   }
 300 }
 301 
 302 void MacroAssembler::movptr(ArrayAddress dst, Register src, Register rscratch) {
 303   movq(as_Address(dst, rscratch), src);
 304 }
 305 
 306 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 307   movq(dst, as_Address(src, dst /*rscratch*/));
 308 }
 309 
 310 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 311 void MacroAssembler::movptr(Address dst, intptr_t src, Register rscratch) {
 312   if (is_simm32(src)) {
 313     movptr(dst, checked_cast<int32_t>(src));
 314   } else {
 315     mov64(rscratch, src);
 316     movq(dst, rscratch);
 317   }
 318 }
 319 
 320 void MacroAssembler::pushoop(jobject obj, Register rscratch) {
 321   movoop(rscratch, obj);
 322   push(rscratch);
 323 }
 324 
 325 void MacroAssembler::pushklass(Metadata* obj, Register rscratch) {
 326   mov_metadata(rscratch, obj);
 327   push(rscratch);
 328 }
 329 
 330 void MacroAssembler::pushptr(AddressLiteral src, Register rscratch) {
 331   lea(rscratch, src);
 332   if (src.is_lval()) {
 333     push(rscratch);
 334   } else {
 335     pushq(Address(rscratch, 0));
 336   }
 337 }
 338 
 339 static void pass_arg0(MacroAssembler* masm, Register arg) {
 340   if (c_rarg0 != arg ) {
 341     masm->mov(c_rarg0, arg);
 342   }
 343 }
 344 
 345 static void pass_arg1(MacroAssembler* masm, Register arg) {
 346   if (c_rarg1 != arg ) {
 347     masm->mov(c_rarg1, arg);
 348   }
 349 }
 350 
 351 static void pass_arg2(MacroAssembler* masm, Register arg) {
 352   if (c_rarg2 != arg ) {
 353     masm->mov(c_rarg2, arg);
 354   }
 355 }
 356 
 357 static void pass_arg3(MacroAssembler* masm, Register arg) {
 358   if (c_rarg3 != arg ) {
 359     masm->mov(c_rarg3, arg);
 360   }
 361 }
 362 
 363 void MacroAssembler::stop(const char* msg) {
 364   if (ShowMessageBoxOnError) {
 365     address rip = pc();
 366     pusha(); // get regs on stack
 367     lea(c_rarg1, InternalAddress(rip));
 368     movq(c_rarg2, rsp); // pass pointer to regs array
 369   }
 370   // Skip AOT caching C strings in scratch buffer.
 371   const char* str = (code_section()->scratch_emit()) ? msg : AOTCodeCache::add_C_string(msg);
 372   lea(c_rarg0, ExternalAddress((address) str));
 373   andq(rsp, -16); // align stack as required by ABI
 374   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 375   hlt();
 376 }
 377 
 378 void MacroAssembler::warn(const char* msg) {
 379   push(rbp);
 380   movq(rbp, rsp);
 381   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 382   push_CPU_state();   // keeps alignment at 16 bytes
 383 
 384 #ifdef _WIN64
 385   // Windows always allocates space for its register args
 386   subq(rsp,  frame::arg_reg_save_area_bytes);
 387 #endif
 388   lea(c_rarg0, ExternalAddress((address) msg));
 389   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 390 
 391 #ifdef _WIN64
 392   // restore stack pointer
 393   addq(rsp, frame::arg_reg_save_area_bytes);
 394 #endif
 395   pop_CPU_state();
 396   mov(rsp, rbp);
 397   pop(rbp);
 398 }
 399 
 400 void MacroAssembler::print_state() {
 401   address rip = pc();
 402   pusha();            // get regs on stack
 403   push(rbp);
 404   movq(rbp, rsp);
 405   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 406   push_CPU_state();   // keeps alignment at 16 bytes
 407 
 408   lea(c_rarg0, InternalAddress(rip));
 409   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 410   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 411 
 412   pop_CPU_state();
 413   mov(rsp, rbp);
 414   pop(rbp);
 415   popa();
 416 }
 417 
 418 #ifndef PRODUCT
 419 extern "C" void findpc(intptr_t x);
 420 #endif
 421 
 422 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 423   // In order to get locks to work, we need to fake a in_VM state
 424   if (ShowMessageBoxOnError) {
 425     JavaThread* thread = JavaThread::current();
 426     JavaThreadState saved_state = thread->thread_state();
 427     thread->set_thread_state(_thread_in_vm);
 428 #ifndef PRODUCT
 429     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 430       ttyLocker ttyl;
 431       BytecodeCounter::print();
 432     }
 433 #endif
 434     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 435     // XXX correct this offset for amd64
 436     // This is the value of eip which points to where verify_oop will return.
 437     if (os::message_box(msg, "Execution stopped, print registers?")) {
 438       print_state64(pc, regs);
 439       BREAKPOINT;
 440     }
 441   }
 442   fatal("DEBUG MESSAGE: %s", msg);
 443 }
 444 
 445 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 446   ttyLocker ttyl;
 447   DebuggingContext debugging{};
 448   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 449 #ifndef PRODUCT
 450   tty->cr();
 451   findpc(pc);
 452   tty->cr();
 453 #endif
 454 #define PRINT_REG(rax, value) \
 455   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 456   PRINT_REG(rax, regs[15]);
 457   PRINT_REG(rbx, regs[12]);
 458   PRINT_REG(rcx, regs[14]);
 459   PRINT_REG(rdx, regs[13]);
 460   PRINT_REG(rdi, regs[8]);
 461   PRINT_REG(rsi, regs[9]);
 462   PRINT_REG(rbp, regs[10]);
 463   // rsp is actually not stored by pusha(), compute the old rsp from regs (rsp after pusha): regs + 16 = old rsp
 464   PRINT_REG(rsp, (intptr_t)(&regs[16]));
 465   PRINT_REG(r8 , regs[7]);
 466   PRINT_REG(r9 , regs[6]);
 467   PRINT_REG(r10, regs[5]);
 468   PRINT_REG(r11, regs[4]);
 469   PRINT_REG(r12, regs[3]);
 470   PRINT_REG(r13, regs[2]);
 471   PRINT_REG(r14, regs[1]);
 472   PRINT_REG(r15, regs[0]);
 473 #undef PRINT_REG
 474   // Print some words near the top of the stack.
 475   int64_t* rsp = &regs[16];
 476   int64_t* dump_sp = rsp;
 477   for (int col1 = 0; col1 < 8; col1++) {
 478     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 479     os::print_location(tty, *dump_sp++);
 480   }
 481   for (int row = 0; row < 25; row++) {
 482     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 483     for (int col = 0; col < 4; col++) {
 484       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 485     }
 486     tty->cr();
 487   }
 488   // Print some instructions around pc:
 489   Disassembler::decode((address)pc-64, (address)pc);
 490   tty->print_cr("--------");
 491   Disassembler::decode((address)pc, (address)pc+32);
 492 }
 493 
 494 // The java_calling_convention describes stack locations as ideal slots on
 495 // a frame with no abi restrictions. Since we must observe abi restrictions
 496 // (like the placement of the register window) the slots must be biased by
 497 // the following value.
 498 static int reg2offset_in(VMReg r) {
 499   // Account for saved rbp and return address
 500   // This should really be in_preserve_stack_slots
 501   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
 502 }
 503 
 504 static int reg2offset_out(VMReg r) {
 505   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 506 }
 507 
 508 // A long move
 509 void MacroAssembler::long_move(VMRegPair src, VMRegPair dst, Register tmp, int in_stk_bias, int out_stk_bias) {
 510 
 511   // The calling conventions assures us that each VMregpair is either
 512   // all really one physical register or adjacent stack slots.
 513 
 514   if (src.is_single_phys_reg() ) {
 515     if (dst.is_single_phys_reg()) {
 516       if (dst.first() != src.first()) {
 517         mov(dst.first()->as_Register(), src.first()->as_Register());
 518       }
 519     } else {
 520       assert(dst.is_single_reg(), "not a stack pair: (%s, %s), (%s, %s)",
 521              src.first()->name(), src.second()->name(), dst.first()->name(), dst.second()->name());
 522       movq(Address(rsp, reg2offset_out(dst.first()) + out_stk_bias), src.first()->as_Register());
 523     }
 524   } else if (dst.is_single_phys_reg()) {
 525     assert(src.is_single_reg(),  "not a stack pair");
 526     movq(dst.first()->as_Register(), Address(rbp, reg2offset_in(src.first()) + in_stk_bias));
 527   } else {
 528     assert(src.is_single_reg() && dst.is_single_reg(), "not stack pairs");
 529     movq(tmp, Address(rbp, reg2offset_in(src.first()) + in_stk_bias));
 530     movq(Address(rsp, reg2offset_out(dst.first()) + out_stk_bias), tmp);
 531   }
 532 }
 533 
 534 // A double move
 535 void MacroAssembler::double_move(VMRegPair src, VMRegPair dst, Register tmp, int in_stk_bias, int out_stk_bias) {
 536 
 537   // The calling conventions assures us that each VMregpair is either
 538   // all really one physical register or adjacent stack slots.
 539 
 540   if (src.is_single_phys_reg() ) {
 541     if (dst.is_single_phys_reg()) {
 542       // In theory these overlap but the ordering is such that this is likely a nop
 543       if ( src.first() != dst.first()) {
 544         movdbl(dst.first()->as_XMMRegister(), src.first()->as_XMMRegister());
 545       }
 546     } else {
 547       assert(dst.is_single_reg(), "not a stack pair");
 548       movdbl(Address(rsp, reg2offset_out(dst.first()) + out_stk_bias), src.first()->as_XMMRegister());
 549     }
 550   } else if (dst.is_single_phys_reg()) {
 551     assert(src.is_single_reg(),  "not a stack pair");
 552     movdbl(dst.first()->as_XMMRegister(), Address(rbp, reg2offset_in(src.first()) + in_stk_bias));
 553   } else {
 554     assert(src.is_single_reg() && dst.is_single_reg(), "not stack pairs");
 555     movq(tmp, Address(rbp, reg2offset_in(src.first()) + in_stk_bias));
 556     movq(Address(rsp, reg2offset_out(dst.first()) + out_stk_bias), tmp);
 557   }
 558 }
 559 
 560 
 561 // A float arg may have to do float reg int reg conversion
 562 void MacroAssembler::float_move(VMRegPair src, VMRegPair dst, Register tmp, int in_stk_bias, int out_stk_bias) {
 563   assert(!src.second()->is_valid() && !dst.second()->is_valid(), "bad float_move");
 564 
 565   // The calling conventions assures us that each VMregpair is either
 566   // all really one physical register or adjacent stack slots.
 567 
 568   if (src.first()->is_stack()) {
 569     if (dst.first()->is_stack()) {
 570       movl(tmp, Address(rbp, reg2offset_in(src.first()) + in_stk_bias));
 571       movptr(Address(rsp, reg2offset_out(dst.first()) + out_stk_bias), tmp);
 572     } else {
 573       // stack to reg
 574       assert(dst.first()->is_XMMRegister(), "only expect xmm registers as parameters");
 575       movflt(dst.first()->as_XMMRegister(), Address(rbp, reg2offset_in(src.first()) + in_stk_bias));
 576     }
 577   } else if (dst.first()->is_stack()) {
 578     // reg to stack
 579     assert(src.first()->is_XMMRegister(), "only expect xmm registers as parameters");
 580     movflt(Address(rsp, reg2offset_out(dst.first()) + out_stk_bias), src.first()->as_XMMRegister());
 581   } else {
 582     // reg to reg
 583     // In theory these overlap but the ordering is such that this is likely a nop
 584     if ( src.first() != dst.first()) {
 585       movdbl(dst.first()->as_XMMRegister(),  src.first()->as_XMMRegister());
 586     }
 587   }
 588 }
 589 
 590 // On 64 bit we will store integer like items to the stack as
 591 // 64 bits items (x86_32/64 abi) even though java would only store
 592 // 32bits for a parameter. On 32bit it will simply be 32 bits
 593 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
 594 void MacroAssembler::move32_64(VMRegPair src, VMRegPair dst, Register tmp, int in_stk_bias, int out_stk_bias) {
 595   if (src.first()->is_stack()) {
 596     if (dst.first()->is_stack()) {
 597       // stack to stack
 598       movslq(tmp, Address(rbp, reg2offset_in(src.first()) + in_stk_bias));
 599       movq(Address(rsp, reg2offset_out(dst.first()) + out_stk_bias), tmp);
 600     } else {
 601       // stack to reg
 602       movslq(dst.first()->as_Register(), Address(rbp, reg2offset_in(src.first()) + in_stk_bias));
 603     }
 604   } else if (dst.first()->is_stack()) {
 605     // reg to stack
 606     // Do we really have to sign extend???
 607     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
 608     movq(Address(rsp, reg2offset_out(dst.first()) + out_stk_bias), src.first()->as_Register());
 609   } else {
 610     // Do we really have to sign extend???
 611     // __ movslq(dst.first()->as_Register(), src.first()->as_Register());
 612     if (dst.first() != src.first()) {
 613       movq(dst.first()->as_Register(), src.first()->as_Register());
 614     }
 615   }
 616 }
 617 
 618 void MacroAssembler::move_ptr(VMRegPair src, VMRegPair dst) {
 619   if (src.first()->is_stack()) {
 620     if (dst.first()->is_stack()) {
 621       // stack to stack
 622       movq(rax, Address(rbp, reg2offset_in(src.first())));
 623       movq(Address(rsp, reg2offset_out(dst.first())), rax);
 624     } else {
 625       // stack to reg
 626       movq(dst.first()->as_Register(), Address(rbp, reg2offset_in(src.first())));
 627     }
 628   } else if (dst.first()->is_stack()) {
 629     // reg to stack
 630     movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
 631   } else {
 632     if (dst.first() != src.first()) {
 633       movq(dst.first()->as_Register(), src.first()->as_Register());
 634     }
 635   }
 636 }
 637 
 638 // An oop arg. Must pass a handle not the oop itself
 639 void MacroAssembler::object_move(OopMap* map,
 640                         int oop_handle_offset,
 641                         int framesize_in_slots,
 642                         VMRegPair src,
 643                         VMRegPair dst,
 644                         bool is_receiver,
 645                         int* receiver_offset) {
 646 
 647   // must pass a handle. First figure out the location we use as a handle
 648 
 649   Register rHandle = dst.first()->is_stack() ? rax : dst.first()->as_Register();
 650 
 651   // See if oop is null if it is we need no handle
 652 
 653   if (src.first()->is_stack()) {
 654 
 655     // Oop is already on the stack as an argument
 656     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
 657     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
 658     if (is_receiver) {
 659       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
 660     }
 661 
 662     cmpptr(Address(rbp, reg2offset_in(src.first())), NULL_WORD);
 663     lea(rHandle, Address(rbp, reg2offset_in(src.first())));
 664     // conditionally move a null
 665     cmovptr(Assembler::equal, rHandle, Address(rbp, reg2offset_in(src.first())));
 666   } else {
 667 
 668     // Oop is in a register we must store it to the space we reserve
 669     // on the stack for oop_handles and pass a handle if oop is non-null
 670 
 671     const Register rOop = src.first()->as_Register();
 672     int oop_slot;
 673     if (rOop == j_rarg0)
 674       oop_slot = 0;
 675     else if (rOop == j_rarg1)
 676       oop_slot = 1;
 677     else if (rOop == j_rarg2)
 678       oop_slot = 2;
 679     else if (rOop == j_rarg3)
 680       oop_slot = 3;
 681     else if (rOop == j_rarg4)
 682       oop_slot = 4;
 683     else {
 684       assert(rOop == j_rarg5, "wrong register");
 685       oop_slot = 5;
 686     }
 687 
 688     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
 689     int offset = oop_slot*VMRegImpl::stack_slot_size;
 690 
 691     map->set_oop(VMRegImpl::stack2reg(oop_slot));
 692     // Store oop in handle area, may be null
 693     movptr(Address(rsp, offset), rOop);
 694     if (is_receiver) {
 695       *receiver_offset = offset;
 696     }
 697 
 698     cmpptr(rOop, NULL_WORD);
 699     lea(rHandle, Address(rsp, offset));
 700     // conditionally move a null from the handle area where it was just stored
 701     cmovptr(Assembler::equal, rHandle, Address(rsp, offset));
 702   }
 703 
 704   // If arg is on the stack then place it otherwise it is already in correct reg.
 705   if (dst.first()->is_stack()) {
 706     movptr(Address(rsp, reg2offset_out(dst.first())), rHandle);
 707   }
 708 }
 709 
 710 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 711   addq(dst, imm32);
 712 }
 713 
 714 void MacroAssembler::addptr(Register dst, Register src) {
 715   addq(dst, src);
 716 }
 717 
 718 void MacroAssembler::addptr(Address dst, Register src) {
 719   addq(dst, src);
 720 }
 721 
 722 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src, Register rscratch) {
 723   assert(rscratch != noreg || always_reachable(src), "missing");
 724 
 725   if (reachable(src)) {
 726     Assembler::addsd(dst, as_Address(src));
 727   } else {
 728     lea(rscratch, src);
 729     Assembler::addsd(dst, Address(rscratch, 0));
 730   }
 731 }
 732 
 733 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src, Register rscratch) {
 734   assert(rscratch != noreg || always_reachable(src), "missing");
 735 
 736   if (reachable(src)) {
 737     addss(dst, as_Address(src));
 738   } else {
 739     lea(rscratch, src);
 740     addss(dst, Address(rscratch, 0));
 741   }
 742 }
 743 
 744 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src, Register rscratch) {
 745   assert(rscratch != noreg || always_reachable(src), "missing");
 746 
 747   if (reachable(src)) {
 748     Assembler::addpd(dst, as_Address(src));
 749   } else {
 750     lea(rscratch, src);
 751     Assembler::addpd(dst, Address(rscratch, 0));
 752   }
 753 }
 754 
 755 // See 8273459.  Function for ensuring 64-byte alignment, intended for stubs only.
 756 // Stub code is generated once and never copied.
 757 // NMethods can't use this because they get copied and we can't force alignment > 32 bytes.
 758 void MacroAssembler::align64() {
 759   align(64, (uint)(uintptr_t)pc());
 760 }
 761 
 762 void MacroAssembler::align32() {
 763   align(32, (uint)(uintptr_t)pc());
 764 }
 765 
 766 void MacroAssembler::align(uint modulus) {
 767   // 8273459: Ensure alignment is possible with current segment alignment
 768   assert(modulus <= (uintx)CodeEntryAlignment, "Alignment must be <= CodeEntryAlignment");
 769   align(modulus, offset());
 770 }
 771 
 772 void MacroAssembler::align(uint modulus, uint target) {
 773   if (target % modulus != 0) {
 774     nop(modulus - (target % modulus));
 775   }
 776 }
 777 
 778 void MacroAssembler::push_f(XMMRegister r) {
 779   subptr(rsp, wordSize);
 780   movflt(Address(rsp, 0), r);
 781 }
 782 
 783 void MacroAssembler::pop_f(XMMRegister r) {
 784   movflt(r, Address(rsp, 0));
 785   addptr(rsp, wordSize);
 786 }
 787 
 788 void MacroAssembler::push_d(XMMRegister r) {
 789   subptr(rsp, 2 * wordSize);
 790   movdbl(Address(rsp, 0), r);
 791 }
 792 
 793 void MacroAssembler::pop_d(XMMRegister r) {
 794   movdbl(r, Address(rsp, 0));
 795   addptr(rsp, 2 * Interpreter::stackElementSize);
 796 }
 797 
 798 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src, Register rscratch) {
 799   // Used in sign-masking with aligned address.
 800   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 801   assert(rscratch != noreg || always_reachable(src), "missing");
 802 
 803   if (UseAVX > 2 &&
 804       (!VM_Version::supports_avx512dq() || !VM_Version::supports_avx512vl()) &&
 805       (dst->encoding() >= 16)) {
 806     vpand(dst, dst, src, AVX_512bit, rscratch);
 807   } else if (reachable(src)) {
 808     Assembler::andpd(dst, as_Address(src));
 809   } else {
 810     lea(rscratch, src);
 811     Assembler::andpd(dst, Address(rscratch, 0));
 812   }
 813 }
 814 
 815 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src, Register rscratch) {
 816   // Used in sign-masking with aligned address.
 817   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 818   assert(rscratch != noreg || always_reachable(src), "missing");
 819 
 820   if (reachable(src)) {
 821     Assembler::andps(dst, as_Address(src));
 822   } else {
 823     lea(rscratch, src);
 824     Assembler::andps(dst, Address(rscratch, 0));
 825   }
 826 }
 827 
 828 void MacroAssembler::andptr(Register dst, int32_t imm32) {
 829   andq(dst, imm32);
 830 }
 831 
 832 void MacroAssembler::andq(Register dst, AddressLiteral src, Register rscratch) {
 833   assert(rscratch != noreg || always_reachable(src), "missing");
 834 
 835   if (reachable(src)) {
 836     andq(dst, as_Address(src));
 837   } else {
 838     lea(rscratch, src);
 839     andq(dst, Address(rscratch, 0));
 840   }
 841 }
 842 
 843 void MacroAssembler::atomic_incl(Address counter_addr) {
 844   lock();
 845   incrementl(counter_addr);
 846 }
 847 
 848 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register rscratch) {
 849   assert(rscratch != noreg || always_reachable(counter_addr), "missing");
 850 
 851   if (reachable(counter_addr)) {
 852     atomic_incl(as_Address(counter_addr));
 853   } else {
 854     lea(rscratch, counter_addr);
 855     atomic_incl(Address(rscratch, 0));
 856   }
 857 }
 858 
 859 void MacroAssembler::atomic_incq(Address counter_addr) {
 860   lock();
 861   incrementq(counter_addr);
 862 }
 863 
 864 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register rscratch) {
 865   assert(rscratch != noreg || always_reachable(counter_addr), "missing");
 866 
 867   if (reachable(counter_addr)) {
 868     atomic_incq(as_Address(counter_addr));
 869   } else {
 870     lea(rscratch, counter_addr);
 871     atomic_incq(Address(rscratch, 0));
 872   }
 873 }
 874 
 875 // Writes to stack successive pages until offset reached to check for
 876 // stack overflow + shadow pages.  This clobbers tmp.
 877 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
 878   movptr(tmp, rsp);
 879   // Bang stack for total size given plus shadow page size.
 880   // Bang one page at a time because large size can bang beyond yellow and
 881   // red zones.
 882   Label loop;
 883   bind(loop);
 884   movl(Address(tmp, (-(int)os::vm_page_size())), size );
 885   subptr(tmp, (int)os::vm_page_size());
 886   subl(size, (int)os::vm_page_size());
 887   jcc(Assembler::greater, loop);
 888 
 889   // Bang down shadow pages too.
 890   // At this point, (tmp-0) is the last address touched, so don't
 891   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
 892   // was post-decremented.)  Skip this address by starting at i=1, and
 893   // touch a few more pages below.  N.B.  It is important to touch all
 894   // the way down including all pages in the shadow zone.
 895   for (int i = 1; i < ((int)StackOverflow::stack_shadow_zone_size() / (int)os::vm_page_size()); i++) {
 896     // this could be any sized move but this is can be a debugging crumb
 897     // so the bigger the better.
 898     movptr(Address(tmp, (-i*(int)os::vm_page_size())), size );
 899   }
 900 }
 901 
 902 void MacroAssembler::reserved_stack_check() {
 903   // testing if reserved zone needs to be enabled
 904   Label no_reserved_zone_enabling;
 905 
 906   cmpptr(rsp, Address(r15_thread, JavaThread::reserved_stack_activation_offset()));
 907   jcc(Assembler::below, no_reserved_zone_enabling);
 908 
 909   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), r15_thread);
 910   jump(RuntimeAddress(SharedRuntime::throw_delayed_StackOverflowError_entry()));
 911   should_not_reach_here();
 912 
 913   bind(no_reserved_zone_enabling);
 914 }
 915 
 916 void MacroAssembler::c2bool(Register x) {
 917   // implements x == 0 ? 0 : 1
 918   // note: must only look at least-significant byte of x
 919   //       since C-style booleans are stored in one byte
 920   //       only! (was bug)
 921   andl(x, 0xFF);
 922   setb(Assembler::notZero, x);
 923 }
 924 
 925 // Wouldn't need if AddressLiteral version had new name
 926 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
 927   Assembler::call(L, rtype);
 928 }
 929 
 930 void MacroAssembler::call(Register entry) {
 931   Assembler::call(entry);
 932 }
 933 
 934 void MacroAssembler::call(AddressLiteral entry, Register rscratch) {
 935   assert(rscratch != noreg || always_reachable(entry), "missing");
 936 
 937   if (reachable(entry)) {
 938     Assembler::call_literal(entry.target(), entry.rspec());
 939   } else {
 940     lea(rscratch, entry);
 941     Assembler::call(rscratch);
 942   }
 943 }
 944 
 945 void MacroAssembler::ic_call(address entry, jint method_index) {
 946   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
 947   // Needs full 64-bit immediate for later patching.
 948   mov64(rax, (int64_t)Universe::non_oop_word());
 949   call(AddressLiteral(entry, rh));
 950 }
 951 
 952 int MacroAssembler::ic_check_size() {
 953   return UseCompactObjectHeaders ? 17 : 14;
 954 }
 955 
 956 int MacroAssembler::ic_check(int end_alignment) {
 957   Register receiver = j_rarg0;
 958   Register data = rax;
 959   Register temp = rscratch1;
 960 
 961   // The UEP of a code blob ensures that the VEP is padded. However, the padding of the UEP is placed
 962   // before the inline cache check, so we don't have to execute any nop instructions when dispatching
 963   // through the UEP, yet we can ensure that the VEP is aligned appropriately. That's why we align
 964   // before the inline cache check here, and not after
 965   align(end_alignment, offset() + ic_check_size());
 966 
 967   int uep_offset = offset();
 968 
 969   if (UseCompactObjectHeaders) {
 970     load_narrow_klass_compact(temp, receiver);
 971     cmpl(temp, Address(data, CompiledICData::speculated_klass_offset()));
 972   } else if (UseCompressedClassPointers) {
 973     movl(temp, Address(receiver, oopDesc::klass_offset_in_bytes()));
 974     cmpl(temp, Address(data, CompiledICData::speculated_klass_offset()));
 975   } else {
 976     movptr(temp, Address(receiver, oopDesc::klass_offset_in_bytes()));
 977     cmpptr(temp, Address(data, CompiledICData::speculated_klass_offset()));
 978   }
 979 
 980   // if inline cache check fails, then jump to runtime routine
 981   jump_cc(Assembler::notEqual, RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 982   assert((offset() % end_alignment) == 0, "Misaligned verified entry point (%d, %d, %d)", uep_offset, offset(), end_alignment);
 983 
 984   return uep_offset;
 985 }
 986 
 987 void MacroAssembler::emit_static_call_stub() {
 988   // Static stub relocation also tags the Method* in the code-stream.
 989   mov_metadata(rbx, (Metadata*) nullptr);  // Method is zapped till fixup time.
 990   // This is recognized as unresolved by relocs/nativeinst/ic code.
 991   jump(RuntimeAddress(pc()));
 992 }
 993 
 994 // Implementation of call_VM versions
 995 
 996 void MacroAssembler::call_VM(Register oop_result,
 997                              address entry_point,
 998                              bool check_exceptions) {
 999   Label C, E;
1000   call(C, relocInfo::none);
1001   jmp(E);
1002 
1003   bind(C);
1004   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
1005   ret(0);
1006 
1007   bind(E);
1008 }
1009 
1010 void MacroAssembler::call_VM(Register oop_result,
1011                              address entry_point,
1012                              Register arg_1,
1013                              bool check_exceptions) {
1014   Label C, E;
1015   call(C, relocInfo::none);
1016   jmp(E);
1017 
1018   bind(C);
1019   pass_arg1(this, arg_1);
1020   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
1021   ret(0);
1022 
1023   bind(E);
1024 }
1025 
1026 void MacroAssembler::call_VM(Register oop_result,
1027                              address entry_point,
1028                              Register arg_1,
1029                              Register arg_2,
1030                              bool check_exceptions) {
1031   Label C, E;
1032   call(C, relocInfo::none);
1033   jmp(E);
1034 
1035   bind(C);
1036 
1037   assert_different_registers(arg_1, c_rarg2);
1038 
1039   pass_arg2(this, arg_2);
1040   pass_arg1(this, arg_1);
1041   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
1042   ret(0);
1043 
1044   bind(E);
1045 }
1046 
1047 void MacroAssembler::call_VM(Register oop_result,
1048                              address entry_point,
1049                              Register arg_1,
1050                              Register arg_2,
1051                              Register arg_3,
1052                              bool check_exceptions) {
1053   Label C, E;
1054   call(C, relocInfo::none);
1055   jmp(E);
1056 
1057   bind(C);
1058 
1059   assert_different_registers(arg_1, c_rarg2, c_rarg3);
1060   assert_different_registers(arg_2, c_rarg3);
1061   pass_arg3(this, arg_3);
1062   pass_arg2(this, arg_2);
1063   pass_arg1(this, arg_1);
1064   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
1065   ret(0);
1066 
1067   bind(E);
1068 }
1069 
1070 void MacroAssembler::call_VM(Register oop_result,
1071                              Register last_java_sp,
1072                              address entry_point,
1073                              int number_of_arguments,
1074                              bool check_exceptions) {
1075   call_VM_base(oop_result, last_java_sp, entry_point, number_of_arguments, check_exceptions);
1076 }
1077 
1078 void MacroAssembler::call_VM(Register oop_result,
1079                              Register last_java_sp,
1080                              address entry_point,
1081                              Register arg_1,
1082                              bool check_exceptions) {
1083   pass_arg1(this, arg_1);
1084   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
1085 }
1086 
1087 void MacroAssembler::call_VM(Register oop_result,
1088                              Register last_java_sp,
1089                              address entry_point,
1090                              Register arg_1,
1091                              Register arg_2,
1092                              bool check_exceptions) {
1093 
1094   assert_different_registers(arg_1, c_rarg2);
1095   pass_arg2(this, arg_2);
1096   pass_arg1(this, arg_1);
1097   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
1098 }
1099 
1100 void MacroAssembler::call_VM(Register oop_result,
1101                              Register last_java_sp,
1102                              address entry_point,
1103                              Register arg_1,
1104                              Register arg_2,
1105                              Register arg_3,
1106                              bool check_exceptions) {
1107   assert_different_registers(arg_1, c_rarg2, c_rarg3);
1108   assert_different_registers(arg_2, c_rarg3);
1109   pass_arg3(this, arg_3);
1110   pass_arg2(this, arg_2);
1111   pass_arg1(this, arg_1);
1112   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
1113 }
1114 
1115 void MacroAssembler::super_call_VM(Register oop_result,
1116                                    Register last_java_sp,
1117                                    address entry_point,
1118                                    int number_of_arguments,
1119                                    bool check_exceptions) {
1120   MacroAssembler::call_VM_base(oop_result, last_java_sp, entry_point, number_of_arguments, check_exceptions);
1121 }
1122 
1123 void MacroAssembler::super_call_VM(Register oop_result,
1124                                    Register last_java_sp,
1125                                    address entry_point,
1126                                    Register arg_1,
1127                                    bool check_exceptions) {
1128   pass_arg1(this, arg_1);
1129   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
1130 }
1131 
1132 void MacroAssembler::super_call_VM(Register oop_result,
1133                                    Register last_java_sp,
1134                                    address entry_point,
1135                                    Register arg_1,
1136                                    Register arg_2,
1137                                    bool check_exceptions) {
1138 
1139   assert_different_registers(arg_1, c_rarg2);
1140   pass_arg2(this, arg_2);
1141   pass_arg1(this, arg_1);
1142   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
1143 }
1144 
1145 void MacroAssembler::super_call_VM(Register oop_result,
1146                                    Register last_java_sp,
1147                                    address entry_point,
1148                                    Register arg_1,
1149                                    Register arg_2,
1150                                    Register arg_3,
1151                                    bool check_exceptions) {
1152   assert_different_registers(arg_1, c_rarg2, c_rarg3);
1153   assert_different_registers(arg_2, c_rarg3);
1154   pass_arg3(this, arg_3);
1155   pass_arg2(this, arg_2);
1156   pass_arg1(this, arg_1);
1157   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
1158 }
1159 
1160 void MacroAssembler::call_VM_base(Register oop_result,
1161                                   Register last_java_sp,
1162                                   address  entry_point,
1163                                   int      number_of_arguments,
1164                                   bool     check_exceptions) {
1165   Register java_thread = r15_thread;
1166 
1167   // determine last_java_sp register
1168   if (!last_java_sp->is_valid()) {
1169     last_java_sp = rsp;
1170   }
1171   // debugging support
1172   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
1173 #ifdef ASSERT
1174   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
1175   // r12 is the heapbase.
1176   if (UseCompressedOops && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");
1177 #endif // ASSERT
1178 
1179   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
1180   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
1181 
1182   // push java thread (becomes first argument of C function)
1183 
1184   mov(c_rarg0, r15_thread);
1185 
1186   // set last Java frame before call
1187   assert(last_java_sp != rbp, "can't use ebp/rbp");
1188 
1189   // Only interpreter should have to set fp
1190   set_last_Java_frame(last_java_sp, rbp, nullptr, rscratch1);
1191 
1192   // do the call, remove parameters
1193   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
1194 
1195 #ifdef ASSERT
1196   // Check that thread register is not clobbered.
1197   guarantee(java_thread != rax, "change this code");
1198   push(rax);
1199   { Label L;
1200     get_thread_slow(rax);
1201     cmpptr(java_thread, rax);
1202     jcc(Assembler::equal, L);
1203     STOP("MacroAssembler::call_VM_base: java_thread not callee saved?");
1204     bind(L);
1205   }
1206   pop(rax);
1207 #endif
1208 
1209   // reset last Java frame
1210   // Only interpreter should have to clear fp
1211   reset_last_Java_frame(true);
1212 
1213    // C++ interp handles this in the interpreter
1214   check_and_handle_popframe();
1215   check_and_handle_earlyret();
1216 
1217   if (check_exceptions) {
1218     // check for pending exceptions (java_thread is set upon return)
1219     cmpptr(Address(r15_thread, Thread::pending_exception_offset()), NULL_WORD);
1220     // This used to conditionally jump to forward_exception however it is
1221     // possible if we relocate that the branch will not reach. So we must jump
1222     // around so we can always reach
1223 
1224     Label ok;
1225     jcc(Assembler::equal, ok);
1226     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
1227     bind(ok);
1228   }
1229 
1230   // get oop result if there is one and reset the value in the thread
1231   if (oop_result->is_valid()) {
1232     get_vm_result_oop(oop_result);
1233   }
1234 }
1235 
1236 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
1237   // Calculate the value for last_Java_sp somewhat subtle.
1238   // call_VM does an intermediate call which places a return address on
1239   // the stack just under the stack pointer as the user finished with it.
1240   // This allows use to retrieve last_Java_pc from last_Java_sp[-1].
1241 
1242   // We've pushed one address, correct last_Java_sp
1243   lea(rax, Address(rsp, wordSize));
1244 
1245   call_VM_base(oop_result, rax, entry_point, number_of_arguments, check_exceptions);
1246 }
1247 
1248 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
1249 void MacroAssembler::call_VM_leaf0(address entry_point) {
1250   MacroAssembler::call_VM_leaf_base(entry_point, 0);
1251 }
1252 
1253 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
1254   call_VM_leaf_base(entry_point, number_of_arguments);
1255 }
1256 
1257 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
1258   pass_arg0(this, arg_0);
1259   call_VM_leaf(entry_point, 1);
1260 }
1261 
1262 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1263 
1264   assert_different_registers(arg_0, c_rarg1);
1265   pass_arg1(this, arg_1);
1266   pass_arg0(this, arg_0);
1267   call_VM_leaf(entry_point, 2);
1268 }
1269 
1270 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
1271   assert_different_registers(arg_0, c_rarg1, c_rarg2);
1272   assert_different_registers(arg_1, c_rarg2);
1273   pass_arg2(this, arg_2);
1274   pass_arg1(this, arg_1);
1275   pass_arg0(this, arg_0);
1276   call_VM_leaf(entry_point, 3);
1277 }
1278 
1279 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
1280   assert_different_registers(arg_0, c_rarg1, c_rarg2, c_rarg3);
1281   assert_different_registers(arg_1, c_rarg2, c_rarg3);
1282   assert_different_registers(arg_2, c_rarg3);
1283   pass_arg3(this, arg_3);
1284   pass_arg2(this, arg_2);
1285   pass_arg1(this, arg_1);
1286   pass_arg0(this, arg_0);
1287   call_VM_leaf(entry_point, 3);
1288 }
1289 
1290 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
1291   pass_arg0(this, arg_0);
1292   MacroAssembler::call_VM_leaf_base(entry_point, 1);
1293 }
1294 
1295 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1296   assert_different_registers(arg_0, c_rarg1);
1297   pass_arg1(this, arg_1);
1298   pass_arg0(this, arg_0);
1299   MacroAssembler::call_VM_leaf_base(entry_point, 2);
1300 }
1301 
1302 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
1303   assert_different_registers(arg_0, c_rarg1, c_rarg2);
1304   assert_different_registers(arg_1, c_rarg2);
1305   pass_arg2(this, arg_2);
1306   pass_arg1(this, arg_1);
1307   pass_arg0(this, arg_0);
1308   MacroAssembler::call_VM_leaf_base(entry_point, 3);
1309 }
1310 
1311 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
1312   assert_different_registers(arg_0, c_rarg1, c_rarg2, c_rarg3);
1313   assert_different_registers(arg_1, c_rarg2, c_rarg3);
1314   assert_different_registers(arg_2, c_rarg3);
1315   pass_arg3(this, arg_3);
1316   pass_arg2(this, arg_2);
1317   pass_arg1(this, arg_1);
1318   pass_arg0(this, arg_0);
1319   MacroAssembler::call_VM_leaf_base(entry_point, 4);
1320 }
1321 
1322 void MacroAssembler::get_vm_result_oop(Register oop_result) {
1323   movptr(oop_result, Address(r15_thread, JavaThread::vm_result_oop_offset()));
1324   movptr(Address(r15_thread, JavaThread::vm_result_oop_offset()), NULL_WORD);
1325   verify_oop_msg(oop_result, "broken oop in call_VM_base");
1326 }
1327 
1328 void MacroAssembler::get_vm_result_metadata(Register metadata_result) {
1329   movptr(metadata_result, Address(r15_thread, JavaThread::vm_result_metadata_offset()));
1330   movptr(Address(r15_thread, JavaThread::vm_result_metadata_offset()), NULL_WORD);
1331 }
1332 
1333 void MacroAssembler::check_and_handle_earlyret() {
1334 }
1335 
1336 void MacroAssembler::check_and_handle_popframe() {
1337 }
1338 
1339 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm, Register rscratch) {
1340   assert(rscratch != noreg || always_reachable(src1), "missing");
1341 
1342   if (reachable(src1)) {
1343     cmpl(as_Address(src1), imm);
1344   } else {
1345     lea(rscratch, src1);
1346     cmpl(Address(rscratch, 0), imm);
1347   }
1348 }
1349 
1350 void MacroAssembler::cmp32(Register src1, AddressLiteral src2, Register rscratch) {
1351   assert(!src2.is_lval(), "use cmpptr");
1352   assert(rscratch != noreg || always_reachable(src2), "missing");
1353 
1354   if (reachable(src2)) {
1355     cmpl(src1, as_Address(src2));
1356   } else {
1357     lea(rscratch, src2);
1358     cmpl(src1, Address(rscratch, 0));
1359   }
1360 }
1361 
1362 void MacroAssembler::cmp32(Register src1, int32_t imm) {
1363   Assembler::cmpl(src1, imm);
1364 }
1365 
1366 void MacroAssembler::cmp32(Register src1, Address src2) {
1367   Assembler::cmpl(src1, src2);
1368 }
1369 
1370 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
1371   ucomisd(opr1, opr2);
1372 
1373   Label L;
1374   if (unordered_is_less) {
1375     movl(dst, -1);
1376     jcc(Assembler::parity, L);
1377     jcc(Assembler::below , L);
1378     movl(dst, 0);
1379     jcc(Assembler::equal , L);
1380     increment(dst);
1381   } else { // unordered is greater
1382     movl(dst, 1);
1383     jcc(Assembler::parity, L);
1384     jcc(Assembler::above , L);
1385     movl(dst, 0);
1386     jcc(Assembler::equal , L);
1387     decrementl(dst);
1388   }
1389   bind(L);
1390 }
1391 
1392 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
1393   ucomiss(opr1, opr2);
1394 
1395   Label L;
1396   if (unordered_is_less) {
1397     movl(dst, -1);
1398     jcc(Assembler::parity, L);
1399     jcc(Assembler::below , L);
1400     movl(dst, 0);
1401     jcc(Assembler::equal , L);
1402     increment(dst);
1403   } else { // unordered is greater
1404     movl(dst, 1);
1405     jcc(Assembler::parity, L);
1406     jcc(Assembler::above , L);
1407     movl(dst, 0);
1408     jcc(Assembler::equal , L);
1409     decrementl(dst);
1410   }
1411   bind(L);
1412 }
1413 
1414 
1415 void MacroAssembler::cmp8(AddressLiteral src1, int imm, Register rscratch) {
1416   assert(rscratch != noreg || always_reachable(src1), "missing");
1417 
1418   if (reachable(src1)) {
1419     cmpb(as_Address(src1), imm);
1420   } else {
1421     lea(rscratch, src1);
1422     cmpb(Address(rscratch, 0), imm);
1423   }
1424 }
1425 
1426 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2, Register rscratch) {
1427   assert(rscratch != noreg || always_reachable(src2), "missing");
1428 
1429   if (src2.is_lval()) {
1430     movptr(rscratch, src2);
1431     Assembler::cmpq(src1, rscratch);
1432   } else if (reachable(src2)) {
1433     cmpq(src1, as_Address(src2));
1434   } else {
1435     lea(rscratch, src2);
1436     Assembler::cmpq(src1, Address(rscratch, 0));
1437   }
1438 }
1439 
1440 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2, Register rscratch) {
1441   assert(src2.is_lval(), "not a mem-mem compare");
1442   // moves src2's literal address
1443   movptr(rscratch, src2);
1444   Assembler::cmpq(src1, rscratch);
1445 }
1446 
1447 void MacroAssembler::cmpoop(Register src1, Register src2) {
1448   cmpptr(src1, src2);
1449 }
1450 
1451 void MacroAssembler::cmpoop(Register src1, Address src2) {
1452   cmpptr(src1, src2);
1453 }
1454 
1455 void MacroAssembler::cmpoop(Register src1, jobject src2, Register rscratch) {
1456   movoop(rscratch, src2);
1457   cmpptr(src1, rscratch);
1458 }
1459 
1460 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr, Register rscratch) {
1461   assert(rscratch != noreg || always_reachable(adr), "missing");
1462 
1463   if (reachable(adr)) {
1464     lock();
1465     cmpxchgptr(reg, as_Address(adr));
1466   } else {
1467     lea(rscratch, adr);
1468     lock();
1469     cmpxchgptr(reg, Address(rscratch, 0));
1470   }
1471 }
1472 
1473 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
1474   cmpxchgq(reg, adr);
1475 }
1476 
1477 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src, Register rscratch) {
1478   assert(rscratch != noreg || always_reachable(src), "missing");
1479 
1480   if (reachable(src)) {
1481     Assembler::comisd(dst, as_Address(src));
1482   } else {
1483     lea(rscratch, src);
1484     Assembler::comisd(dst, Address(rscratch, 0));
1485   }
1486 }
1487 
1488 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src, Register rscratch) {
1489   assert(rscratch != noreg || always_reachable(src), "missing");
1490 
1491   if (reachable(src)) {
1492     Assembler::comiss(dst, as_Address(src));
1493   } else {
1494     lea(rscratch, src);
1495     Assembler::comiss(dst, Address(rscratch, 0));
1496   }
1497 }
1498 
1499 
1500 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr, Register rscratch) {
1501   assert(rscratch != noreg || always_reachable(counter_addr), "missing");
1502 
1503   Condition negated_cond = negate_condition(cond);
1504   Label L;
1505   jcc(negated_cond, L);
1506   pushf(); // Preserve flags
1507   atomic_incl(counter_addr, rscratch);
1508   popf();
1509   bind(L);
1510 }
1511 
1512 int MacroAssembler::corrected_idivl(Register reg) {
1513   // Full implementation of Java idiv and irem; checks for
1514   // special case as described in JVM spec., p.243 & p.271.
1515   // The function returns the (pc) offset of the idivl
1516   // instruction - may be needed for implicit exceptions.
1517   //
1518   //         normal case                           special case
1519   //
1520   // input : rax,: dividend                         min_int
1521   //         reg: divisor   (may not be rax,/rdx)   -1
1522   //
1523   // output: rax,: quotient  (= rax, idiv reg)       min_int
1524   //         rdx: remainder (= rax, irem reg)       0
1525   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
1526   const int min_int = 0x80000000;
1527   Label normal_case, special_case;
1528 
1529   // check for special case
1530   cmpl(rax, min_int);
1531   jcc(Assembler::notEqual, normal_case);
1532   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
1533   cmpl(reg, -1);
1534   jcc(Assembler::equal, special_case);
1535 
1536   // handle normal case
1537   bind(normal_case);
1538   cdql();
1539   int idivl_offset = offset();
1540   idivl(reg);
1541 
1542   // normal and special case exit
1543   bind(special_case);
1544 
1545   return idivl_offset;
1546 }
1547 
1548 
1549 
1550 void MacroAssembler::decrementl(Register reg, int value) {
1551   if (value == min_jint) {subl(reg, value) ; return; }
1552   if (value <  0) { incrementl(reg, -value); return; }
1553   if (value == 0) {                        ; return; }
1554   if (value == 1 && UseIncDec) { decl(reg) ; return; }
1555   /* else */      { subl(reg, value)       ; return; }
1556 }
1557 
1558 void MacroAssembler::decrementl(Address dst, int value) {
1559   if (value == min_jint) {subl(dst, value) ; return; }
1560   if (value <  0) { incrementl(dst, -value); return; }
1561   if (value == 0) {                        ; return; }
1562   if (value == 1 && UseIncDec) { decl(dst) ; return; }
1563   /* else */      { subl(dst, value)       ; return; }
1564 }
1565 
1566 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
1567   assert(shift_value > 0, "illegal shift value");
1568   Label _is_positive;
1569   testl (reg, reg);
1570   jcc (Assembler::positive, _is_positive);
1571   int offset = (1 << shift_value) - 1 ;
1572 
1573   if (offset == 1) {
1574     incrementl(reg);
1575   } else {
1576     addl(reg, offset);
1577   }
1578 
1579   bind (_is_positive);
1580   sarl(reg, shift_value);
1581 }
1582 
1583 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src, Register rscratch) {
1584   assert(rscratch != noreg || always_reachable(src), "missing");
1585 
1586   if (reachable(src)) {
1587     Assembler::divsd(dst, as_Address(src));
1588   } else {
1589     lea(rscratch, src);
1590     Assembler::divsd(dst, Address(rscratch, 0));
1591   }
1592 }
1593 
1594 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src, Register rscratch) {
1595   assert(rscratch != noreg || always_reachable(src), "missing");
1596 
1597   if (reachable(src)) {
1598     Assembler::divss(dst, as_Address(src));
1599   } else {
1600     lea(rscratch, src);
1601     Assembler::divss(dst, Address(rscratch, 0));
1602   }
1603 }
1604 
1605 void MacroAssembler::enter() {
1606   push(rbp);
1607   mov(rbp, rsp);
1608 }
1609 
1610 void MacroAssembler::post_call_nop() {
1611   if (!Continuations::enabled()) {
1612     return;
1613   }
1614   InstructionMark im(this);
1615   relocate(post_call_nop_Relocation::spec());
1616   InlineSkippedInstructionsCounter skipCounter(this);
1617   emit_int8((uint8_t)0x0f);
1618   emit_int8((uint8_t)0x1f);
1619   emit_int8((uint8_t)0x84);
1620   emit_int8((uint8_t)0x00);
1621   emit_int32(0x00);
1622 }
1623 
1624 // A 5 byte nop that is safe for patching (see patch_verified_entry)
1625 void MacroAssembler::fat_nop() {
1626   if (UseAddressNop) {
1627     addr_nop_5();
1628   } else {
1629     emit_int8((uint8_t)0x26); // es:
1630     emit_int8((uint8_t)0x2e); // cs:
1631     emit_int8((uint8_t)0x64); // fs:
1632     emit_int8((uint8_t)0x65); // gs:
1633     emit_int8((uint8_t)0x90);
1634   }
1635 }
1636 
1637 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src, Register rscratch) {
1638   assert(rscratch != noreg || always_reachable(src), "missing");
1639   if (reachable(src)) {
1640     Assembler::mulpd(dst, as_Address(src));
1641   } else {
1642     lea(rscratch, src);
1643     Assembler::mulpd(dst, Address(rscratch, 0));
1644   }
1645 }
1646 
1647 // dst = c = a * b + c
1648 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
1649   Assembler::vfmadd231sd(c, a, b);
1650   if (dst != c) {
1651     movdbl(dst, c);
1652   }
1653 }
1654 
1655 // dst = c = a * b + c
1656 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
1657   Assembler::vfmadd231ss(c, a, b);
1658   if (dst != c) {
1659     movflt(dst, c);
1660   }
1661 }
1662 
1663 // dst = c = a * b + c
1664 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
1665   Assembler::vfmadd231pd(c, a, b, vector_len);
1666   if (dst != c) {
1667     vmovdqu(dst, c);
1668   }
1669 }
1670 
1671 // dst = c = a * b + c
1672 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
1673   Assembler::vfmadd231ps(c, a, b, vector_len);
1674   if (dst != c) {
1675     vmovdqu(dst, c);
1676   }
1677 }
1678 
1679 // dst = c = a * b + c
1680 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
1681   Assembler::vfmadd231pd(c, a, b, vector_len);
1682   if (dst != c) {
1683     vmovdqu(dst, c);
1684   }
1685 }
1686 
1687 // dst = c = a * b + c
1688 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
1689   Assembler::vfmadd231ps(c, a, b, vector_len);
1690   if (dst != c) {
1691     vmovdqu(dst, c);
1692   }
1693 }
1694 
1695 void MacroAssembler::incrementl(AddressLiteral dst, Register rscratch) {
1696   assert(rscratch != noreg || always_reachable(dst), "missing");
1697 
1698   if (reachable(dst)) {
1699     incrementl(as_Address(dst));
1700   } else {
1701     lea(rscratch, dst);
1702     incrementl(Address(rscratch, 0));
1703   }
1704 }
1705 
1706 void MacroAssembler::incrementl(ArrayAddress dst, Register rscratch) {
1707   incrementl(as_Address(dst, rscratch));
1708 }
1709 
1710 void MacroAssembler::incrementl(Register reg, int value) {
1711   if (value == min_jint) {addl(reg, value) ; return; }
1712   if (value <  0) { decrementl(reg, -value); return; }
1713   if (value == 0) {                        ; return; }
1714   if (value == 1 && UseIncDec) { incl(reg) ; return; }
1715   /* else */      { addl(reg, value)       ; return; }
1716 }
1717 
1718 void MacroAssembler::incrementl(Address dst, int value) {
1719   if (value == min_jint) {addl(dst, value) ; return; }
1720   if (value <  0) { decrementl(dst, -value); return; }
1721   if (value == 0) {                        ; return; }
1722   if (value == 1 && UseIncDec) { incl(dst) ; return; }
1723   /* else */      { addl(dst, value)       ; return; }
1724 }
1725 
1726 void MacroAssembler::jump(AddressLiteral dst, Register rscratch) {
1727   assert(rscratch != noreg || always_reachable(dst), "missing");
1728   assert(!dst.rspec().reloc()->is_data(), "should not use ExternalAddress for jump");
1729   if (reachable(dst)) {
1730     jmp_literal(dst.target(), dst.rspec());
1731   } else {
1732     lea(rscratch, dst);
1733     jmp(rscratch);
1734   }
1735 }
1736 
1737 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst, Register rscratch) {
1738   assert(rscratch != noreg || always_reachable(dst), "missing");
1739   assert(!dst.rspec().reloc()->is_data(), "should not use ExternalAddress for jump_cc");
1740   if (reachable(dst)) {
1741     InstructionMark im(this);
1742     relocate(dst.reloc());
1743     const int short_size = 2;
1744     const int long_size = 6;
1745     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
1746     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
1747       // 0111 tttn #8-bit disp
1748       emit_int8(0x70 | cc);
1749       emit_int8((offs - short_size) & 0xFF);
1750     } else {
1751       // 0000 1111 1000 tttn #32-bit disp
1752       emit_int8(0x0F);
1753       emit_int8((unsigned char)(0x80 | cc));
1754       emit_int32(offs - long_size);
1755     }
1756   } else {
1757 #ifdef ASSERT
1758     warning("reversing conditional branch");
1759 #endif /* ASSERT */
1760     Label skip;
1761     jccb(reverse[cc], skip);
1762     lea(rscratch, dst);
1763     Assembler::jmp(rscratch);
1764     bind(skip);
1765   }
1766 }
1767 
1768 void MacroAssembler::cmp32_mxcsr_std(Address mxcsr_save, Register tmp, Register rscratch) {
1769   ExternalAddress mxcsr_std(StubRoutines::x86::addr_mxcsr_std());
1770   assert(rscratch != noreg || always_reachable(mxcsr_std), "missing");
1771 
1772   stmxcsr(mxcsr_save);
1773   movl(tmp, mxcsr_save);
1774   if (EnableX86ECoreOpts) {
1775     // The mxcsr_std has status bits set for performance on ECore
1776     orl(tmp, 0x003f);
1777   } else {
1778     // Mask out status bits (only check control and mask bits)
1779     andl(tmp, 0xFFC0);
1780   }
1781   cmp32(tmp, mxcsr_std, rscratch);
1782 }
1783 
1784 void MacroAssembler::ldmxcsr(AddressLiteral src, Register rscratch) {
1785   assert(rscratch != noreg || always_reachable(src), "missing");
1786 
1787   if (reachable(src)) {
1788     Assembler::ldmxcsr(as_Address(src));
1789   } else {
1790     lea(rscratch, src);
1791     Assembler::ldmxcsr(Address(rscratch, 0));
1792   }
1793 }
1794 
1795 int MacroAssembler::load_signed_byte(Register dst, Address src) {
1796   int off = offset();
1797   movsbl(dst, src); // movsxb
1798   return off;
1799 }
1800 
1801 // Note: load_signed_short used to be called load_signed_word.
1802 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
1803 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
1804 // The term "word" in HotSpot means a 32- or 64-bit machine word.
1805 int MacroAssembler::load_signed_short(Register dst, Address src) {
1806   // This is dubious to me since it seems safe to do a signed 16 => 64 bit
1807   // version but this is what 64bit has always done. This seems to imply
1808   // that users are only using 32bits worth.
1809   int off = offset();
1810   movswl(dst, src); // movsxw
1811   return off;
1812 }
1813 
1814 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
1815   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
1816   // and "3.9 Partial Register Penalties", p. 22).
1817   int off = offset();
1818   movzbl(dst, src); // movzxb
1819   return off;
1820 }
1821 
1822 // Note: load_unsigned_short used to be called load_unsigned_word.
1823 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
1824   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
1825   // and "3.9 Partial Register Penalties", p. 22).
1826   int off = offset();
1827   movzwl(dst, src); // movzxw
1828   return off;
1829 }
1830 
1831 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
1832   switch (size_in_bytes) {
1833   case  8:  movq(dst, src); break;
1834   case  4:  movl(dst, src); break;
1835   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
1836   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
1837   default:  ShouldNotReachHere();
1838   }
1839 }
1840 
1841 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
1842   switch (size_in_bytes) {
1843   case  8:  movq(dst, src); break;
1844   case  4:  movl(dst, src); break;
1845   case  2:  movw(dst, src); break;
1846   case  1:  movb(dst, src); break;
1847   default:  ShouldNotReachHere();
1848   }
1849 }
1850 
1851 void MacroAssembler::mov32(AddressLiteral dst, Register src, Register rscratch) {
1852   assert(rscratch != noreg || always_reachable(dst), "missing");
1853 
1854   if (reachable(dst)) {
1855     movl(as_Address(dst), src);
1856   } else {
1857     lea(rscratch, dst);
1858     movl(Address(rscratch, 0), src);
1859   }
1860 }
1861 
1862 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
1863   if (reachable(src)) {
1864     movl(dst, as_Address(src));
1865   } else {
1866     lea(dst, src);
1867     movl(dst, Address(dst, 0));
1868   }
1869 }
1870 
1871 // C++ bool manipulation
1872 
1873 void MacroAssembler::movbool(Register dst, Address src) {
1874   if(sizeof(bool) == 1)
1875     movb(dst, src);
1876   else if(sizeof(bool) == 2)
1877     movw(dst, src);
1878   else if(sizeof(bool) == 4)
1879     movl(dst, src);
1880   else
1881     // unsupported
1882     ShouldNotReachHere();
1883 }
1884 
1885 void MacroAssembler::movbool(Address dst, bool boolconst) {
1886   if(sizeof(bool) == 1)
1887     movb(dst, (int) boolconst);
1888   else if(sizeof(bool) == 2)
1889     movw(dst, (int) boolconst);
1890   else if(sizeof(bool) == 4)
1891     movl(dst, (int) boolconst);
1892   else
1893     // unsupported
1894     ShouldNotReachHere();
1895 }
1896 
1897 void MacroAssembler::movbool(Address dst, Register src) {
1898   if(sizeof(bool) == 1)
1899     movb(dst, src);
1900   else if(sizeof(bool) == 2)
1901     movw(dst, src);
1902   else if(sizeof(bool) == 4)
1903     movl(dst, src);
1904   else
1905     // unsupported
1906     ShouldNotReachHere();
1907 }
1908 
1909 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src, Register rscratch) {
1910   assert(rscratch != noreg || always_reachable(src), "missing");
1911 
1912   if (reachable(src)) {
1913     movdl(dst, as_Address(src));
1914   } else {
1915     lea(rscratch, src);
1916     movdl(dst, Address(rscratch, 0));
1917   }
1918 }
1919 
1920 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src, Register rscratch) {
1921   assert(rscratch != noreg || always_reachable(src), "missing");
1922 
1923   if (reachable(src)) {
1924     movq(dst, as_Address(src));
1925   } else {
1926     lea(rscratch, src);
1927     movq(dst, Address(rscratch, 0));
1928   }
1929 }
1930 
1931 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src, Register rscratch) {
1932   assert(rscratch != noreg || always_reachable(src), "missing");
1933 
1934   if (reachable(src)) {
1935     if (UseXmmLoadAndClearUpper) {
1936       movsd (dst, as_Address(src));
1937     } else {
1938       movlpd(dst, as_Address(src));
1939     }
1940   } else {
1941     lea(rscratch, src);
1942     if (UseXmmLoadAndClearUpper) {
1943       movsd (dst, Address(rscratch, 0));
1944     } else {
1945       movlpd(dst, Address(rscratch, 0));
1946     }
1947   }
1948 }
1949 
1950 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src, Register rscratch) {
1951   assert(rscratch != noreg || always_reachable(src), "missing");
1952 
1953   if (reachable(src)) {
1954     movss(dst, as_Address(src));
1955   } else {
1956     lea(rscratch, src);
1957     movss(dst, Address(rscratch, 0));
1958   }
1959 }
1960 
1961 void MacroAssembler::movptr(Register dst, Register src) {
1962   movq(dst, src);
1963 }
1964 
1965 void MacroAssembler::movptr(Register dst, Address src) {
1966   movq(dst, src);
1967 }
1968 
1969 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
1970 void MacroAssembler::movptr(Register dst, intptr_t src) {
1971   if (is_uimm32(src)) {
1972     movl(dst, checked_cast<uint32_t>(src));
1973   } else if (is_simm32(src)) {
1974     movq(dst, checked_cast<int32_t>(src));
1975   } else {
1976     mov64(dst, src);
1977   }
1978 }
1979 
1980 void MacroAssembler::movptr(Address dst, Register src) {
1981   movq(dst, src);
1982 }
1983 
1984 void MacroAssembler::movptr(Address dst, int32_t src) {
1985   movslq(dst, src);
1986 }
1987 
1988 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
1989   assert(((src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
1990   Assembler::movdqu(dst, src);
1991 }
1992 
1993 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
1994   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
1995   Assembler::movdqu(dst, src);
1996 }
1997 
1998 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
1999   assert(((dst->encoding() < 16  && src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
2000   Assembler::movdqu(dst, src);
2001 }
2002 
2003 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register rscratch) {
2004   assert(rscratch != noreg || always_reachable(src), "missing");
2005 
2006   if (reachable(src)) {
2007     movdqu(dst, as_Address(src));
2008   } else {
2009     lea(rscratch, src);
2010     movdqu(dst, Address(rscratch, 0));
2011   }
2012 }
2013 
2014 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
2015   assert(((src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
2016   Assembler::vmovdqu(dst, src);
2017 }
2018 
2019 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
2020   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
2021   Assembler::vmovdqu(dst, src);
2022 }
2023 
2024 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
2025   assert(((dst->encoding() < 16  && src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
2026   Assembler::vmovdqu(dst, src);
2027 }
2028 
2029 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src, Register rscratch) {
2030   assert(rscratch != noreg || always_reachable(src), "missing");
2031 
2032   if (reachable(src)) {
2033     vmovdqu(dst, as_Address(src));
2034   }
2035   else {
2036     lea(rscratch, src);
2037     vmovdqu(dst, Address(rscratch, 0));
2038   }
2039 }
2040 
2041 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src, int vector_len, Register rscratch) {
2042   assert(rscratch != noreg || always_reachable(src), "missing");
2043 
2044   if (vector_len == AVX_512bit) {
2045     evmovdquq(dst, src, AVX_512bit, rscratch);
2046   } else if (vector_len == AVX_256bit) {
2047     vmovdqu(dst, src, rscratch);
2048   } else {
2049     movdqu(dst, src, rscratch);
2050   }
2051 }
2052 
2053 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src, int vector_len) {
2054   if (vector_len == AVX_512bit) {
2055     evmovdquq(dst, src, AVX_512bit);
2056   } else if (vector_len == AVX_256bit) {
2057     vmovdqu(dst, src);
2058   } else {
2059     movdqu(dst, src);
2060   }
2061 }
2062 
2063 void MacroAssembler::vmovdqu(Address dst, XMMRegister src, int vector_len) {
2064   if (vector_len == AVX_512bit) {
2065     evmovdquq(dst, src, AVX_512bit);
2066   } else if (vector_len == AVX_256bit) {
2067     vmovdqu(dst, src);
2068   } else {
2069     movdqu(dst, src);
2070   }
2071 }
2072 
2073 void MacroAssembler::vmovdqu(XMMRegister dst, Address src, int vector_len) {
2074   if (vector_len == AVX_512bit) {
2075     evmovdquq(dst, src, AVX_512bit);
2076   } else if (vector_len == AVX_256bit) {
2077     vmovdqu(dst, src);
2078   } else {
2079     movdqu(dst, src);
2080   }
2081 }
2082 
2083 void MacroAssembler::vmovdqa(XMMRegister dst, AddressLiteral src, Register rscratch) {
2084   assert(rscratch != noreg || always_reachable(src), "missing");
2085 
2086   if (reachable(src)) {
2087     vmovdqa(dst, as_Address(src));
2088   }
2089   else {
2090     lea(rscratch, src);
2091     vmovdqa(dst, Address(rscratch, 0));
2092   }
2093 }
2094 
2095 void MacroAssembler::vmovdqa(XMMRegister dst, AddressLiteral src, int vector_len, Register rscratch) {
2096   assert(rscratch != noreg || always_reachable(src), "missing");
2097 
2098   if (vector_len == AVX_512bit) {
2099     evmovdqaq(dst, src, AVX_512bit, rscratch);
2100   } else if (vector_len == AVX_256bit) {
2101     vmovdqa(dst, src, rscratch);
2102   } else {
2103     movdqa(dst, src, rscratch);
2104   }
2105 }
2106 
2107 void MacroAssembler::kmov(KRegister dst, Address src) {
2108   if (VM_Version::supports_avx512bw()) {
2109     kmovql(dst, src);
2110   } else {
2111     assert(VM_Version::supports_evex(), "");
2112     kmovwl(dst, src);
2113   }
2114 }
2115 
2116 void MacroAssembler::kmov(Address dst, KRegister src) {
2117   if (VM_Version::supports_avx512bw()) {
2118     kmovql(dst, src);
2119   } else {
2120     assert(VM_Version::supports_evex(), "");
2121     kmovwl(dst, src);
2122   }
2123 }
2124 
2125 void MacroAssembler::kmov(KRegister dst, KRegister src) {
2126   if (VM_Version::supports_avx512bw()) {
2127     kmovql(dst, src);
2128   } else {
2129     assert(VM_Version::supports_evex(), "");
2130     kmovwl(dst, src);
2131   }
2132 }
2133 
2134 void MacroAssembler::kmov(Register dst, KRegister src) {
2135   if (VM_Version::supports_avx512bw()) {
2136     kmovql(dst, src);
2137   } else {
2138     assert(VM_Version::supports_evex(), "");
2139     kmovwl(dst, src);
2140   }
2141 }
2142 
2143 void MacroAssembler::kmov(KRegister dst, Register src) {
2144   if (VM_Version::supports_avx512bw()) {
2145     kmovql(dst, src);
2146   } else {
2147     assert(VM_Version::supports_evex(), "");
2148     kmovwl(dst, src);
2149   }
2150 }
2151 
2152 void MacroAssembler::kmovql(KRegister dst, AddressLiteral src, Register rscratch) {
2153   assert(rscratch != noreg || always_reachable(src), "missing");
2154 
2155   if (reachable(src)) {
2156     kmovql(dst, as_Address(src));
2157   } else {
2158     lea(rscratch, src);
2159     kmovql(dst, Address(rscratch, 0));
2160   }
2161 }
2162 
2163 void MacroAssembler::kmovwl(KRegister dst, AddressLiteral src, Register rscratch) {
2164   assert(rscratch != noreg || always_reachable(src), "missing");
2165 
2166   if (reachable(src)) {
2167     kmovwl(dst, as_Address(src));
2168   } else {
2169     lea(rscratch, src);
2170     kmovwl(dst, Address(rscratch, 0));
2171   }
2172 }
2173 
2174 void MacroAssembler::evmovdqub(XMMRegister dst, KRegister mask, AddressLiteral src, bool merge,
2175                                int vector_len, Register rscratch) {
2176   assert(rscratch != noreg || always_reachable(src), "missing");
2177 
2178   if (reachable(src)) {
2179     Assembler::evmovdqub(dst, mask, as_Address(src), merge, vector_len);
2180   } else {
2181     lea(rscratch, src);
2182     Assembler::evmovdqub(dst, mask, Address(rscratch, 0), merge, vector_len);
2183   }
2184 }
2185 
2186 void MacroAssembler::evmovdquw(XMMRegister dst, KRegister mask, AddressLiteral src, bool merge,
2187                                int vector_len, Register rscratch) {
2188   assert(rscratch != noreg || always_reachable(src), "missing");
2189 
2190   if (reachable(src)) {
2191     Assembler::evmovdquw(dst, mask, as_Address(src), merge, vector_len);
2192   } else {
2193     lea(rscratch, src);
2194     Assembler::evmovdquw(dst, mask, Address(rscratch, 0), merge, vector_len);
2195   }
2196 }
2197 
2198 void MacroAssembler::evmovdqul(XMMRegister dst, KRegister mask, AddressLiteral src, bool merge, int vector_len, Register rscratch) {
2199   assert(rscratch != noreg || always_reachable(src), "missing");
2200 
2201   if (reachable(src)) {
2202     Assembler::evmovdqul(dst, mask, as_Address(src), merge, vector_len);
2203   } else {
2204     lea(rscratch, src);
2205     Assembler::evmovdqul(dst, mask, Address(rscratch, 0), merge, vector_len);
2206   }
2207 }
2208 
2209 void MacroAssembler::evmovdquq(XMMRegister dst, KRegister mask, AddressLiteral src, bool merge, int vector_len, Register rscratch) {
2210   assert(rscratch != noreg || always_reachable(src), "missing");
2211 
2212   if (reachable(src)) {
2213     Assembler::evmovdquq(dst, mask, as_Address(src), merge, vector_len);
2214   } else {
2215     lea(rscratch, src);
2216     Assembler::evmovdquq(dst, mask, Address(rscratch, 0), merge, vector_len);
2217   }
2218 }
2219 
2220 void MacroAssembler::evmovdquq(XMMRegister dst, AddressLiteral src, int vector_len, Register rscratch) {
2221   assert(rscratch != noreg || always_reachable(src), "missing");
2222 
2223   if (reachable(src)) {
2224     Assembler::evmovdquq(dst, as_Address(src), vector_len);
2225   } else {
2226     lea(rscratch, src);
2227     Assembler::evmovdquq(dst, Address(rscratch, 0), vector_len);
2228   }
2229 }
2230 
2231 void MacroAssembler::evmovdqaq(XMMRegister dst, KRegister mask, AddressLiteral src, bool merge, int vector_len, Register rscratch) {
2232   assert(rscratch != noreg || always_reachable(src), "missing");
2233 
2234   if (reachable(src)) {
2235     Assembler::evmovdqaq(dst, mask, as_Address(src), merge, vector_len);
2236   } else {
2237     lea(rscratch, src);
2238     Assembler::evmovdqaq(dst, mask, Address(rscratch, 0), merge, vector_len);
2239   }
2240 }
2241 
2242 void MacroAssembler::evmovdqaq(XMMRegister dst, AddressLiteral src, int vector_len, Register rscratch) {
2243   assert(rscratch != noreg || always_reachable(src), "missing");
2244 
2245   if (reachable(src)) {
2246     Assembler::evmovdqaq(dst, as_Address(src), vector_len);
2247   } else {
2248     lea(rscratch, src);
2249     Assembler::evmovdqaq(dst, Address(rscratch, 0), vector_len);
2250   }
2251 }
2252 
2253 
2254 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src, Register rscratch) {
2255   assert(rscratch != noreg || always_reachable(src), "missing");
2256 
2257   if (reachable(src)) {
2258     Assembler::movdqa(dst, as_Address(src));
2259   } else {
2260     lea(rscratch, src);
2261     Assembler::movdqa(dst, Address(rscratch, 0));
2262   }
2263 }
2264 
2265 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src, Register rscratch) {
2266   assert(rscratch != noreg || always_reachable(src), "missing");
2267 
2268   if (reachable(src)) {
2269     Assembler::movsd(dst, as_Address(src));
2270   } else {
2271     lea(rscratch, src);
2272     Assembler::movsd(dst, Address(rscratch, 0));
2273   }
2274 }
2275 
2276 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src, Register rscratch) {
2277   assert(rscratch != noreg || always_reachable(src), "missing");
2278 
2279   if (reachable(src)) {
2280     Assembler::movss(dst, as_Address(src));
2281   } else {
2282     lea(rscratch, src);
2283     Assembler::movss(dst, Address(rscratch, 0));
2284   }
2285 }
2286 
2287 void MacroAssembler::movddup(XMMRegister dst, AddressLiteral src, Register rscratch) {
2288   assert(rscratch != noreg || always_reachable(src), "missing");
2289 
2290   if (reachable(src)) {
2291     Assembler::movddup(dst, as_Address(src));
2292   } else {
2293     lea(rscratch, src);
2294     Assembler::movddup(dst, Address(rscratch, 0));
2295   }
2296 }
2297 
2298 void MacroAssembler::vmovddup(XMMRegister dst, AddressLiteral src, int vector_len, Register rscratch) {
2299   assert(rscratch != noreg || always_reachable(src), "missing");
2300 
2301   if (reachable(src)) {
2302     Assembler::vmovddup(dst, as_Address(src), vector_len);
2303   } else {
2304     lea(rscratch, src);
2305     Assembler::vmovddup(dst, Address(rscratch, 0), vector_len);
2306   }
2307 }
2308 
2309 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src, Register rscratch) {
2310   assert(rscratch != noreg || always_reachable(src), "missing");
2311 
2312   if (reachable(src)) {
2313     Assembler::mulsd(dst, as_Address(src));
2314   } else {
2315     lea(rscratch, src);
2316     Assembler::mulsd(dst, Address(rscratch, 0));
2317   }
2318 }
2319 
2320 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src, Register rscratch) {
2321   assert(rscratch != noreg || always_reachable(src), "missing");
2322 
2323   if (reachable(src)) {
2324     Assembler::mulss(dst, as_Address(src));
2325   } else {
2326     lea(rscratch, src);
2327     Assembler::mulss(dst, Address(rscratch, 0));
2328   }
2329 }
2330 
2331 void MacroAssembler::null_check(Register reg, int offset) {
2332   if (needs_explicit_null_check(offset)) {
2333     // provoke OS null exception if reg is null by
2334     // accessing M[reg] w/o changing any (non-CC) registers
2335     // NOTE: cmpl is plenty here to provoke a segv
2336     cmpptr(rax, Address(reg, 0));
2337     // Note: should probably use testl(rax, Address(reg, 0));
2338     //       may be shorter code (however, this version of
2339     //       testl needs to be implemented first)
2340   } else {
2341     // nothing to do, (later) access of M[reg + offset]
2342     // will provoke OS null exception if reg is null
2343   }
2344 }
2345 
2346 void MacroAssembler::os_breakpoint() {
2347   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
2348   // (e.g., MSVC can't call ps() otherwise)
2349   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
2350 }
2351 
2352 void MacroAssembler::unimplemented(const char* what) {
2353   const char* buf = nullptr;
2354   {
2355     ResourceMark rm;
2356     stringStream ss;
2357     ss.print("unimplemented: %s", what);
2358     buf = code_string(ss.as_string());
2359   }
2360   stop(buf);
2361 }
2362 
2363 #define XSTATE_BV 0x200
2364 
2365 void MacroAssembler::pop_CPU_state() {
2366   pop_FPU_state();
2367   pop_IU_state();
2368 }
2369 
2370 void MacroAssembler::pop_FPU_state() {
2371   fxrstor(Address(rsp, 0));
2372   addptr(rsp, FPUStateSizeInWords * wordSize);
2373 }
2374 
2375 void MacroAssembler::pop_IU_state() {
2376   popa();
2377   addq(rsp, 8);
2378   popf();
2379 }
2380 
2381 // Save Integer and Float state
2382 // Warning: Stack must be 16 byte aligned (64bit)
2383 void MacroAssembler::push_CPU_state() {
2384   push_IU_state();
2385   push_FPU_state();
2386 }
2387 
2388 void MacroAssembler::push_FPU_state() {
2389   subptr(rsp, FPUStateSizeInWords * wordSize);
2390   fxsave(Address(rsp, 0));
2391 }
2392 
2393 void MacroAssembler::push_IU_state() {
2394   // Push flags first because pusha kills them
2395   pushf();
2396   // Make sure rsp stays 16-byte aligned
2397   subq(rsp, 8);
2398   pusha();
2399 }
2400 
2401 void MacroAssembler::push_cont_fastpath() {
2402   if (!Continuations::enabled()) return;
2403 
2404   Label L_done;
2405   cmpptr(rsp, Address(r15_thread, JavaThread::cont_fastpath_offset()));
2406   jccb(Assembler::belowEqual, L_done);
2407   movptr(Address(r15_thread, JavaThread::cont_fastpath_offset()), rsp);
2408   bind(L_done);
2409 }
2410 
2411 void MacroAssembler::pop_cont_fastpath() {
2412   if (!Continuations::enabled()) return;
2413 
2414   Label L_done;
2415   cmpptr(rsp, Address(r15_thread, JavaThread::cont_fastpath_offset()));
2416   jccb(Assembler::below, L_done);
2417   movptr(Address(r15_thread, JavaThread::cont_fastpath_offset()), 0);
2418   bind(L_done);
2419 }
2420 
2421 void MacroAssembler::inc_held_monitor_count() {
2422   incrementq(Address(r15_thread, JavaThread::held_monitor_count_offset()));
2423 }
2424 
2425 void MacroAssembler::dec_held_monitor_count() {
2426   decrementq(Address(r15_thread, JavaThread::held_monitor_count_offset()));
2427 }
2428 
2429 #ifdef ASSERT
2430 void MacroAssembler::stop_if_in_cont(Register cont, const char* name) {
2431   Label no_cont;
2432   movptr(cont, Address(r15_thread, JavaThread::cont_entry_offset()));
2433   testl(cont, cont);
2434   jcc(Assembler::zero, no_cont);
2435   stop(name);
2436   bind(no_cont);
2437 }
2438 #endif
2439 
2440 void MacroAssembler::reset_last_Java_frame(bool clear_fp) { // determine java_thread register
2441   // we must set sp to zero to clear frame
2442   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
2443   // must clear fp, so that compiled frames are not confused; it is
2444   // possible that we need it only for debugging
2445   if (clear_fp) {
2446     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
2447   }
2448   // Always clear the pc because it could have been set by make_walkable()
2449   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
2450   vzeroupper();
2451 }
2452 
2453 void MacroAssembler::round_to(Register reg, int modulus) {
2454   addptr(reg, modulus - 1);
2455   andptr(reg, -modulus);
2456 }
2457 
2458 void MacroAssembler::safepoint_poll(Label& slow_path, bool at_return, bool in_nmethod) {
2459   if (at_return) {
2460     // Note that when in_nmethod is set, the stack pointer is incremented before the poll. Therefore,
2461     // we may safely use rsp instead to perform the stack watermark check.
2462     cmpptr(in_nmethod ? rsp : rbp, Address(r15_thread, JavaThread::polling_word_offset()));
2463     jcc(Assembler::above, slow_path);
2464     return;
2465   }
2466   testb(Address(r15_thread, JavaThread::polling_word_offset()), SafepointMechanism::poll_bit());
2467   jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
2468 }
2469 
2470 // Calls to C land
2471 //
2472 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
2473 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
2474 // has to be reset to 0. This is required to allow proper stack traversal.
2475 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
2476                                          Register last_java_fp,
2477                                          address  last_java_pc,
2478                                          Register rscratch) {
2479   vzeroupper();
2480   // determine last_java_sp register
2481   if (!last_java_sp->is_valid()) {
2482     last_java_sp = rsp;
2483   }
2484   // last_java_fp is optional
2485   if (last_java_fp->is_valid()) {
2486     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
2487   }
2488   // last_java_pc is optional
2489   if (last_java_pc != nullptr) {
2490     Address java_pc(r15_thread,
2491                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
2492     lea(java_pc, InternalAddress(last_java_pc), rscratch);
2493   }
2494   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
2495 }
2496 
2497 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
2498                                          Register last_java_fp,
2499                                          Label &L,
2500                                          Register scratch) {
2501   lea(scratch, L);
2502   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), scratch);
2503   set_last_Java_frame(last_java_sp, last_java_fp, nullptr, scratch);
2504 }
2505 
2506 void MacroAssembler::shlptr(Register dst, int imm8) {
2507   shlq(dst, imm8);
2508 }
2509 
2510 void MacroAssembler::shrptr(Register dst, int imm8) {
2511   shrq(dst, imm8);
2512 }
2513 
2514 void MacroAssembler::sign_extend_byte(Register reg) {
2515   movsbl(reg, reg); // movsxb
2516 }
2517 
2518 void MacroAssembler::sign_extend_short(Register reg) {
2519   movswl(reg, reg); // movsxw
2520 }
2521 
2522 void MacroAssembler::testl(Address dst, int32_t imm32) {
2523   if (imm32 >= 0 && is8bit(imm32)) {
2524     testb(dst, imm32);
2525   } else {
2526     Assembler::testl(dst, imm32);
2527   }
2528 }
2529 
2530 void MacroAssembler::testl(Register dst, int32_t imm32) {
2531   if (imm32 >= 0 && is8bit(imm32) && dst->has_byte_register()) {
2532     testb(dst, imm32);
2533   } else {
2534     Assembler::testl(dst, imm32);
2535   }
2536 }
2537 
2538 void MacroAssembler::testl(Register dst, AddressLiteral src) {
2539   assert(always_reachable(src), "Address should be reachable");
2540   testl(dst, as_Address(src));
2541 }
2542 
2543 void MacroAssembler::testq(Address dst, int32_t imm32) {
2544   if (imm32 >= 0) {
2545     testl(dst, imm32);
2546   } else {
2547     Assembler::testq(dst, imm32);
2548   }
2549 }
2550 
2551 void MacroAssembler::testq(Register dst, int32_t imm32) {
2552   if (imm32 >= 0) {
2553     testl(dst, imm32);
2554   } else {
2555     Assembler::testq(dst, imm32);
2556   }
2557 }
2558 
2559 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
2560   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2561   Assembler::pcmpeqb(dst, src);
2562 }
2563 
2564 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
2565   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2566   Assembler::pcmpeqw(dst, src);
2567 }
2568 
2569 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
2570   assert((dst->encoding() < 16),"XMM register should be 0-15");
2571   Assembler::pcmpestri(dst, src, imm8);
2572 }
2573 
2574 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
2575   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
2576   Assembler::pcmpestri(dst, src, imm8);
2577 }
2578 
2579 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
2580   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2581   Assembler::pmovzxbw(dst, src);
2582 }
2583 
2584 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
2585   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2586   Assembler::pmovzxbw(dst, src);
2587 }
2588 
2589 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
2590   assert((src->encoding() < 16),"XMM register should be 0-15");
2591   Assembler::pmovmskb(dst, src);
2592 }
2593 
2594 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
2595   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
2596   Assembler::ptest(dst, src);
2597 }
2598 
2599 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src, Register rscratch) {
2600   assert(rscratch != noreg || always_reachable(src), "missing");
2601 
2602   if (reachable(src)) {
2603     Assembler::sqrtss(dst, as_Address(src));
2604   } else {
2605     lea(rscratch, src);
2606     Assembler::sqrtss(dst, Address(rscratch, 0));
2607   }
2608 }
2609 
2610 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src, Register rscratch) {
2611   assert(rscratch != noreg || always_reachable(src), "missing");
2612 
2613   if (reachable(src)) {
2614     Assembler::subsd(dst, as_Address(src));
2615   } else {
2616     lea(rscratch, src);
2617     Assembler::subsd(dst, Address(rscratch, 0));
2618   }
2619 }
2620 
2621 void MacroAssembler::roundsd(XMMRegister dst, AddressLiteral src, int32_t rmode, Register rscratch) {
2622   assert(rscratch != noreg || always_reachable(src), "missing");
2623 
2624   if (reachable(src)) {
2625     Assembler::roundsd(dst, as_Address(src), rmode);
2626   } else {
2627     lea(rscratch, src);
2628     Assembler::roundsd(dst, Address(rscratch, 0), rmode);
2629   }
2630 }
2631 
2632 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src, Register rscratch) {
2633   assert(rscratch != noreg || always_reachable(src), "missing");
2634 
2635   if (reachable(src)) {
2636     Assembler::subss(dst, as_Address(src));
2637   } else {
2638     lea(rscratch, src);
2639     Assembler::subss(dst, Address(rscratch, 0));
2640   }
2641 }
2642 
2643 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src, Register rscratch) {
2644   assert(rscratch != noreg || always_reachable(src), "missing");
2645 
2646   if (reachable(src)) {
2647     Assembler::ucomisd(dst, as_Address(src));
2648   } else {
2649     lea(rscratch, src);
2650     Assembler::ucomisd(dst, Address(rscratch, 0));
2651   }
2652 }
2653 
2654 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src, Register rscratch) {
2655   assert(rscratch != noreg || always_reachable(src), "missing");
2656 
2657   if (reachable(src)) {
2658     Assembler::ucomiss(dst, as_Address(src));
2659   } else {
2660     lea(rscratch, src);
2661     Assembler::ucomiss(dst, Address(rscratch, 0));
2662   }
2663 }
2664 
2665 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src, Register rscratch) {
2666   assert(rscratch != noreg || always_reachable(src), "missing");
2667 
2668   // Used in sign-bit flipping with aligned address.
2669   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
2670 
2671   if (UseAVX > 2 &&
2672       (!VM_Version::supports_avx512dq() || !VM_Version::supports_avx512vl()) &&
2673       (dst->encoding() >= 16)) {
2674     vpxor(dst, dst, src, Assembler::AVX_512bit, rscratch);
2675   } else if (reachable(src)) {
2676     Assembler::xorpd(dst, as_Address(src));
2677   } else {
2678     lea(rscratch, src);
2679     Assembler::xorpd(dst, Address(rscratch, 0));
2680   }
2681 }
2682 
2683 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
2684   if (UseAVX > 2 &&
2685       (!VM_Version::supports_avx512dq() || !VM_Version::supports_avx512vl()) &&
2686       ((dst->encoding() >= 16) || (src->encoding() >= 16))) {
2687     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
2688   } else {
2689     Assembler::xorpd(dst, src);
2690   }
2691 }
2692 
2693 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
2694   if (UseAVX > 2 &&
2695       (!VM_Version::supports_avx512dq() || !VM_Version::supports_avx512vl()) &&
2696       ((dst->encoding() >= 16) || (src->encoding() >= 16))) {
2697     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
2698   } else {
2699     Assembler::xorps(dst, src);
2700   }
2701 }
2702 
2703 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src, Register rscratch) {
2704   assert(rscratch != noreg || always_reachable(src), "missing");
2705 
2706   // Used in sign-bit flipping with aligned address.
2707   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
2708 
2709   if (UseAVX > 2 &&
2710       (!VM_Version::supports_avx512dq() || !VM_Version::supports_avx512vl()) &&
2711       (dst->encoding() >= 16)) {
2712     vpxor(dst, dst, src, Assembler::AVX_512bit, rscratch);
2713   } else if (reachable(src)) {
2714     Assembler::xorps(dst, as_Address(src));
2715   } else {
2716     lea(rscratch, src);
2717     Assembler::xorps(dst, Address(rscratch, 0));
2718   }
2719 }
2720 
2721 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src, Register rscratch) {
2722   assert(rscratch != noreg || always_reachable(src), "missing");
2723 
2724   // Used in sign-bit flipping with aligned address.
2725   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
2726   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
2727   if (reachable(src)) {
2728     Assembler::pshufb(dst, as_Address(src));
2729   } else {
2730     lea(rscratch, src);
2731     Assembler::pshufb(dst, Address(rscratch, 0));
2732   }
2733 }
2734 
2735 // AVX 3-operands instructions
2736 
2737 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src, Register rscratch) {
2738   assert(rscratch != noreg || always_reachable(src), "missing");
2739 
2740   if (reachable(src)) {
2741     vaddsd(dst, nds, as_Address(src));
2742   } else {
2743     lea(rscratch, src);
2744     vaddsd(dst, nds, Address(rscratch, 0));
2745   }
2746 }
2747 
2748 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src, Register rscratch) {
2749   assert(rscratch != noreg || always_reachable(src), "missing");
2750 
2751   if (reachable(src)) {
2752     vaddss(dst, nds, as_Address(src));
2753   } else {
2754     lea(rscratch, src);
2755     vaddss(dst, nds, Address(rscratch, 0));
2756   }
2757 }
2758 
2759 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
2760   assert(UseAVX > 0, "requires some form of AVX");
2761   assert(rscratch != noreg || always_reachable(src), "missing");
2762 
2763   if (reachable(src)) {
2764     Assembler::vpaddb(dst, nds, as_Address(src), vector_len);
2765   } else {
2766     lea(rscratch, src);
2767     Assembler::vpaddb(dst, nds, Address(rscratch, 0), vector_len);
2768   }
2769 }
2770 
2771 void MacroAssembler::vpaddd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
2772   assert(UseAVX > 0, "requires some form of AVX");
2773   assert(rscratch != noreg || always_reachable(src), "missing");
2774 
2775   if (reachable(src)) {
2776     Assembler::vpaddd(dst, nds, as_Address(src), vector_len);
2777   } else {
2778     lea(rscratch, src);
2779     Assembler::vpaddd(dst, nds, Address(rscratch, 0), vector_len);
2780   }
2781 }
2782 
2783 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len, Register rscratch) {
2784   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
2785   assert(rscratch != noreg || always_reachable(negate_field), "missing");
2786 
2787   vandps(dst, nds, negate_field, vector_len, rscratch);
2788 }
2789 
2790 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len, Register rscratch) {
2791   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
2792   assert(rscratch != noreg || always_reachable(negate_field), "missing");
2793 
2794   vandpd(dst, nds, negate_field, vector_len, rscratch);
2795 }
2796 
2797 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
2798   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2799   Assembler::vpaddb(dst, nds, src, vector_len);
2800 }
2801 
2802 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
2803   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2804   Assembler::vpaddb(dst, nds, src, vector_len);
2805 }
2806 
2807 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
2808   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2809   Assembler::vpaddw(dst, nds, src, vector_len);
2810 }
2811 
2812 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
2813   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2814   Assembler::vpaddw(dst, nds, src, vector_len);
2815 }
2816 
2817 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
2818   assert(rscratch != noreg || always_reachable(src), "missing");
2819 
2820   if (reachable(src)) {
2821     Assembler::vpand(dst, nds, as_Address(src), vector_len);
2822   } else {
2823     lea(rscratch, src);
2824     Assembler::vpand(dst, nds, Address(rscratch, 0), vector_len);
2825   }
2826 }
2827 
2828 void MacroAssembler::vpbroadcastd(XMMRegister dst, AddressLiteral src, int vector_len, Register rscratch) {
2829   assert(rscratch != noreg || always_reachable(src), "missing");
2830 
2831   if (reachable(src)) {
2832     Assembler::vpbroadcastd(dst, as_Address(src), vector_len);
2833   } else {
2834     lea(rscratch, src);
2835     Assembler::vpbroadcastd(dst, Address(rscratch, 0), vector_len);
2836   }
2837 }
2838 
2839 void MacroAssembler::vbroadcasti128(XMMRegister dst, AddressLiteral src, int vector_len, Register rscratch) {
2840   assert(rscratch != noreg || always_reachable(src), "missing");
2841 
2842   if (reachable(src)) {
2843     Assembler::vbroadcasti128(dst, as_Address(src), vector_len);
2844   } else {
2845     lea(rscratch, src);
2846     Assembler::vbroadcasti128(dst, Address(rscratch, 0), vector_len);
2847   }
2848 }
2849 
2850 void MacroAssembler::vpbroadcastq(XMMRegister dst, AddressLiteral src, int vector_len, Register rscratch) {
2851   assert(rscratch != noreg || always_reachable(src), "missing");
2852 
2853   if (reachable(src)) {
2854     Assembler::vpbroadcastq(dst, as_Address(src), vector_len);
2855   } else {
2856     lea(rscratch, src);
2857     Assembler::vpbroadcastq(dst, Address(rscratch, 0), vector_len);
2858   }
2859 }
2860 
2861 void MacroAssembler::vbroadcastsd(XMMRegister dst, AddressLiteral src, int vector_len, Register rscratch) {
2862   assert(rscratch != noreg || always_reachable(src), "missing");
2863 
2864   if (reachable(src)) {
2865     Assembler::vbroadcastsd(dst, as_Address(src), vector_len);
2866   } else {
2867     lea(rscratch, src);
2868     Assembler::vbroadcastsd(dst, Address(rscratch, 0), vector_len);
2869   }
2870 }
2871 
2872 void MacroAssembler::vbroadcastss(XMMRegister dst, AddressLiteral src, int vector_len, Register rscratch) {
2873   assert(rscratch != noreg || always_reachable(src), "missing");
2874 
2875   if (reachable(src)) {
2876     Assembler::vbroadcastss(dst, as_Address(src), vector_len);
2877   } else {
2878     lea(rscratch, src);
2879     Assembler::vbroadcastss(dst, Address(rscratch, 0), vector_len);
2880   }
2881 }
2882 
2883 // Vector float blend
2884 // vblendvps(XMMRegister dst, XMMRegister nds, XMMRegister src, XMMRegister mask, int vector_len, bool compute_mask = true, XMMRegister scratch = xnoreg)
2885 void MacroAssembler::vblendvps(XMMRegister dst, XMMRegister src1, XMMRegister src2, XMMRegister mask, int vector_len, bool compute_mask, XMMRegister scratch) {
2886   // WARN: Allow dst == (src1|src2), mask == scratch
2887   bool blend_emulation = EnableX86ECoreOpts && UseAVX > 1;
2888   bool scratch_available = scratch != xnoreg && scratch != src1 && scratch != src2 && scratch != dst;
2889   bool dst_available = dst != mask && (dst != src1 || dst != src2);
2890   if (blend_emulation && scratch_available && dst_available) {
2891     if (compute_mask) {
2892       vpsrad(scratch, mask, 32, vector_len);
2893       mask = scratch;
2894     }
2895     if (dst == src1) {
2896       vpandn(dst,     mask, src1, vector_len); // if mask == 0, src1
2897       vpand (scratch, mask, src2, vector_len); // if mask == 1, src2
2898     } else {
2899       vpand (dst,     mask, src2, vector_len); // if mask == 1, src2
2900       vpandn(scratch, mask, src1, vector_len); // if mask == 0, src1
2901     }
2902     vpor(dst, dst, scratch, vector_len);
2903   } else {
2904     Assembler::vblendvps(dst, src1, src2, mask, vector_len);
2905   }
2906 }
2907 
2908 // vblendvpd(XMMRegister dst, XMMRegister nds, XMMRegister src, XMMRegister mask, int vector_len, bool compute_mask = true, XMMRegister scratch = xnoreg)
2909 void MacroAssembler::vblendvpd(XMMRegister dst, XMMRegister src1, XMMRegister src2, XMMRegister mask, int vector_len, bool compute_mask, XMMRegister scratch) {
2910   // WARN: Allow dst == (src1|src2), mask == scratch
2911   bool blend_emulation = EnableX86ECoreOpts && UseAVX > 1;
2912   bool scratch_available = scratch != xnoreg && scratch != src1 && scratch != src2 && scratch != dst && (!compute_mask || scratch != mask);
2913   bool dst_available = dst != mask && (dst != src1 || dst != src2);
2914   if (blend_emulation && scratch_available && dst_available) {
2915     if (compute_mask) {
2916       vpxor(scratch, scratch, scratch, vector_len);
2917       vpcmpgtq(scratch, scratch, mask, vector_len);
2918       mask = scratch;
2919     }
2920     if (dst == src1) {
2921       vpandn(dst,     mask, src1, vector_len); // if mask == 0, src
2922       vpand (scratch, mask, src2, vector_len); // if mask == 1, src2
2923     } else {
2924       vpand (dst,     mask, src2, vector_len); // if mask == 1, src2
2925       vpandn(scratch, mask, src1, vector_len); // if mask == 0, src
2926     }
2927     vpor(dst, dst, scratch, vector_len);
2928   } else {
2929     Assembler::vblendvpd(dst, src1, src2, mask, vector_len);
2930   }
2931 }
2932 
2933 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
2934   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2935   Assembler::vpcmpeqb(dst, nds, src, vector_len);
2936 }
2937 
2938 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister src1, Address src2, int vector_len) {
2939   assert(((dst->encoding() < 16 && src1->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2940   Assembler::vpcmpeqb(dst, src1, src2, vector_len);
2941 }
2942 
2943 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
2944   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2945   Assembler::vpcmpeqw(dst, nds, src, vector_len);
2946 }
2947 
2948 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
2949   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
2950   Assembler::vpcmpeqw(dst, nds, src, vector_len);
2951 }
2952 
2953 void MacroAssembler::evpcmpeqd(KRegister kdst, KRegister mask, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
2954   assert(rscratch != noreg || always_reachable(src), "missing");
2955 
2956   if (reachable(src)) {
2957     Assembler::evpcmpeqd(kdst, mask, nds, as_Address(src), vector_len);
2958   } else {
2959     lea(rscratch, src);
2960     Assembler::evpcmpeqd(kdst, mask, nds, Address(rscratch, 0), vector_len);
2961   }
2962 }
2963 
2964 void MacroAssembler::evpcmpd(KRegister kdst, KRegister mask, XMMRegister nds, AddressLiteral src,
2965                              int comparison, bool is_signed, int vector_len, Register rscratch) {
2966   assert(rscratch != noreg || always_reachable(src), "missing");
2967 
2968   if (reachable(src)) {
2969     Assembler::evpcmpd(kdst, mask, nds, as_Address(src), comparison, is_signed, vector_len);
2970   } else {
2971     lea(rscratch, src);
2972     Assembler::evpcmpd(kdst, mask, nds, Address(rscratch, 0), comparison, is_signed, vector_len);
2973   }
2974 }
2975 
2976 void MacroAssembler::evpcmpq(KRegister kdst, KRegister mask, XMMRegister nds, AddressLiteral src,
2977                              int comparison, bool is_signed, int vector_len, Register rscratch) {
2978   assert(rscratch != noreg || always_reachable(src), "missing");
2979 
2980   if (reachable(src)) {
2981     Assembler::evpcmpq(kdst, mask, nds, as_Address(src), comparison, is_signed, vector_len);
2982   } else {
2983     lea(rscratch, src);
2984     Assembler::evpcmpq(kdst, mask, nds, Address(rscratch, 0), comparison, is_signed, vector_len);
2985   }
2986 }
2987 
2988 void MacroAssembler::evpcmpb(KRegister kdst, KRegister mask, XMMRegister nds, AddressLiteral src,
2989                              int comparison, bool is_signed, int vector_len, Register rscratch) {
2990   assert(rscratch != noreg || always_reachable(src), "missing");
2991 
2992   if (reachable(src)) {
2993     Assembler::evpcmpb(kdst, mask, nds, as_Address(src), comparison, is_signed, vector_len);
2994   } else {
2995     lea(rscratch, src);
2996     Assembler::evpcmpb(kdst, mask, nds, Address(rscratch, 0), comparison, is_signed, vector_len);
2997   }
2998 }
2999 
3000 void MacroAssembler::evpcmpw(KRegister kdst, KRegister mask, XMMRegister nds, AddressLiteral src,
3001                              int comparison, bool is_signed, int vector_len, Register rscratch) {
3002   assert(rscratch != noreg || always_reachable(src), "missing");
3003 
3004   if (reachable(src)) {
3005     Assembler::evpcmpw(kdst, mask, nds, as_Address(src), comparison, is_signed, vector_len);
3006   } else {
3007     lea(rscratch, src);
3008     Assembler::evpcmpw(kdst, mask, nds, Address(rscratch, 0), comparison, is_signed, vector_len);
3009   }
3010 }
3011 
3012 void MacroAssembler::vpcmpCC(XMMRegister dst, XMMRegister nds, XMMRegister src, int cond_encoding, Width width, int vector_len) {
3013   if (width == Assembler::Q) {
3014     Assembler::vpcmpCCq(dst, nds, src, cond_encoding, vector_len);
3015   } else {
3016     Assembler::vpcmpCCbwd(dst, nds, src, cond_encoding, vector_len);
3017   }
3018 }
3019 
3020 void MacroAssembler::vpcmpCCW(XMMRegister dst, XMMRegister nds, XMMRegister src, XMMRegister xtmp, ComparisonPredicate cond, Width width, int vector_len) {
3021   int eq_cond_enc = 0x29;
3022   int gt_cond_enc = 0x37;
3023   if (width != Assembler::Q) {
3024     eq_cond_enc = 0x74 + width;
3025     gt_cond_enc = 0x64 + width;
3026   }
3027   switch (cond) {
3028   case eq:
3029     vpcmpCC(dst, nds, src, eq_cond_enc, width, vector_len);
3030     break;
3031   case neq:
3032     vpcmpCC(dst, nds, src, eq_cond_enc, width, vector_len);
3033     vallones(xtmp, vector_len);
3034     vpxor(dst, xtmp, dst, vector_len);
3035     break;
3036   case le:
3037     vpcmpCC(dst, nds, src, gt_cond_enc, width, vector_len);
3038     vallones(xtmp, vector_len);
3039     vpxor(dst, xtmp, dst, vector_len);
3040     break;
3041   case nlt:
3042     vpcmpCC(dst, src, nds, gt_cond_enc, width, vector_len);
3043     vallones(xtmp, vector_len);
3044     vpxor(dst, xtmp, dst, vector_len);
3045     break;
3046   case lt:
3047     vpcmpCC(dst, src, nds, gt_cond_enc, width, vector_len);
3048     break;
3049   case nle:
3050     vpcmpCC(dst, nds, src, gt_cond_enc, width, vector_len);
3051     break;
3052   default:
3053     assert(false, "Should not reach here");
3054   }
3055 }
3056 
3057 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
3058   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3059   Assembler::vpmovzxbw(dst, src, vector_len);
3060 }
3061 
3062 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src, int vector_len) {
3063   assert((src->encoding() < 16),"XMM register should be 0-15");
3064   Assembler::vpmovmskb(dst, src, vector_len);
3065 }
3066 
3067 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3068   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3069   Assembler::vpmullw(dst, nds, src, vector_len);
3070 }
3071 
3072 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3073   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3074   Assembler::vpmullw(dst, nds, src, vector_len);
3075 }
3076 
3077 void MacroAssembler::vpmulld(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
3078   assert((UseAVX > 0), "AVX support is needed");
3079   assert(rscratch != noreg || always_reachable(src), "missing");
3080 
3081   if (reachable(src)) {
3082     Assembler::vpmulld(dst, nds, as_Address(src), vector_len);
3083   } else {
3084     lea(rscratch, src);
3085     Assembler::vpmulld(dst, nds, Address(rscratch, 0), vector_len);
3086   }
3087 }
3088 
3089 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3090   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3091   Assembler::vpsubb(dst, nds, src, vector_len);
3092 }
3093 
3094 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3095   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3096   Assembler::vpsubb(dst, nds, src, vector_len);
3097 }
3098 
3099 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3100   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3101   Assembler::vpsubw(dst, nds, src, vector_len);
3102 }
3103 
3104 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3105   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3106   Assembler::vpsubw(dst, nds, src, vector_len);
3107 }
3108 
3109 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3110   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3111   Assembler::vpsraw(dst, nds, shift, vector_len);
3112 }
3113 
3114 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3115   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3116   Assembler::vpsraw(dst, nds, shift, vector_len);
3117 }
3118 
3119 void MacroAssembler::evpsraq(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3120   assert(UseAVX > 2,"");
3121   if (!VM_Version::supports_avx512vl() && vector_len < 2) {
3122      vector_len = 2;
3123   }
3124   Assembler::evpsraq(dst, nds, shift, vector_len);
3125 }
3126 
3127 void MacroAssembler::evpsraq(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3128   assert(UseAVX > 2,"");
3129   if (!VM_Version::supports_avx512vl() && vector_len < 2) {
3130      vector_len = 2;
3131   }
3132   Assembler::evpsraq(dst, nds, shift, vector_len);
3133 }
3134 
3135 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3136   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3137   Assembler::vpsrlw(dst, nds, shift, vector_len);
3138 }
3139 
3140 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3141   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3142   Assembler::vpsrlw(dst, nds, shift, vector_len);
3143 }
3144 
3145 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3146   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3147   Assembler::vpsllw(dst, nds, shift, vector_len);
3148 }
3149 
3150 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3151   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3152   Assembler::vpsllw(dst, nds, shift, vector_len);
3153 }
3154 
3155 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
3156   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
3157   Assembler::vptest(dst, src);
3158 }
3159 
3160 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
3161   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3162   Assembler::punpcklbw(dst, src);
3163 }
3164 
3165 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
3166   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3167   Assembler::pshufd(dst, src, mode);
3168 }
3169 
3170 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
3171   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3172   Assembler::pshuflw(dst, src, mode);
3173 }
3174 
3175 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
3176   assert(rscratch != noreg || always_reachable(src), "missing");
3177 
3178   if (reachable(src)) {
3179     vandpd(dst, nds, as_Address(src), vector_len);
3180   } else {
3181     lea(rscratch, src);
3182     vandpd(dst, nds, Address(rscratch, 0), vector_len);
3183   }
3184 }
3185 
3186 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
3187   assert(rscratch != noreg || always_reachable(src), "missing");
3188 
3189   if (reachable(src)) {
3190     vandps(dst, nds, as_Address(src), vector_len);
3191   } else {
3192     lea(rscratch, src);
3193     vandps(dst, nds, Address(rscratch, 0), vector_len);
3194   }
3195 }
3196 
3197 void MacroAssembler::evpord(XMMRegister dst, KRegister mask, XMMRegister nds, AddressLiteral src,
3198                             bool merge, int vector_len, Register rscratch) {
3199   assert(rscratch != noreg || always_reachable(src), "missing");
3200 
3201   if (reachable(src)) {
3202     Assembler::evpord(dst, mask, nds, as_Address(src), merge, vector_len);
3203   } else {
3204     lea(rscratch, src);
3205     Assembler::evpord(dst, mask, nds, Address(rscratch, 0), merge, vector_len);
3206   }
3207 }
3208 
3209 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src, Register rscratch) {
3210   assert(rscratch != noreg || always_reachable(src), "missing");
3211 
3212   if (reachable(src)) {
3213     vdivsd(dst, nds, as_Address(src));
3214   } else {
3215     lea(rscratch, src);
3216     vdivsd(dst, nds, Address(rscratch, 0));
3217   }
3218 }
3219 
3220 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src, Register rscratch) {
3221   assert(rscratch != noreg || always_reachable(src), "missing");
3222 
3223   if (reachable(src)) {
3224     vdivss(dst, nds, as_Address(src));
3225   } else {
3226     lea(rscratch, src);
3227     vdivss(dst, nds, Address(rscratch, 0));
3228   }
3229 }
3230 
3231 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src, Register rscratch) {
3232   assert(rscratch != noreg || always_reachable(src), "missing");
3233 
3234   if (reachable(src)) {
3235     vmulsd(dst, nds, as_Address(src));
3236   } else {
3237     lea(rscratch, src);
3238     vmulsd(dst, nds, Address(rscratch, 0));
3239   }
3240 }
3241 
3242 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src, Register rscratch) {
3243   assert(rscratch != noreg || always_reachable(src), "missing");
3244 
3245   if (reachable(src)) {
3246     vmulss(dst, nds, as_Address(src));
3247   } else {
3248     lea(rscratch, src);
3249     vmulss(dst, nds, Address(rscratch, 0));
3250   }
3251 }
3252 
3253 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src, Register rscratch) {
3254   assert(rscratch != noreg || always_reachable(src), "missing");
3255 
3256   if (reachable(src)) {
3257     vsubsd(dst, nds, as_Address(src));
3258   } else {
3259     lea(rscratch, src);
3260     vsubsd(dst, nds, Address(rscratch, 0));
3261   }
3262 }
3263 
3264 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src, Register rscratch) {
3265   assert(rscratch != noreg || always_reachable(src), "missing");
3266 
3267   if (reachable(src)) {
3268     vsubss(dst, nds, as_Address(src));
3269   } else {
3270     lea(rscratch, src);
3271     vsubss(dst, nds, Address(rscratch, 0));
3272   }
3273 }
3274 
3275 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src, Register rscratch) {
3276   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
3277   assert(rscratch != noreg || always_reachable(src), "missing");
3278 
3279   vxorps(dst, nds, src, Assembler::AVX_128bit, rscratch);
3280 }
3281 
3282 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src, Register rscratch) {
3283   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
3284   assert(rscratch != noreg || always_reachable(src), "missing");
3285 
3286   vxorpd(dst, nds, src, Assembler::AVX_128bit, rscratch);
3287 }
3288 
3289 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
3290   assert(rscratch != noreg || always_reachable(src), "missing");
3291 
3292   if (reachable(src)) {
3293     vxorpd(dst, nds, as_Address(src), vector_len);
3294   } else {
3295     lea(rscratch, src);
3296     vxorpd(dst, nds, Address(rscratch, 0), vector_len);
3297   }
3298 }
3299 
3300 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
3301   assert(rscratch != noreg || always_reachable(src), "missing");
3302 
3303   if (reachable(src)) {
3304     vxorps(dst, nds, as_Address(src), vector_len);
3305   } else {
3306     lea(rscratch, src);
3307     vxorps(dst, nds, Address(rscratch, 0), vector_len);
3308   }
3309 }
3310 
3311 void MacroAssembler::vpxor(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
3312   assert(rscratch != noreg || always_reachable(src), "missing");
3313 
3314   if (UseAVX > 1 || (vector_len < 1)) {
3315     if (reachable(src)) {
3316       Assembler::vpxor(dst, nds, as_Address(src), vector_len);
3317     } else {
3318       lea(rscratch, src);
3319       Assembler::vpxor(dst, nds, Address(rscratch, 0), vector_len);
3320     }
3321   } else {
3322     MacroAssembler::vxorpd(dst, nds, src, vector_len, rscratch);
3323   }
3324 }
3325 
3326 void MacroAssembler::vpermd(XMMRegister dst,  XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
3327   assert(rscratch != noreg || always_reachable(src), "missing");
3328 
3329   if (reachable(src)) {
3330     Assembler::vpermd(dst, nds, as_Address(src), vector_len);
3331   } else {
3332     lea(rscratch, src);
3333     Assembler::vpermd(dst, nds, Address(rscratch, 0), vector_len);
3334   }
3335 }
3336 
3337 void MacroAssembler::clear_jobject_tag(Register possibly_non_local) {
3338   const int32_t inverted_mask = ~static_cast<int32_t>(JNIHandles::tag_mask);
3339   STATIC_ASSERT(inverted_mask == -4); // otherwise check this code
3340   // The inverted mask is sign-extended
3341   andptr(possibly_non_local, inverted_mask);
3342 }
3343 
3344 void MacroAssembler::resolve_jobject(Register value,
3345                                      Register tmp) {
3346   Register thread = r15_thread;
3347   assert_different_registers(value, thread, tmp);
3348   Label done, tagged, weak_tagged;
3349   testptr(value, value);
3350   jcc(Assembler::zero, done);           // Use null as-is.
3351   testptr(value, JNIHandles::tag_mask); // Test for tag.
3352   jcc(Assembler::notZero, tagged);
3353 
3354   // Resolve local handle
3355   access_load_at(T_OBJECT, IN_NATIVE | AS_RAW, value, Address(value, 0), tmp);
3356   verify_oop(value);
3357   jmp(done);
3358 
3359   bind(tagged);
3360   testptr(value, JNIHandles::TypeTag::weak_global); // Test for weak tag.
3361   jcc(Assembler::notZero, weak_tagged);
3362 
3363   // Resolve global handle
3364   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, -JNIHandles::TypeTag::global), tmp);
3365   verify_oop(value);
3366   jmp(done);
3367 
3368   bind(weak_tagged);
3369   // Resolve jweak.
3370   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
3371                  value, Address(value, -JNIHandles::TypeTag::weak_global), tmp);
3372   verify_oop(value);
3373 
3374   bind(done);
3375 }
3376 
3377 void MacroAssembler::resolve_global_jobject(Register value,
3378                                             Register tmp) {
3379   Register thread = r15_thread;
3380   assert_different_registers(value, thread, tmp);
3381   Label done;
3382 
3383   testptr(value, value);
3384   jcc(Assembler::zero, done);           // Use null as-is.
3385 
3386 #ifdef ASSERT
3387   {
3388     Label valid_global_tag;
3389     testptr(value, JNIHandles::TypeTag::global); // Test for global tag.
3390     jcc(Assembler::notZero, valid_global_tag);
3391     stop("non global jobject using resolve_global_jobject");
3392     bind(valid_global_tag);
3393   }
3394 #endif
3395 
3396   // Resolve global handle
3397   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, -JNIHandles::TypeTag::global), tmp);
3398   verify_oop(value);
3399 
3400   bind(done);
3401 }
3402 
3403 void MacroAssembler::subptr(Register dst, int32_t imm32) {
3404   subq(dst, imm32);
3405 }
3406 
3407 // Force generation of a 4 byte immediate value even if it fits into 8bit
3408 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
3409   subq_imm32(dst, imm32);
3410 }
3411 
3412 void MacroAssembler::subptr(Register dst, Register src) {
3413   subq(dst, src);
3414 }
3415 
3416 // C++ bool manipulation
3417 void MacroAssembler::testbool(Register dst) {
3418   if(sizeof(bool) == 1)
3419     testb(dst, 0xff);
3420   else if(sizeof(bool) == 2) {
3421     // testw implementation needed for two byte bools
3422     ShouldNotReachHere();
3423   } else if(sizeof(bool) == 4)
3424     testl(dst, dst);
3425   else
3426     // unsupported
3427     ShouldNotReachHere();
3428 }
3429 
3430 void MacroAssembler::testptr(Register dst, Register src) {
3431   testq(dst, src);
3432 }
3433 
3434 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
3435 void MacroAssembler::tlab_allocate(Register obj,
3436                                    Register var_size_in_bytes,
3437                                    int con_size_in_bytes,
3438                                    Register t1,
3439                                    Register t2,
3440                                    Label& slow_case) {
3441   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
3442   bs->tlab_allocate(this, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
3443 }
3444 
3445 RegSet MacroAssembler::call_clobbered_gp_registers() {
3446   RegSet regs;
3447   regs += RegSet::of(rax, rcx, rdx);
3448 #ifndef _WINDOWS
3449   regs += RegSet::of(rsi, rdi);
3450 #endif
3451   regs += RegSet::range(r8, r11);
3452   if (UseAPX) {
3453     regs += RegSet::range(r16, as_Register(Register::number_of_registers - 1));
3454   }
3455   return regs;
3456 }
3457 
3458 XMMRegSet MacroAssembler::call_clobbered_xmm_registers() {
3459   int num_xmm_registers = XMMRegister::available_xmm_registers();
3460 #if defined(_WINDOWS)
3461   XMMRegSet result = XMMRegSet::range(xmm0, xmm5);
3462   if (num_xmm_registers > 16) {
3463      result += XMMRegSet::range(xmm16, as_XMMRegister(num_xmm_registers - 1));
3464   }
3465   return result;
3466 #else
3467   return XMMRegSet::range(xmm0, as_XMMRegister(num_xmm_registers - 1));
3468 #endif
3469 }
3470 
3471 // C1 only ever uses the first double/float of the XMM register.
3472 static int xmm_save_size() { return sizeof(double); }
3473 
3474 static void save_xmm_register(MacroAssembler* masm, int offset, XMMRegister reg) {
3475   masm->movdbl(Address(rsp, offset), reg);
3476 }
3477 
3478 static void restore_xmm_register(MacroAssembler* masm, int offset, XMMRegister reg) {
3479   masm->movdbl(reg, Address(rsp, offset));
3480 }
3481 
3482 static int register_section_sizes(RegSet gp_registers, XMMRegSet xmm_registers,
3483                                   bool save_fpu, int& gp_area_size, int& xmm_area_size) {
3484 
3485   gp_area_size = align_up(gp_registers.size() * Register::max_slots_per_register * VMRegImpl::stack_slot_size,
3486                          StackAlignmentInBytes);
3487   xmm_area_size = save_fpu ? xmm_registers.size() * xmm_save_size() : 0;
3488 
3489   return gp_area_size + xmm_area_size;
3490 }
3491 
3492 void MacroAssembler::push_call_clobbered_registers_except(RegSet exclude, bool save_fpu) {
3493   block_comment("push_call_clobbered_registers start");
3494   // Regular registers
3495   RegSet gp_registers_to_push = call_clobbered_gp_registers() - exclude;
3496 
3497   int gp_area_size;
3498   int xmm_area_size;
3499   int total_save_size = register_section_sizes(gp_registers_to_push, call_clobbered_xmm_registers(), save_fpu,
3500                                                gp_area_size, xmm_area_size);
3501   subptr(rsp, total_save_size);
3502 
3503   push_set(gp_registers_to_push, 0);
3504 
3505   if (save_fpu) {
3506     push_set(call_clobbered_xmm_registers(), gp_area_size);
3507   }
3508 
3509   block_comment("push_call_clobbered_registers end");
3510 }
3511 
3512 void MacroAssembler::pop_call_clobbered_registers_except(RegSet exclude, bool restore_fpu) {
3513   block_comment("pop_call_clobbered_registers start");
3514 
3515   RegSet gp_registers_to_pop = call_clobbered_gp_registers() - exclude;
3516 
3517   int gp_area_size;
3518   int xmm_area_size;
3519   int total_save_size = register_section_sizes(gp_registers_to_pop, call_clobbered_xmm_registers(), restore_fpu,
3520                                                gp_area_size, xmm_area_size);
3521 
3522   if (restore_fpu) {
3523     pop_set(call_clobbered_xmm_registers(), gp_area_size);
3524   }
3525 
3526   pop_set(gp_registers_to_pop, 0);
3527 
3528   addptr(rsp, total_save_size);
3529 
3530   vzeroupper();
3531 
3532   block_comment("pop_call_clobbered_registers end");
3533 }
3534 
3535 void MacroAssembler::push_set(XMMRegSet set, int offset) {
3536   assert(is_aligned(set.size() * xmm_save_size(), StackAlignmentInBytes), "must be");
3537   int spill_offset = offset;
3538 
3539   for (RegSetIterator<XMMRegister> it = set.begin(); *it != xnoreg; ++it) {
3540     save_xmm_register(this, spill_offset, *it);
3541     spill_offset += xmm_save_size();
3542   }
3543 }
3544 
3545 void MacroAssembler::pop_set(XMMRegSet set, int offset) {
3546   int restore_size = set.size() * xmm_save_size();
3547   assert(is_aligned(restore_size, StackAlignmentInBytes), "must be");
3548 
3549   int restore_offset = offset + restore_size - xmm_save_size();
3550 
3551   for (ReverseRegSetIterator<XMMRegister> it = set.rbegin(); *it != xnoreg; ++it) {
3552     restore_xmm_register(this, restore_offset, *it);
3553     restore_offset -= xmm_save_size();
3554   }
3555 }
3556 
3557 void MacroAssembler::push_set(RegSet set, int offset) {
3558   int spill_offset;
3559   if (offset == -1) {
3560     int register_push_size = set.size() * Register::max_slots_per_register * VMRegImpl::stack_slot_size;
3561     int aligned_size = align_up(register_push_size, StackAlignmentInBytes);
3562     subptr(rsp, aligned_size);
3563     spill_offset = 0;
3564   } else {
3565     spill_offset = offset;
3566   }
3567 
3568   for (RegSetIterator<Register> it = set.begin(); *it != noreg; ++it) {
3569     movptr(Address(rsp, spill_offset), *it);
3570     spill_offset += Register::max_slots_per_register * VMRegImpl::stack_slot_size;
3571   }
3572 }
3573 
3574 void MacroAssembler::pop_set(RegSet set, int offset) {
3575 
3576   int gp_reg_size = Register::max_slots_per_register * VMRegImpl::stack_slot_size;
3577   int restore_size = set.size() * gp_reg_size;
3578   int aligned_size = align_up(restore_size, StackAlignmentInBytes);
3579 
3580   int restore_offset;
3581   if (offset == -1) {
3582     restore_offset = restore_size - gp_reg_size;
3583   } else {
3584     restore_offset = offset + restore_size - gp_reg_size;
3585   }
3586   for (ReverseRegSetIterator<Register> it = set.rbegin(); *it != noreg; ++it) {
3587     movptr(*it, Address(rsp, restore_offset));
3588     restore_offset -= gp_reg_size;
3589   }
3590 
3591   if (offset == -1) {
3592     addptr(rsp, aligned_size);
3593   }
3594 }
3595 
3596 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
3597 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
3598   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
3599   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
3600   Label done;
3601 
3602   testptr(length_in_bytes, length_in_bytes);
3603   jcc(Assembler::zero, done);
3604 
3605   // initialize topmost word, divide index by 2, check if odd and test if zero
3606   // note: for the remaining code to work, index must be a multiple of BytesPerWord
3607 #ifdef ASSERT
3608   {
3609     Label L;
3610     testptr(length_in_bytes, BytesPerWord - 1);
3611     jcc(Assembler::zero, L);
3612     stop("length must be a multiple of BytesPerWord");
3613     bind(L);
3614   }
3615 #endif
3616   Register index = length_in_bytes;
3617   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
3618   if (UseIncDec) {
3619     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
3620   } else {
3621     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
3622     shrptr(index, 1);
3623   }
3624 
3625   // initialize remaining object fields: index is a multiple of 2 now
3626   {
3627     Label loop;
3628     bind(loop);
3629     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
3630     decrement(index);
3631     jcc(Assembler::notZero, loop);
3632   }
3633 
3634   bind(done);
3635 }
3636 
3637 // Look up the method for a megamorphic invokeinterface call.
3638 // The target method is determined by <intf_klass, itable_index>.
3639 // The receiver klass is in recv_klass.
3640 // On success, the result will be in method_result, and execution falls through.
3641 // On failure, execution transfers to the given label.
3642 void MacroAssembler::lookup_interface_method(Register recv_klass,
3643                                              Register intf_klass,
3644                                              RegisterOrConstant itable_index,
3645                                              Register method_result,
3646                                              Register scan_temp,
3647                                              Label& L_no_such_interface,
3648                                              bool return_method) {
3649   assert_different_registers(recv_klass, intf_klass, scan_temp);
3650   assert_different_registers(method_result, intf_klass, scan_temp);
3651   assert(recv_klass != method_result || !return_method,
3652          "recv_klass can be destroyed when method isn't needed");
3653 
3654   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
3655          "caller must use same register for non-constant itable index as for method");
3656 
3657   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
3658   int vtable_base = in_bytes(Klass::vtable_start_offset());
3659   int itentry_off = in_bytes(itableMethodEntry::method_offset());
3660   int scan_step   = itableOffsetEntry::size() * wordSize;
3661   int vte_size    = vtableEntry::size_in_bytes();
3662   Address::ScaleFactor times_vte_scale = Address::times_ptr;
3663   assert(vte_size == wordSize, "else adjust times_vte_scale");
3664 
3665   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
3666 
3667   // Could store the aligned, prescaled offset in the klass.
3668   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
3669 
3670   if (return_method) {
3671     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
3672     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
3673     lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
3674   }
3675 
3676   // for (scan = klass->itable(); scan->interface() != nullptr; scan += scan_step) {
3677   //   if (scan->interface() == intf) {
3678   //     result = (klass + scan->offset() + itable_index);
3679   //   }
3680   // }
3681   Label search, found_method;
3682 
3683   for (int peel = 1; peel >= 0; peel--) {
3684     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset()));
3685     cmpptr(intf_klass, method_result);
3686 
3687     if (peel) {
3688       jccb(Assembler::equal, found_method);
3689     } else {
3690       jccb(Assembler::notEqual, search);
3691       // (invert the test to fall through to found_method...)
3692     }
3693 
3694     if (!peel)  break;
3695 
3696     bind(search);
3697 
3698     // Check that the previous entry is non-null.  A null entry means that
3699     // the receiver class doesn't implement the interface, and wasn't the
3700     // same as when the caller was compiled.
3701     testptr(method_result, method_result);
3702     jcc(Assembler::zero, L_no_such_interface);
3703     addptr(scan_temp, scan_step);
3704   }
3705 
3706   bind(found_method);
3707 
3708   if (return_method) {
3709     // Got a hit.
3710     movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset()));
3711     movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
3712   }
3713 }
3714 
3715 // Look up the method for a megamorphic invokeinterface call in a single pass over itable:
3716 // - check recv_klass (actual object class) is a subtype of resolved_klass from CompiledICData
3717 // - find a holder_klass (class that implements the method) vtable offset and get the method from vtable by index
3718 // The target method is determined by <holder_klass, itable_index>.
3719 // The receiver klass is in recv_klass.
3720 // On success, the result will be in method_result, and execution falls through.
3721 // On failure, execution transfers to the given label.
3722 void MacroAssembler::lookup_interface_method_stub(Register recv_klass,
3723                                                   Register holder_klass,
3724                                                   Register resolved_klass,
3725                                                   Register method_result,
3726                                                   Register scan_temp,
3727                                                   Register temp_reg2,
3728                                                   Register receiver,
3729                                                   int itable_index,
3730                                                   Label& L_no_such_interface) {
3731   assert_different_registers(recv_klass, method_result, holder_klass, resolved_klass, scan_temp, temp_reg2, receiver);
3732   Register temp_itbl_klass = method_result;
3733   Register temp_reg = (temp_reg2 == noreg ? recv_klass : temp_reg2); // reuse recv_klass register on 32-bit x86 impl
3734 
3735   int vtable_base = in_bytes(Klass::vtable_start_offset());
3736   int itentry_off = in_bytes(itableMethodEntry::method_offset());
3737   int scan_step = itableOffsetEntry::size() * wordSize;
3738   int vte_size = vtableEntry::size_in_bytes();
3739   int ioffset = in_bytes(itableOffsetEntry::interface_offset());
3740   int ooffset = in_bytes(itableOffsetEntry::offset_offset());
3741   Address::ScaleFactor times_vte_scale = Address::times_ptr;
3742   assert(vte_size == wordSize, "adjust times_vte_scale");
3743 
3744   Label L_loop_scan_resolved_entry, L_resolved_found, L_holder_found;
3745 
3746   // temp_itbl_klass = recv_klass.itable[0]
3747   // scan_temp = &recv_klass.itable[0] + step
3748   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
3749   movptr(temp_itbl_klass, Address(recv_klass, scan_temp, times_vte_scale, vtable_base + ioffset));
3750   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base + ioffset + scan_step));
3751   xorptr(temp_reg, temp_reg);
3752 
3753   // Initial checks:
3754   //   - if (holder_klass != resolved_klass), go to "scan for resolved"
3755   //   - if (itable[0] == 0), no such interface
3756   //   - if (itable[0] == holder_klass), shortcut to "holder found"
3757   cmpptr(holder_klass, resolved_klass);
3758   jccb(Assembler::notEqual, L_loop_scan_resolved_entry);
3759   testptr(temp_itbl_klass, temp_itbl_klass);
3760   jccb(Assembler::zero, L_no_such_interface);
3761   cmpptr(holder_klass, temp_itbl_klass);
3762   jccb(Assembler::equal, L_holder_found);
3763 
3764   // Loop: Look for holder_klass record in itable
3765   //   do {
3766   //     tmp = itable[index];
3767   //     index += step;
3768   //     if (tmp == holder_klass) {
3769   //       goto L_holder_found; // Found!
3770   //     }
3771   //   } while (tmp != 0);
3772   //   goto L_no_such_interface // Not found.
3773   Label L_scan_holder;
3774   bind(L_scan_holder);
3775     movptr(temp_itbl_klass, Address(scan_temp, 0));
3776     addptr(scan_temp, scan_step);
3777     cmpptr(holder_klass, temp_itbl_klass);
3778     jccb(Assembler::equal, L_holder_found);
3779     testptr(temp_itbl_klass, temp_itbl_klass);
3780     jccb(Assembler::notZero, L_scan_holder);
3781 
3782   jmpb(L_no_such_interface);
3783 
3784   // Loop: Look for resolved_class record in itable
3785   //   do {
3786   //     tmp = itable[index];
3787   //     index += step;
3788   //     if (tmp == holder_klass) {
3789   //        // Also check if we have met a holder klass
3790   //        holder_tmp = itable[index-step-ioffset];
3791   //     }
3792   //     if (tmp == resolved_klass) {
3793   //        goto L_resolved_found;  // Found!
3794   //     }
3795   //   } while (tmp != 0);
3796   //   goto L_no_such_interface // Not found.
3797   //
3798   Label L_loop_scan_resolved;
3799   bind(L_loop_scan_resolved);
3800     movptr(temp_itbl_klass, Address(scan_temp, 0));
3801     addptr(scan_temp, scan_step);
3802     bind(L_loop_scan_resolved_entry);
3803     cmpptr(holder_klass, temp_itbl_klass);
3804     cmovl(Assembler::equal, temp_reg, Address(scan_temp, ooffset - ioffset - scan_step));
3805     cmpptr(resolved_klass, temp_itbl_klass);
3806     jccb(Assembler::equal, L_resolved_found);
3807     testptr(temp_itbl_klass, temp_itbl_klass);
3808     jccb(Assembler::notZero, L_loop_scan_resolved);
3809 
3810   jmpb(L_no_such_interface);
3811 
3812   Label L_ready;
3813 
3814   // See if we already have a holder klass. If not, go and scan for it.
3815   bind(L_resolved_found);
3816   testptr(temp_reg, temp_reg);
3817   jccb(Assembler::zero, L_scan_holder);
3818   jmpb(L_ready);
3819 
3820   bind(L_holder_found);
3821   movl(temp_reg, Address(scan_temp, ooffset - ioffset - scan_step));
3822 
3823   // Finally, temp_reg contains holder_klass vtable offset
3824   bind(L_ready);
3825   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
3826   if (temp_reg2 == noreg) { // recv_klass register is clobbered for 32-bit x86 impl
3827     load_klass(scan_temp, receiver, noreg);
3828     movptr(method_result, Address(scan_temp, temp_reg, Address::times_1, itable_index * wordSize + itentry_off));
3829   } else {
3830     movptr(method_result, Address(recv_klass, temp_reg, Address::times_1, itable_index * wordSize + itentry_off));
3831   }
3832 }
3833 
3834 
3835 // virtual method calling
3836 void MacroAssembler::lookup_virtual_method(Register recv_klass,
3837                                            RegisterOrConstant vtable_index,
3838                                            Register method_result) {
3839   const ByteSize base = Klass::vtable_start_offset();
3840   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
3841   Address vtable_entry_addr(recv_klass,
3842                             vtable_index, Address::times_ptr,
3843                             base + vtableEntry::method_offset());
3844   movptr(method_result, vtable_entry_addr);
3845 }
3846 
3847 
3848 void MacroAssembler::check_klass_subtype(Register sub_klass,
3849                            Register super_klass,
3850                            Register temp_reg,
3851                            Label& L_success) {
3852   Label L_failure;
3853   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, nullptr);
3854   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, nullptr);
3855   bind(L_failure);
3856 }
3857 
3858 
3859 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
3860                                                    Register super_klass,
3861                                                    Register temp_reg,
3862                                                    Label* L_success,
3863                                                    Label* L_failure,
3864                                                    Label* L_slow_path,
3865                                         RegisterOrConstant super_check_offset) {
3866   assert_different_registers(sub_klass, super_klass, temp_reg);
3867   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
3868   if (super_check_offset.is_register()) {
3869     assert_different_registers(sub_klass, super_klass,
3870                                super_check_offset.as_register());
3871   } else if (must_load_sco) {
3872     assert(temp_reg != noreg, "supply either a temp or a register offset");
3873   }
3874 
3875   Label L_fallthrough;
3876   int label_nulls = 0;
3877   if (L_success == nullptr)   { L_success   = &L_fallthrough; label_nulls++; }
3878   if (L_failure == nullptr)   { L_failure   = &L_fallthrough; label_nulls++; }
3879   if (L_slow_path == nullptr) { L_slow_path = &L_fallthrough; label_nulls++; }
3880   assert(label_nulls <= 1, "at most one null in the batch");
3881 
3882   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
3883   int sco_offset = in_bytes(Klass::super_check_offset_offset());
3884   Address super_check_offset_addr(super_klass, sco_offset);
3885 
3886   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
3887   // range of a jccb.  If this routine grows larger, reconsider at
3888   // least some of these.
3889 #define local_jcc(assembler_cond, label)                                \
3890   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
3891   else                             jcc( assembler_cond, label) /*omit semi*/
3892 
3893   // Hacked jmp, which may only be used just before L_fallthrough.
3894 #define final_jmp(label)                                                \
3895   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
3896   else                            jmp(label)                /*omit semi*/
3897 
3898   // If the pointers are equal, we are done (e.g., String[] elements).
3899   // This self-check enables sharing of secondary supertype arrays among
3900   // non-primary types such as array-of-interface.  Otherwise, each such
3901   // type would need its own customized SSA.
3902   // We move this check to the front of the fast path because many
3903   // type checks are in fact trivially successful in this manner,
3904   // so we get a nicely predicted branch right at the start of the check.
3905   cmpptr(sub_klass, super_klass);
3906   local_jcc(Assembler::equal, *L_success);
3907 
3908   // Check the supertype display:
3909   if (must_load_sco) {
3910     // Positive movl does right thing on LP64.
3911     movl(temp_reg, super_check_offset_addr);
3912     super_check_offset = RegisterOrConstant(temp_reg);
3913   }
3914   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
3915   cmpptr(super_klass, super_check_addr); // load displayed supertype
3916 
3917   // This check has worked decisively for primary supers.
3918   // Secondary supers are sought in the super_cache ('super_cache_addr').
3919   // (Secondary supers are interfaces and very deeply nested subtypes.)
3920   // This works in the same check above because of a tricky aliasing
3921   // between the super_cache and the primary super display elements.
3922   // (The 'super_check_addr' can address either, as the case requires.)
3923   // Note that the cache is updated below if it does not help us find
3924   // what we need immediately.
3925   // So if it was a primary super, we can just fail immediately.
3926   // Otherwise, it's the slow path for us (no success at this point).
3927 
3928   if (super_check_offset.is_register()) {
3929     local_jcc(Assembler::equal, *L_success);
3930     cmpl(super_check_offset.as_register(), sc_offset);
3931     if (L_failure == &L_fallthrough) {
3932       local_jcc(Assembler::equal, *L_slow_path);
3933     } else {
3934       local_jcc(Assembler::notEqual, *L_failure);
3935       final_jmp(*L_slow_path);
3936     }
3937   } else if (super_check_offset.as_constant() == sc_offset) {
3938     // Need a slow path; fast failure is impossible.
3939     if (L_slow_path == &L_fallthrough) {
3940       local_jcc(Assembler::equal, *L_success);
3941     } else {
3942       local_jcc(Assembler::notEqual, *L_slow_path);
3943       final_jmp(*L_success);
3944     }
3945   } else {
3946     // No slow path; it's a fast decision.
3947     if (L_failure == &L_fallthrough) {
3948       local_jcc(Assembler::equal, *L_success);
3949     } else {
3950       local_jcc(Assembler::notEqual, *L_failure);
3951       final_jmp(*L_success);
3952     }
3953   }
3954 
3955   bind(L_fallthrough);
3956 
3957 #undef local_jcc
3958 #undef final_jmp
3959 }
3960 
3961 
3962 void MacroAssembler::check_klass_subtype_slow_path_linear(Register sub_klass,
3963                                                           Register super_klass,
3964                                                           Register temp_reg,
3965                                                           Register temp2_reg,
3966                                                           Label* L_success,
3967                                                           Label* L_failure,
3968                                                           bool set_cond_codes) {
3969   assert_different_registers(sub_klass, super_klass, temp_reg);
3970   if (temp2_reg != noreg)
3971     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
3972 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
3973 
3974   Label L_fallthrough;
3975   int label_nulls = 0;
3976   if (L_success == nullptr)   { L_success   = &L_fallthrough; label_nulls++; }
3977   if (L_failure == nullptr)   { L_failure   = &L_fallthrough; label_nulls++; }
3978   assert(label_nulls <= 1, "at most one null in the batch");
3979 
3980   // a couple of useful fields in sub_klass:
3981   int ss_offset = in_bytes(Klass::secondary_supers_offset());
3982   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
3983   Address secondary_supers_addr(sub_klass, ss_offset);
3984   Address super_cache_addr(     sub_klass, sc_offset);
3985 
3986   // Do a linear scan of the secondary super-klass chain.
3987   // This code is rarely used, so simplicity is a virtue here.
3988   // The repne_scan instruction uses fixed registers, which we must spill.
3989   // Don't worry too much about pre-existing connections with the input regs.
3990 
3991   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
3992   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
3993 
3994   // Get super_klass value into rax (even if it was in rdi or rcx).
3995   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
3996   if (super_klass != rax) {
3997     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
3998     mov(rax, super_klass);
3999   }
4000   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
4001   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
4002 
4003 #ifndef PRODUCT
4004   uint* pst_counter = &SharedRuntime::_partial_subtype_ctr;
4005   ExternalAddress pst_counter_addr((address) pst_counter);
4006   lea(rcx, pst_counter_addr);
4007   incrementl(Address(rcx, 0));
4008 #endif //PRODUCT
4009 
4010   // We will consult the secondary-super array.
4011   movptr(rdi, secondary_supers_addr);
4012   // Load the array length.  (Positive movl does right thing on LP64.)
4013   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
4014   // Skip to start of data.
4015   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
4016 
4017   // Scan RCX words at [RDI] for an occurrence of RAX.
4018   // Set NZ/Z based on last compare.
4019   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
4020   // not change flags (only scas instruction which is repeated sets flags).
4021   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
4022 
4023     testptr(rax,rax); // Set Z = 0
4024     repne_scan();
4025 
4026   // Unspill the temp. registers:
4027   if (pushed_rdi)  pop(rdi);
4028   if (pushed_rcx)  pop(rcx);
4029   if (pushed_rax)  pop(rax);
4030 
4031   if (set_cond_codes) {
4032     // Special hack for the AD files:  rdi is guaranteed non-zero.
4033     assert(!pushed_rdi, "rdi must be left non-null");
4034     // Also, the condition codes are properly set Z/NZ on succeed/failure.
4035   }
4036 
4037   if (L_failure == &L_fallthrough)
4038         jccb(Assembler::notEqual, *L_failure);
4039   else  jcc(Assembler::notEqual, *L_failure);
4040 
4041   // Success.  Cache the super we found and proceed in triumph.
4042   movptr(super_cache_addr, super_klass);
4043 
4044   if (L_success != &L_fallthrough) {
4045     jmp(*L_success);
4046   }
4047 
4048 #undef IS_A_TEMP
4049 
4050   bind(L_fallthrough);
4051 }
4052 
4053 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
4054                                                    Register super_klass,
4055                                                    Register temp_reg,
4056                                                    Register temp2_reg,
4057                                                    Label* L_success,
4058                                                    Label* L_failure,
4059                                                    bool set_cond_codes) {
4060   assert(set_cond_codes == false, "must be false on 64-bit x86");
4061   check_klass_subtype_slow_path
4062     (sub_klass, super_klass, temp_reg, temp2_reg, noreg, noreg,
4063      L_success, L_failure);
4064 }
4065 
4066 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
4067                                                    Register super_klass,
4068                                                    Register temp_reg,
4069                                                    Register temp2_reg,
4070                                                    Register temp3_reg,
4071                                                    Register temp4_reg,
4072                                                    Label* L_success,
4073                                                    Label* L_failure) {
4074   if (UseSecondarySupersTable) {
4075     check_klass_subtype_slow_path_table
4076       (sub_klass, super_klass, temp_reg, temp2_reg, temp3_reg, temp4_reg,
4077        L_success, L_failure);
4078   } else {
4079     check_klass_subtype_slow_path_linear
4080       (sub_klass, super_klass, temp_reg, temp2_reg, L_success, L_failure, /*set_cond_codes*/false);
4081   }
4082 }
4083 
4084 Register MacroAssembler::allocate_if_noreg(Register r,
4085                                   RegSetIterator<Register> &available_regs,
4086                                   RegSet &regs_to_push) {
4087   if (!r->is_valid()) {
4088     r = *available_regs++;
4089     regs_to_push += r;
4090   }
4091   return r;
4092 }
4093 
4094 void MacroAssembler::check_klass_subtype_slow_path_table(Register sub_klass,
4095                                                          Register super_klass,
4096                                                          Register temp_reg,
4097                                                          Register temp2_reg,
4098                                                          Register temp3_reg,
4099                                                          Register result_reg,
4100                                                          Label* L_success,
4101                                                          Label* L_failure) {
4102   // NB! Callers may assume that, when temp2_reg is a valid register,
4103   // this code sets it to a nonzero value.
4104   bool temp2_reg_was_valid = temp2_reg->is_valid();
4105 
4106   RegSet temps = RegSet::of(temp_reg, temp2_reg, temp3_reg);
4107 
4108   Label L_fallthrough;
4109   int label_nulls = 0;
4110   if (L_success == nullptr)   { L_success   = &L_fallthrough; label_nulls++; }
4111   if (L_failure == nullptr)   { L_failure   = &L_fallthrough; label_nulls++; }
4112   assert(label_nulls <= 1, "at most one null in the batch");
4113 
4114   BLOCK_COMMENT("check_klass_subtype_slow_path_table");
4115 
4116   RegSetIterator<Register> available_regs
4117     = (RegSet::of(rax, rcx, rdx, r8) + r9 + r10 + r11 + r12 - temps - sub_klass - super_klass).begin();
4118 
4119   RegSet pushed_regs;
4120 
4121   temp_reg = allocate_if_noreg(temp_reg, available_regs, pushed_regs);
4122   temp2_reg = allocate_if_noreg(temp2_reg, available_regs, pushed_regs);
4123   temp3_reg = allocate_if_noreg(temp3_reg, available_regs, pushed_regs);
4124   result_reg = allocate_if_noreg(result_reg, available_regs, pushed_regs);
4125   Register temp4_reg = allocate_if_noreg(noreg, available_regs, pushed_regs);
4126 
4127   assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg, temp3_reg, result_reg);
4128 
4129   {
4130 
4131     int register_push_size = pushed_regs.size() * Register::max_slots_per_register * VMRegImpl::stack_slot_size;
4132     int aligned_size = align_up(register_push_size, StackAlignmentInBytes);
4133     subptr(rsp, aligned_size);
4134     push_set(pushed_regs, 0);
4135 
4136     lookup_secondary_supers_table_var(sub_klass,
4137                                       super_klass,
4138                                       temp_reg, temp2_reg, temp3_reg, temp4_reg, result_reg);
4139     cmpq(result_reg, 0);
4140 
4141     // Unspill the temp. registers:
4142     pop_set(pushed_regs, 0);
4143     // Increment SP but do not clobber flags.
4144     lea(rsp, Address(rsp, aligned_size));
4145   }
4146 
4147   if (temp2_reg_was_valid) {
4148     movq(temp2_reg, 1);
4149   }
4150 
4151   jcc(Assembler::notEqual, *L_failure);
4152 
4153   if (L_success != &L_fallthrough) {
4154     jmp(*L_success);
4155   }
4156 
4157   bind(L_fallthrough);
4158 }
4159 
4160 // population_count variant for running without the POPCNT
4161 // instruction, which was introduced with SSE4.2 in 2008.
4162 void MacroAssembler::population_count(Register dst, Register src,
4163                                       Register scratch1, Register scratch2) {
4164   assert_different_registers(src, scratch1, scratch2);
4165   if (UsePopCountInstruction) {
4166     Assembler::popcntq(dst, src);
4167   } else {
4168     assert_different_registers(src, scratch1, scratch2);
4169     assert_different_registers(dst, scratch1, scratch2);
4170     Label loop, done;
4171 
4172     mov(scratch1, src);
4173     // dst = 0;
4174     // while(scratch1 != 0) {
4175     //   dst++;
4176     //   scratch1 &= (scratch1 - 1);
4177     // }
4178     xorl(dst, dst);
4179     testq(scratch1, scratch1);
4180     jccb(Assembler::equal, done);
4181     {
4182       bind(loop);
4183       incq(dst);
4184       movq(scratch2, scratch1);
4185       decq(scratch2);
4186       andq(scratch1, scratch2);
4187       jccb(Assembler::notEqual, loop);
4188     }
4189     bind(done);
4190   }
4191 #ifdef ASSERT
4192   mov64(scratch1, 0xCafeBabeDeadBeef);
4193   movq(scratch2, scratch1);
4194 #endif
4195 }
4196 
4197 // Ensure that the inline code and the stub are using the same registers.
4198 #define LOOKUP_SECONDARY_SUPERS_TABLE_REGISTERS                      \
4199 do {                                                                 \
4200   assert(r_super_klass  == rax, "mismatch");                         \
4201   assert(r_array_base   == rbx, "mismatch");                         \
4202   assert(r_array_length == rcx, "mismatch");                         \
4203   assert(r_array_index  == rdx, "mismatch");                         \
4204   assert(r_sub_klass    == rsi || r_sub_klass == noreg, "mismatch"); \
4205   assert(r_bitmap       == r11 || r_bitmap    == noreg, "mismatch"); \
4206   assert(result         == rdi || result      == noreg, "mismatch"); \
4207 } while(0)
4208 
4209 // Versions of salq and rorq that don't need count to be in rcx
4210 
4211 void MacroAssembler::salq(Register dest, Register count) {
4212   if (count == rcx) {
4213     Assembler::salq(dest);
4214   } else {
4215     assert_different_registers(rcx, dest);
4216     xchgq(rcx, count);
4217     Assembler::salq(dest);
4218     xchgq(rcx, count);
4219   }
4220 }
4221 
4222 void MacroAssembler::rorq(Register dest, Register count) {
4223   if (count == rcx) {
4224     Assembler::rorq(dest);
4225   } else {
4226     assert_different_registers(rcx, dest);
4227     xchgq(rcx, count);
4228     Assembler::rorq(dest);
4229     xchgq(rcx, count);
4230   }
4231 }
4232 
4233 // Return true: we succeeded in generating this code
4234 //
4235 // At runtime, return 0 in result if r_super_klass is a superclass of
4236 // r_sub_klass, otherwise return nonzero. Use this if you know the
4237 // super_klass_slot of the class you're looking for. This is always
4238 // the case for instanceof and checkcast.
4239 void MacroAssembler::lookup_secondary_supers_table_const(Register r_sub_klass,
4240                                                          Register r_super_klass,
4241                                                          Register temp1,
4242                                                          Register temp2,
4243                                                          Register temp3,
4244                                                          Register temp4,
4245                                                          Register result,
4246                                                          u1 super_klass_slot) {
4247   assert_different_registers(r_sub_klass, r_super_klass, temp1, temp2, temp3, temp4, result);
4248 
4249   Label L_fallthrough, L_success, L_failure;
4250 
4251   BLOCK_COMMENT("lookup_secondary_supers_table {");
4252 
4253   const Register
4254     r_array_index  = temp1,
4255     r_array_length = temp2,
4256     r_array_base   = temp3,
4257     r_bitmap       = temp4;
4258 
4259   LOOKUP_SECONDARY_SUPERS_TABLE_REGISTERS;
4260 
4261   xorq(result, result); // = 0
4262 
4263   movq(r_bitmap, Address(r_sub_klass, Klass::secondary_supers_bitmap_offset()));
4264   movq(r_array_index, r_bitmap);
4265 
4266   // First check the bitmap to see if super_klass might be present. If
4267   // the bit is zero, we are certain that super_klass is not one of
4268   // the secondary supers.
4269   u1 bit = super_klass_slot;
4270   {
4271     // NB: If the count in a x86 shift instruction is 0, the flags are
4272     // not affected, so we do a testq instead.
4273     int shift_count = Klass::SECONDARY_SUPERS_TABLE_MASK - bit;
4274     if (shift_count != 0) {
4275       salq(r_array_index, shift_count);
4276     } else {
4277       testq(r_array_index, r_array_index);
4278     }
4279   }
4280   // We test the MSB of r_array_index, i.e. its sign bit
4281   jcc(Assembler::positive, L_failure);
4282 
4283   // Get the first array index that can contain super_klass into r_array_index.
4284   if (bit != 0) {
4285     population_count(r_array_index, r_array_index, temp2, temp3);
4286   } else {
4287     movl(r_array_index, 1);
4288   }
4289   // NB! r_array_index is off by 1. It is compensated by keeping r_array_base off by 1 word.
4290 
4291   // We will consult the secondary-super array.
4292   movptr(r_array_base, Address(r_sub_klass, in_bytes(Klass::secondary_supers_offset())));
4293 
4294   // We're asserting that the first word in an Array<Klass*> is the
4295   // length, and the second word is the first word of the data. If
4296   // that ever changes, r_array_base will have to be adjusted here.
4297   assert(Array<Klass*>::base_offset_in_bytes() == wordSize, "Adjust this code");
4298   assert(Array<Klass*>::length_offset_in_bytes() == 0, "Adjust this code");
4299 
4300   cmpq(r_super_klass, Address(r_array_base, r_array_index, Address::times_8));
4301   jccb(Assembler::equal, L_success);
4302 
4303   // Is there another entry to check? Consult the bitmap.
4304   btq(r_bitmap, (bit + 1) & Klass::SECONDARY_SUPERS_TABLE_MASK);
4305   jccb(Assembler::carryClear, L_failure);
4306 
4307   // Linear probe. Rotate the bitmap so that the next bit to test is
4308   // in Bit 1.
4309   if (bit != 0) {
4310     rorq(r_bitmap, bit);
4311   }
4312 
4313   // Calls into the stub generated by lookup_secondary_supers_table_slow_path.
4314   // Arguments: r_super_klass, r_array_base, r_array_index, r_bitmap.
4315   // Kills: r_array_length.
4316   // Returns: result.
4317   call(RuntimeAddress(StubRoutines::lookup_secondary_supers_table_slow_path_stub()));
4318   // Result (0/1) is in rdi
4319   jmpb(L_fallthrough);
4320 
4321   bind(L_failure);
4322   incq(result); // 0 => 1
4323 
4324   bind(L_success);
4325   // result = 0;
4326 
4327   bind(L_fallthrough);
4328   BLOCK_COMMENT("} lookup_secondary_supers_table");
4329 
4330   if (VerifySecondarySupers) {
4331     verify_secondary_supers_table(r_sub_klass, r_super_klass, result,
4332                                   temp1, temp2, temp3);
4333   }
4334 }
4335 
4336 // At runtime, return 0 in result if r_super_klass is a superclass of
4337 // r_sub_klass, otherwise return nonzero. Use this version of
4338 // lookup_secondary_supers_table() if you don't know ahead of time
4339 // which superclass will be searched for. Used by interpreter and
4340 // runtime stubs. It is larger and has somewhat greater latency than
4341 // the version above, which takes a constant super_klass_slot.
4342 void MacroAssembler::lookup_secondary_supers_table_var(Register r_sub_klass,
4343                                                        Register r_super_klass,
4344                                                        Register temp1,
4345                                                        Register temp2,
4346                                                        Register temp3,
4347                                                        Register temp4,
4348                                                        Register result) {
4349   assert_different_registers(r_sub_klass, r_super_klass, temp1, temp2, temp3, temp4, result);
4350   assert_different_registers(r_sub_klass, r_super_klass, rcx);
4351   RegSet temps = RegSet::of(temp1, temp2, temp3, temp4);
4352 
4353   Label L_fallthrough, L_success, L_failure;
4354 
4355   BLOCK_COMMENT("lookup_secondary_supers_table {");
4356 
4357   RegSetIterator<Register> available_regs = (temps - rcx).begin();
4358 
4359   // FIXME. Once we are sure that all paths reaching this point really
4360   // do pass rcx as one of our temps we can get rid of the following
4361   // workaround.
4362   assert(temps.contains(rcx), "fix this code");
4363 
4364   // We prefer to have our shift count in rcx. If rcx is one of our
4365   // temps, use it for slot. If not, pick any of our temps.
4366   Register slot;
4367   if (!temps.contains(rcx)) {
4368     slot = *available_regs++;
4369   } else {
4370     slot = rcx;
4371   }
4372 
4373   const Register r_array_index = *available_regs++;
4374   const Register r_bitmap      = *available_regs++;
4375 
4376   // The logic above guarantees this property, but we state it here.
4377   assert_different_registers(r_array_index, r_bitmap, rcx);
4378 
4379   movq(r_bitmap, Address(r_sub_klass, Klass::secondary_supers_bitmap_offset()));
4380   movq(r_array_index, r_bitmap);
4381 
4382   // First check the bitmap to see if super_klass might be present. If
4383   // the bit is zero, we are certain that super_klass is not one of
4384   // the secondary supers.
4385   movb(slot, Address(r_super_klass, Klass::hash_slot_offset()));
4386   xorl(slot, (u1)(Klass::SECONDARY_SUPERS_TABLE_SIZE - 1)); // slot ^ 63 === 63 - slot (mod 64)
4387   salq(r_array_index, slot);
4388 
4389   testq(r_array_index, r_array_index);
4390   // We test the MSB of r_array_index, i.e. its sign bit
4391   jcc(Assembler::positive, L_failure);
4392 
4393   const Register r_array_base = *available_regs++;
4394 
4395   // Get the first array index that can contain super_klass into r_array_index.
4396   // Note: Clobbers r_array_base and slot.
4397   population_count(r_array_index, r_array_index, /*temp2*/r_array_base, /*temp3*/slot);
4398 
4399   // NB! r_array_index is off by 1. It is compensated by keeping r_array_base off by 1 word.
4400 
4401   // We will consult the secondary-super array.
4402   movptr(r_array_base, Address(r_sub_klass, in_bytes(Klass::secondary_supers_offset())));
4403 
4404   // We're asserting that the first word in an Array<Klass*> is the
4405   // length, and the second word is the first word of the data. If
4406   // that ever changes, r_array_base will have to be adjusted here.
4407   assert(Array<Klass*>::base_offset_in_bytes() == wordSize, "Adjust this code");
4408   assert(Array<Klass*>::length_offset_in_bytes() == 0, "Adjust this code");
4409 
4410   cmpq(r_super_klass, Address(r_array_base, r_array_index, Address::times_8));
4411   jccb(Assembler::equal, L_success);
4412 
4413   // Restore slot to its true value
4414   movb(slot, Address(r_super_klass, Klass::hash_slot_offset()));
4415 
4416   // Linear probe. Rotate the bitmap so that the next bit to test is
4417   // in Bit 1.
4418   rorq(r_bitmap, slot);
4419 
4420   // Is there another entry to check? Consult the bitmap.
4421   btq(r_bitmap, 1);
4422   jccb(Assembler::carryClear, L_failure);
4423 
4424   // Calls into the stub generated by lookup_secondary_supers_table_slow_path.
4425   // Arguments: r_super_klass, r_array_base, r_array_index, r_bitmap.
4426   // Kills: r_array_length.
4427   // Returns: result.
4428   lookup_secondary_supers_table_slow_path(r_super_klass,
4429                                           r_array_base,
4430                                           r_array_index,
4431                                           r_bitmap,
4432                                           /*temp1*/result,
4433                                           /*temp2*/slot,
4434                                           &L_success,
4435                                           nullptr);
4436 
4437   bind(L_failure);
4438   movq(result, 1);
4439   jmpb(L_fallthrough);
4440 
4441   bind(L_success);
4442   xorq(result, result); // = 0
4443 
4444   bind(L_fallthrough);
4445   BLOCK_COMMENT("} lookup_secondary_supers_table");
4446 
4447   if (VerifySecondarySupers) {
4448     verify_secondary_supers_table(r_sub_klass, r_super_klass, result,
4449                                   temp1, temp2, temp3);
4450   }
4451 }
4452 
4453 void MacroAssembler::repne_scanq(Register addr, Register value, Register count, Register limit,
4454                                  Label* L_success, Label* L_failure) {
4455   Label L_loop, L_fallthrough;
4456   {
4457     int label_nulls = 0;
4458     if (L_success == nullptr) { L_success = &L_fallthrough; label_nulls++; }
4459     if (L_failure == nullptr) { L_failure = &L_fallthrough; label_nulls++; }
4460     assert(label_nulls <= 1, "at most one null in the batch");
4461   }
4462   bind(L_loop);
4463   cmpq(value, Address(addr, count, Address::times_8));
4464   jcc(Assembler::equal, *L_success);
4465   addl(count, 1);
4466   cmpl(count, limit);
4467   jcc(Assembler::less, L_loop);
4468 
4469   if (&L_fallthrough != L_failure) {
4470     jmp(*L_failure);
4471   }
4472   bind(L_fallthrough);
4473 }
4474 
4475 // Called by code generated by check_klass_subtype_slow_path
4476 // above. This is called when there is a collision in the hashed
4477 // lookup in the secondary supers array.
4478 void MacroAssembler::lookup_secondary_supers_table_slow_path(Register r_super_klass,
4479                                                              Register r_array_base,
4480                                                              Register r_array_index,
4481                                                              Register r_bitmap,
4482                                                              Register temp1,
4483                                                              Register temp2,
4484                                                              Label* L_success,
4485                                                              Label* L_failure) {
4486   assert_different_registers(r_super_klass, r_array_base, r_array_index, r_bitmap, temp1, temp2);
4487 
4488   const Register
4489     r_array_length = temp1,
4490     r_sub_klass    = noreg,
4491     result         = noreg;
4492 
4493   Label L_fallthrough;
4494   int label_nulls = 0;
4495   if (L_success == nullptr)   { L_success   = &L_fallthrough; label_nulls++; }
4496   if (L_failure == nullptr)   { L_failure   = &L_fallthrough; label_nulls++; }
4497   assert(label_nulls <= 1, "at most one null in the batch");
4498 
4499   // Load the array length.
4500   movl(r_array_length, Address(r_array_base, Array<Klass*>::length_offset_in_bytes()));
4501   // And adjust the array base to point to the data.
4502   // NB! Effectively increments current slot index by 1.
4503   assert(Array<Klass*>::base_offset_in_bytes() == wordSize, "");
4504   addptr(r_array_base, Array<Klass*>::base_offset_in_bytes());
4505 
4506   // Linear probe
4507   Label L_huge;
4508 
4509   // The bitmap is full to bursting.
4510   // Implicit invariant: BITMAP_FULL implies (length > 0)
4511   cmpl(r_array_length, (int32_t)Klass::SECONDARY_SUPERS_TABLE_SIZE - 2);
4512   jcc(Assembler::greater, L_huge);
4513 
4514   // NB! Our caller has checked bits 0 and 1 in the bitmap. The
4515   // current slot (at secondary_supers[r_array_index]) has not yet
4516   // been inspected, and r_array_index may be out of bounds if we
4517   // wrapped around the end of the array.
4518 
4519   { // This is conventional linear probing, but instead of terminating
4520     // when a null entry is found in the table, we maintain a bitmap
4521     // in which a 0 indicates missing entries.
4522     // The check above guarantees there are 0s in the bitmap, so the loop
4523     // eventually terminates.
4524 
4525     xorl(temp2, temp2); // = 0;
4526 
4527     Label L_again;
4528     bind(L_again);
4529 
4530     // Check for array wraparound.
4531     cmpl(r_array_index, r_array_length);
4532     cmovl(Assembler::greaterEqual, r_array_index, temp2);
4533 
4534     cmpq(r_super_klass, Address(r_array_base, r_array_index, Address::times_8));
4535     jcc(Assembler::equal, *L_success);
4536 
4537     // If the next bit in bitmap is zero, we're done.
4538     btq(r_bitmap, 2); // look-ahead check (Bit 2); Bits 0 and 1 are tested by now
4539     jcc(Assembler::carryClear, *L_failure);
4540 
4541     rorq(r_bitmap, 1); // Bits 1/2 => 0/1
4542     addl(r_array_index, 1);
4543 
4544     jmp(L_again);
4545   }
4546 
4547   { // Degenerate case: more than 64 secondary supers.
4548     // FIXME: We could do something smarter here, maybe a vectorized
4549     // comparison or a binary search, but is that worth any added
4550     // complexity?
4551     bind(L_huge);
4552     xorl(r_array_index, r_array_index); // = 0
4553     repne_scanq(r_array_base, r_super_klass, r_array_index, r_array_length,
4554                 L_success,
4555                 (&L_fallthrough != L_failure ? L_failure : nullptr));
4556 
4557     bind(L_fallthrough);
4558   }
4559 }
4560 
4561 struct VerifyHelperArguments {
4562   Klass* _super;
4563   Klass* _sub;
4564   intptr_t _linear_result;
4565   intptr_t _table_result;
4566 };
4567 
4568 static void verify_secondary_supers_table_helper(const char* msg, VerifyHelperArguments* args) {
4569   Klass::on_secondary_supers_verification_failure(args->_super,
4570                                                   args->_sub,
4571                                                   args->_linear_result,
4572                                                   args->_table_result,
4573                                                   msg);
4574 }
4575 
4576 // Make sure that the hashed lookup and a linear scan agree.
4577 void MacroAssembler::verify_secondary_supers_table(Register r_sub_klass,
4578                                                    Register r_super_klass,
4579                                                    Register result,
4580                                                    Register temp1,
4581                                                    Register temp2,
4582                                                    Register temp3) {
4583   const Register
4584       r_array_index  = temp1,
4585       r_array_length = temp2,
4586       r_array_base   = temp3,
4587       r_bitmap       = noreg;
4588 
4589   BLOCK_COMMENT("verify_secondary_supers_table {");
4590 
4591   Label L_success, L_failure, L_check, L_done;
4592 
4593   movptr(r_array_base, Address(r_sub_klass, in_bytes(Klass::secondary_supers_offset())));
4594   movl(r_array_length, Address(r_array_base, Array<Klass*>::length_offset_in_bytes()));
4595   // And adjust the array base to point to the data.
4596   addptr(r_array_base, Array<Klass*>::base_offset_in_bytes());
4597 
4598   testl(r_array_length, r_array_length); // array_length == 0?
4599   jcc(Assembler::zero, L_failure);
4600 
4601   movl(r_array_index, 0);
4602   repne_scanq(r_array_base, r_super_klass, r_array_index, r_array_length, &L_success);
4603   // fall through to L_failure
4604 
4605   const Register linear_result = r_array_index; // reuse temp1
4606 
4607   bind(L_failure); // not present
4608   movl(linear_result, 1);
4609   jmp(L_check);
4610 
4611   bind(L_success); // present
4612   movl(linear_result, 0);
4613 
4614   bind(L_check);
4615   cmpl(linear_result, result);
4616   jcc(Assembler::equal, L_done);
4617 
4618   { // To avoid calling convention issues, build a record on the stack
4619     // and pass the pointer to that instead.
4620     push(result);
4621     push(linear_result);
4622     push(r_sub_klass);
4623     push(r_super_klass);
4624     movptr(c_rarg1, rsp);
4625     movptr(c_rarg0, (uintptr_t) "mismatch");
4626     call(RuntimeAddress(CAST_FROM_FN_PTR(address, verify_secondary_supers_table_helper)));
4627     should_not_reach_here();
4628   }
4629   bind(L_done);
4630 
4631   BLOCK_COMMENT("} verify_secondary_supers_table");
4632 }
4633 
4634 #undef LOOKUP_SECONDARY_SUPERS_TABLE_REGISTERS
4635 
4636 void MacroAssembler::clinit_barrier(Register klass, Label* L_fast_path, Label* L_slow_path) {
4637   assert(L_fast_path != nullptr || L_slow_path != nullptr, "at least one is required");
4638 
4639   Label L_fallthrough;
4640   if (L_fast_path == nullptr) {
4641     L_fast_path = &L_fallthrough;
4642   } else if (L_slow_path == nullptr) {
4643     L_slow_path = &L_fallthrough;
4644   }
4645 
4646   // Fast path check: class is fully initialized.
4647   // init_state needs acquire, but x86 is TSO, and so we are already good.
4648   cmpb(Address(klass, InstanceKlass::init_state_offset()), InstanceKlass::fully_initialized);
4649   jcc(Assembler::equal, *L_fast_path);
4650 
4651   // Fast path check: current thread is initializer thread
4652   cmpptr(r15_thread, Address(klass, InstanceKlass::init_thread_offset()));
4653   if (L_slow_path == &L_fallthrough) {
4654     jcc(Assembler::equal, *L_fast_path);
4655     bind(*L_slow_path);
4656   } else if (L_fast_path == &L_fallthrough) {
4657     jcc(Assembler::notEqual, *L_slow_path);
4658     bind(*L_fast_path);
4659   } else {
4660     Unimplemented();
4661   }
4662 }
4663 
4664 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
4665   if (VM_Version::supports_cmov()) {
4666     cmovl(cc, dst, src);
4667   } else {
4668     Label L;
4669     jccb(negate_condition(cc), L);
4670     movl(dst, src);
4671     bind(L);
4672   }
4673 }
4674 
4675 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
4676   if (VM_Version::supports_cmov()) {
4677     cmovl(cc, dst, src);
4678   } else {
4679     Label L;
4680     jccb(negate_condition(cc), L);
4681     movl(dst, src);
4682     bind(L);
4683   }
4684 }
4685 
4686 void MacroAssembler::_verify_oop(Register reg, const char* s, const char* file, int line) {
4687   if (!VerifyOops) return;
4688 
4689   BLOCK_COMMENT("verify_oop {");
4690   push(rscratch1);
4691   push(rax);                          // save rax
4692   push(reg);                          // pass register argument
4693 
4694   // Pass register number to verify_oop_subroutine
4695   const char* b = nullptr;
4696   {
4697     ResourceMark rm;
4698     stringStream ss;
4699     ss.print("verify_oop: %s: %s (%s:%d)", reg->name(), s, file, line);
4700     b = code_string(ss.as_string());
4701   }
4702   AddressLiteral buffer((address) b, external_word_Relocation::spec_for_immediate());
4703   pushptr(buffer.addr(), rscratch1);
4704 
4705   // call indirectly to solve generation ordering problem
4706   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
4707   call(rax);
4708   // Caller pops the arguments (oop, message) and restores rax, r10
4709   BLOCK_COMMENT("} verify_oop");
4710 }
4711 
4712 void MacroAssembler::vallones(XMMRegister dst, int vector_len) {
4713   if (UseAVX > 2 && (vector_len == Assembler::AVX_512bit || VM_Version::supports_avx512vl())) {
4714     // Only pcmpeq has dependency breaking treatment (i.e the execution can begin without
4715     // waiting for the previous result on dst), not vpcmpeqd, so just use vpternlog
4716     vpternlogd(dst, 0xFF, dst, dst, vector_len);
4717   } else if (VM_Version::supports_avx()) {
4718     vpcmpeqd(dst, dst, dst, vector_len);
4719   } else {
4720     pcmpeqd(dst, dst);
4721   }
4722 }
4723 
4724 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
4725                                          int extra_slot_offset) {
4726   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
4727   int stackElementSize = Interpreter::stackElementSize;
4728   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
4729 #ifdef ASSERT
4730   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
4731   assert(offset1 - offset == stackElementSize, "correct arithmetic");
4732 #endif
4733   Register             scale_reg    = noreg;
4734   Address::ScaleFactor scale_factor = Address::no_scale;
4735   if (arg_slot.is_constant()) {
4736     offset += arg_slot.as_constant() * stackElementSize;
4737   } else {
4738     scale_reg    = arg_slot.as_register();
4739     scale_factor = Address::times(stackElementSize);
4740   }
4741   offset += wordSize;           // return PC is on stack
4742   return Address(rsp, scale_reg, scale_factor, offset);
4743 }
4744 
4745 void MacroAssembler::_verify_oop_addr(Address addr, const char* s, const char* file, int line) {
4746   if (!VerifyOops) return;
4747 
4748   push(rscratch1);
4749   push(rax); // save rax,
4750   // addr may contain rsp so we will have to adjust it based on the push
4751   // we just did (and on 64 bit we do two pushes)
4752   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
4753   // stores rax into addr which is backwards of what was intended.
4754   if (addr.uses(rsp)) {
4755     lea(rax, addr);
4756     pushptr(Address(rax, 2 * BytesPerWord));
4757   } else {
4758     pushptr(addr);
4759   }
4760 
4761   // Pass register number to verify_oop_subroutine
4762   const char* b = nullptr;
4763   {
4764     ResourceMark rm;
4765     stringStream ss;
4766     ss.print("verify_oop_addr: %s (%s:%d)", s, file, line);
4767     b = code_string(ss.as_string());
4768   }
4769   AddressLiteral buffer((address) b, external_word_Relocation::spec_for_immediate());
4770   pushptr(buffer.addr(), rscratch1);
4771 
4772   // call indirectly to solve generation ordering problem
4773   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
4774   call(rax);
4775   // Caller pops the arguments (addr, message) and restores rax, r10.
4776 }
4777 
4778 void MacroAssembler::verify_tlab() {
4779 #ifdef ASSERT
4780   if (UseTLAB && VerifyOops) {
4781     Label next, ok;
4782     Register t1 = rsi;
4783 
4784     push(t1);
4785 
4786     movptr(t1, Address(r15_thread, in_bytes(JavaThread::tlab_top_offset())));
4787     cmpptr(t1, Address(r15_thread, in_bytes(JavaThread::tlab_start_offset())));
4788     jcc(Assembler::aboveEqual, next);
4789     STOP("assert(top >= start)");
4790     should_not_reach_here();
4791 
4792     bind(next);
4793     movptr(t1, Address(r15_thread, in_bytes(JavaThread::tlab_end_offset())));
4794     cmpptr(t1, Address(r15_thread, in_bytes(JavaThread::tlab_top_offset())));
4795     jcc(Assembler::aboveEqual, ok);
4796     STOP("assert(top <= end)");
4797     should_not_reach_here();
4798 
4799     bind(ok);
4800     pop(t1);
4801   }
4802 #endif
4803 }
4804 
4805 class ControlWord {
4806  public:
4807   int32_t _value;
4808 
4809   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
4810   int  precision_control() const       { return  (_value >>  8) & 3      ; }
4811   bool precision() const               { return ((_value >>  5) & 1) != 0; }
4812   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
4813   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
4814   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
4815   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
4816   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
4817 
4818   void print() const {
4819     // rounding control
4820     const char* rc;
4821     switch (rounding_control()) {
4822       case 0: rc = "round near"; break;
4823       case 1: rc = "round down"; break;
4824       case 2: rc = "round up  "; break;
4825       case 3: rc = "chop      "; break;
4826       default:
4827         rc = nullptr; // silence compiler warnings
4828         fatal("Unknown rounding control: %d", rounding_control());
4829     };
4830     // precision control
4831     const char* pc;
4832     switch (precision_control()) {
4833       case 0: pc = "24 bits "; break;
4834       case 1: pc = "reserved"; break;
4835       case 2: pc = "53 bits "; break;
4836       case 3: pc = "64 bits "; break;
4837       default:
4838         pc = nullptr; // silence compiler warnings
4839         fatal("Unknown precision control: %d", precision_control());
4840     };
4841     // flags
4842     char f[9];
4843     f[0] = ' ';
4844     f[1] = ' ';
4845     f[2] = (precision   ()) ? 'P' : 'p';
4846     f[3] = (underflow   ()) ? 'U' : 'u';
4847     f[4] = (overflow    ()) ? 'O' : 'o';
4848     f[5] = (zero_divide ()) ? 'Z' : 'z';
4849     f[6] = (denormalized()) ? 'D' : 'd';
4850     f[7] = (invalid     ()) ? 'I' : 'i';
4851     f[8] = '\x0';
4852     // output
4853     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
4854   }
4855 
4856 };
4857 
4858 class StatusWord {
4859  public:
4860   int32_t _value;
4861 
4862   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
4863   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
4864   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
4865   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
4866   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
4867   int  top() const                     { return  (_value >> 11) & 7      ; }
4868   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
4869   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
4870   bool precision() const               { return ((_value >>  5) & 1) != 0; }
4871   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
4872   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
4873   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
4874   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
4875   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
4876 
4877   void print() const {
4878     // condition codes
4879     char c[5];
4880     c[0] = (C3()) ? '3' : '-';
4881     c[1] = (C2()) ? '2' : '-';
4882     c[2] = (C1()) ? '1' : '-';
4883     c[3] = (C0()) ? '0' : '-';
4884     c[4] = '\x0';
4885     // flags
4886     char f[9];
4887     f[0] = (error_status()) ? 'E' : '-';
4888     f[1] = (stack_fault ()) ? 'S' : '-';
4889     f[2] = (precision   ()) ? 'P' : '-';
4890     f[3] = (underflow   ()) ? 'U' : '-';
4891     f[4] = (overflow    ()) ? 'O' : '-';
4892     f[5] = (zero_divide ()) ? 'Z' : '-';
4893     f[6] = (denormalized()) ? 'D' : '-';
4894     f[7] = (invalid     ()) ? 'I' : '-';
4895     f[8] = '\x0';
4896     // output
4897     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
4898   }
4899 
4900 };
4901 
4902 class TagWord {
4903  public:
4904   int32_t _value;
4905 
4906   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
4907 
4908   void print() const {
4909     printf("%04x", _value & 0xFFFF);
4910   }
4911 
4912 };
4913 
4914 class FPU_Register {
4915  public:
4916   int32_t _m0;
4917   int32_t _m1;
4918   int16_t _ex;
4919 
4920   bool is_indefinite() const           {
4921     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
4922   }
4923 
4924   void print() const {
4925     char  sign = (_ex < 0) ? '-' : '+';
4926     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
4927     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
4928   };
4929 
4930 };
4931 
4932 class FPU_State {
4933  public:
4934   enum {
4935     register_size       = 10,
4936     number_of_registers =  8,
4937     register_mask       =  7
4938   };
4939 
4940   ControlWord  _control_word;
4941   StatusWord   _status_word;
4942   TagWord      _tag_word;
4943   int32_t      _error_offset;
4944   int32_t      _error_selector;
4945   int32_t      _data_offset;
4946   int32_t      _data_selector;
4947   int8_t       _register[register_size * number_of_registers];
4948 
4949   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
4950   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
4951 
4952   const char* tag_as_string(int tag) const {
4953     switch (tag) {
4954       case 0: return "valid";
4955       case 1: return "zero";
4956       case 2: return "special";
4957       case 3: return "empty";
4958     }
4959     ShouldNotReachHere();
4960     return nullptr;
4961   }
4962 
4963   void print() const {
4964     // print computation registers
4965     { int t = _status_word.top();
4966       for (int i = 0; i < number_of_registers; i++) {
4967         int j = (i - t) & register_mask;
4968         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
4969         st(j)->print();
4970         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
4971       }
4972     }
4973     printf("\n");
4974     // print control registers
4975     printf("ctrl = "); _control_word.print(); printf("\n");
4976     printf("stat = "); _status_word .print(); printf("\n");
4977     printf("tags = "); _tag_word    .print(); printf("\n");
4978   }
4979 
4980 };
4981 
4982 class Flag_Register {
4983  public:
4984   int32_t _value;
4985 
4986   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
4987   bool direction() const               { return ((_value >> 10) & 1) != 0; }
4988   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
4989   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
4990   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
4991   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
4992   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
4993 
4994   void print() const {
4995     // flags
4996     char f[8];
4997     f[0] = (overflow       ()) ? 'O' : '-';
4998     f[1] = (direction      ()) ? 'D' : '-';
4999     f[2] = (sign           ()) ? 'S' : '-';
5000     f[3] = (zero           ()) ? 'Z' : '-';
5001     f[4] = (auxiliary_carry()) ? 'A' : '-';
5002     f[5] = (parity         ()) ? 'P' : '-';
5003     f[6] = (carry          ()) ? 'C' : '-';
5004     f[7] = '\x0';
5005     // output
5006     printf("%08x  flags = %s", _value, f);
5007   }
5008 
5009 };
5010 
5011 class IU_Register {
5012  public:
5013   int32_t _value;
5014 
5015   void print() const {
5016     printf("%08x  %11d", _value, _value);
5017   }
5018 
5019 };
5020 
5021 class IU_State {
5022  public:
5023   Flag_Register _eflags;
5024   IU_Register   _rdi;
5025   IU_Register   _rsi;
5026   IU_Register   _rbp;
5027   IU_Register   _rsp;
5028   IU_Register   _rbx;
5029   IU_Register   _rdx;
5030   IU_Register   _rcx;
5031   IU_Register   _rax;
5032 
5033   void print() const {
5034     // computation registers
5035     printf("rax,  = "); _rax.print(); printf("\n");
5036     printf("rbx,  = "); _rbx.print(); printf("\n");
5037     printf("rcx  = "); _rcx.print(); printf("\n");
5038     printf("rdx  = "); _rdx.print(); printf("\n");
5039     printf("rdi  = "); _rdi.print(); printf("\n");
5040     printf("rsi  = "); _rsi.print(); printf("\n");
5041     printf("rbp,  = "); _rbp.print(); printf("\n");
5042     printf("rsp  = "); _rsp.print(); printf("\n");
5043     printf("\n");
5044     // control registers
5045     printf("flgs = "); _eflags.print(); printf("\n");
5046   }
5047 };
5048 
5049 
5050 class CPU_State {
5051  public:
5052   FPU_State _fpu_state;
5053   IU_State  _iu_state;
5054 
5055   void print() const {
5056     printf("--------------------------------------------------\n");
5057     _iu_state .print();
5058     printf("\n");
5059     _fpu_state.print();
5060     printf("--------------------------------------------------\n");
5061   }
5062 
5063 };
5064 
5065 
5066 static void _print_CPU_state(CPU_State* state) {
5067   state->print();
5068 };
5069 
5070 
5071 void MacroAssembler::print_CPU_state() {
5072   push_CPU_state();
5073   push(rsp);                // pass CPU state
5074   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
5075   addptr(rsp, wordSize);       // discard argument
5076   pop_CPU_state();
5077 }
5078 
5079 void MacroAssembler::restore_cpu_control_state_after_jni(Register rscratch) {
5080   // Either restore the MXCSR register after returning from the JNI Call
5081   // or verify that it wasn't changed (with -Xcheck:jni flag).
5082   if (VM_Version::supports_sse()) {
5083     if (RestoreMXCSROnJNICalls) {
5084       ldmxcsr(ExternalAddress(StubRoutines::x86::addr_mxcsr_std()), rscratch);
5085     } else if (CheckJNICalls) {
5086       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
5087     }
5088   }
5089   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
5090   vzeroupper();
5091 }
5092 
5093 // ((OopHandle)result).resolve();
5094 void MacroAssembler::resolve_oop_handle(Register result, Register tmp) {
5095   assert_different_registers(result, tmp);
5096 
5097   // Only 64 bit platforms support GCs that require a tmp register
5098   // Only IN_HEAP loads require a thread_tmp register
5099   // OopHandle::resolve is an indirection like jobject.
5100   access_load_at(T_OBJECT, IN_NATIVE,
5101                  result, Address(result, 0), tmp);
5102 }
5103 
5104 // ((WeakHandle)result).resolve();
5105 void MacroAssembler::resolve_weak_handle(Register rresult, Register rtmp) {
5106   assert_different_registers(rresult, rtmp);
5107   Label resolved;
5108 
5109   // A null weak handle resolves to null.
5110   cmpptr(rresult, 0);
5111   jcc(Assembler::equal, resolved);
5112 
5113   // Only 64 bit platforms support GCs that require a tmp register
5114   // Only IN_HEAP loads require a thread_tmp register
5115   // WeakHandle::resolve is an indirection like jweak.
5116   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
5117                  rresult, Address(rresult, 0), rtmp);
5118   bind(resolved);
5119 }
5120 
5121 void MacroAssembler::load_mirror(Register mirror, Register method, Register tmp) {
5122   // get mirror
5123   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
5124   load_method_holder(mirror, method);
5125   movptr(mirror, Address(mirror, mirror_offset));
5126   resolve_oop_handle(mirror, tmp);
5127 }
5128 
5129 void MacroAssembler::load_method_holder_cld(Register rresult, Register rmethod) {
5130   load_method_holder(rresult, rmethod);
5131   movptr(rresult, Address(rresult, InstanceKlass::class_loader_data_offset()));
5132 }
5133 
5134 void MacroAssembler::load_method_holder(Register holder, Register method) {
5135   movptr(holder, Address(method, Method::const_offset()));                      // ConstMethod*
5136   movptr(holder, Address(holder, ConstMethod::constants_offset()));             // ConstantPool*
5137   movptr(holder, Address(holder, ConstantPool::pool_holder_offset()));          // InstanceKlass*
5138 }
5139 
5140 void MacroAssembler::load_narrow_klass_compact(Register dst, Register src) {
5141   assert(UseCompactObjectHeaders, "expect compact object headers");
5142   movq(dst, Address(src, oopDesc::mark_offset_in_bytes()));
5143   shrq(dst, markWord::klass_shift);
5144 }
5145 
5146 void MacroAssembler::load_klass(Register dst, Register src, Register tmp) {
5147   assert_different_registers(src, tmp);
5148   assert_different_registers(dst, tmp);
5149 
5150   if (UseCompactObjectHeaders) {
5151     load_narrow_klass_compact(dst, src);
5152     decode_klass_not_null(dst, tmp);
5153   } else if (UseCompressedClassPointers) {
5154     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5155     decode_klass_not_null(dst, tmp);
5156   } else {
5157     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5158   }
5159 }
5160 
5161 void MacroAssembler::store_klass(Register dst, Register src, Register tmp) {
5162   assert(!UseCompactObjectHeaders, "not with compact headers");
5163   assert_different_registers(src, tmp);
5164   assert_different_registers(dst, tmp);
5165   if (UseCompressedClassPointers) {
5166     encode_klass_not_null(src, tmp);
5167     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
5168   } else {
5169     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
5170   }
5171 }
5172 
5173 void MacroAssembler::cmp_klass(Register klass, Register obj, Register tmp) {
5174   if (UseCompactObjectHeaders) {
5175     assert(tmp != noreg, "need tmp");
5176     assert_different_registers(klass, obj, tmp);
5177     load_narrow_klass_compact(tmp, obj);
5178     cmpl(klass, tmp);
5179   } else if (UseCompressedClassPointers) {
5180     cmpl(klass, Address(obj, oopDesc::klass_offset_in_bytes()));
5181   } else {
5182     cmpptr(klass, Address(obj, oopDesc::klass_offset_in_bytes()));
5183   }
5184 }
5185 
5186 void MacroAssembler::cmp_klasses_from_objects(Register obj1, Register obj2, Register tmp1, Register tmp2) {
5187   if (UseCompactObjectHeaders) {
5188     assert(tmp2 != noreg, "need tmp2");
5189     assert_different_registers(obj1, obj2, tmp1, tmp2);
5190     load_narrow_klass_compact(tmp1, obj1);
5191     load_narrow_klass_compact(tmp2, obj2);
5192     cmpl(tmp1, tmp2);
5193   } else if (UseCompressedClassPointers) {
5194     movl(tmp1, Address(obj1, oopDesc::klass_offset_in_bytes()));
5195     cmpl(tmp1, Address(obj2, oopDesc::klass_offset_in_bytes()));
5196   } else {
5197     movptr(tmp1, Address(obj1, oopDesc::klass_offset_in_bytes()));
5198     cmpptr(tmp1, Address(obj2, oopDesc::klass_offset_in_bytes()));
5199   }
5200 }
5201 
5202 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators, Register dst, Address src,
5203                                     Register tmp1) {
5204   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5205   decorators = AccessInternal::decorator_fixup(decorators, type);
5206   bool as_raw = (decorators & AS_RAW) != 0;
5207   if (as_raw) {
5208     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1);
5209   } else {
5210     bs->load_at(this, decorators, type, dst, src, tmp1);
5211   }
5212 }
5213 
5214 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators, Address dst, Register val,
5215                                      Register tmp1, Register tmp2, Register tmp3) {
5216   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5217   decorators = AccessInternal::decorator_fixup(decorators, type);
5218   bool as_raw = (decorators & AS_RAW) != 0;
5219   if (as_raw) {
5220     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
5221   } else {
5222     bs->store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
5223   }
5224 }
5225 
5226 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1, DecoratorSet decorators) {
5227   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1);
5228 }
5229 
5230 // Doesn't do verification, generates fixed size code
5231 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1, DecoratorSet decorators) {
5232   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1);
5233 }
5234 
5235 void MacroAssembler::store_heap_oop(Address dst, Register val, Register tmp1,
5236                                     Register tmp2, Register tmp3, DecoratorSet decorators) {
5237   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, val, tmp1, tmp2, tmp3);
5238 }
5239 
5240 // Used for storing nulls.
5241 void MacroAssembler::store_heap_oop_null(Address dst) {
5242   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg, noreg);
5243 }
5244 
5245 void MacroAssembler::store_klass_gap(Register dst, Register src) {
5246   assert(!UseCompactObjectHeaders, "Don't use with compact headers");
5247   if (UseCompressedClassPointers) {
5248     // Store to klass gap in destination
5249     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
5250   }
5251 }
5252 
5253 #ifdef ASSERT
5254 void MacroAssembler::verify_heapbase(const char* msg) {
5255   assert (UseCompressedOops, "should be compressed");
5256   assert (Universe::heap() != nullptr, "java heap should be initialized");
5257   if (CheckCompressedOops) {
5258     Label ok;
5259     ExternalAddress src2(CompressedOops::base_addr());
5260     const bool is_src2_reachable = reachable(src2);
5261     if (!is_src2_reachable) {
5262       push(rscratch1);  // cmpptr trashes rscratch1
5263     }
5264     cmpptr(r12_heapbase, src2, rscratch1);
5265     jcc(Assembler::equal, ok);
5266     STOP(msg);
5267     bind(ok);
5268     if (!is_src2_reachable) {
5269       pop(rscratch1);
5270     }
5271   }
5272 }
5273 #endif
5274 
5275 // Algorithm must match oop.inline.hpp encode_heap_oop.
5276 void MacroAssembler::encode_heap_oop(Register r) {
5277 #ifdef ASSERT
5278   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
5279 #endif
5280   verify_oop_msg(r, "broken oop in encode_heap_oop");
5281   if (CompressedOops::base() == nullptr) {
5282     if (CompressedOops::shift() != 0) {
5283       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5284       shrq(r, LogMinObjAlignmentInBytes);
5285     }
5286     return;
5287   }
5288   testq(r, r);
5289   cmovq(Assembler::equal, r, r12_heapbase);
5290   subq(r, r12_heapbase);
5291   shrq(r, LogMinObjAlignmentInBytes);
5292 }
5293 
5294 void MacroAssembler::encode_heap_oop_not_null(Register r) {
5295 #ifdef ASSERT
5296   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
5297   if (CheckCompressedOops) {
5298     Label ok;
5299     testq(r, r);
5300     jcc(Assembler::notEqual, ok);
5301     STOP("null oop passed to encode_heap_oop_not_null");
5302     bind(ok);
5303   }
5304 #endif
5305   verify_oop_msg(r, "broken oop in encode_heap_oop_not_null");
5306   if (CompressedOops::base() != nullptr) {
5307     subq(r, r12_heapbase);
5308   }
5309   if (CompressedOops::shift() != 0) {
5310     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5311     shrq(r, LogMinObjAlignmentInBytes);
5312   }
5313 }
5314 
5315 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
5316 #ifdef ASSERT
5317   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
5318   if (CheckCompressedOops) {
5319     Label ok;
5320     testq(src, src);
5321     jcc(Assembler::notEqual, ok);
5322     STOP("null oop passed to encode_heap_oop_not_null2");
5323     bind(ok);
5324   }
5325 #endif
5326   verify_oop_msg(src, "broken oop in encode_heap_oop_not_null2");
5327   if (dst != src) {
5328     movq(dst, src);
5329   }
5330   if (CompressedOops::base() != nullptr) {
5331     subq(dst, r12_heapbase);
5332   }
5333   if (CompressedOops::shift() != 0) {
5334     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5335     shrq(dst, LogMinObjAlignmentInBytes);
5336   }
5337 }
5338 
5339 void  MacroAssembler::decode_heap_oop(Register r) {
5340 #ifdef ASSERT
5341   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
5342 #endif
5343   if (CompressedOops::base() == nullptr) {
5344     if (CompressedOops::shift() != 0) {
5345       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5346       shlq(r, LogMinObjAlignmentInBytes);
5347     }
5348   } else {
5349     Label done;
5350     shlq(r, LogMinObjAlignmentInBytes);
5351     jccb(Assembler::equal, done);
5352     addq(r, r12_heapbase);
5353     bind(done);
5354   }
5355   verify_oop_msg(r, "broken oop in decode_heap_oop");
5356 }
5357 
5358 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
5359   // Note: it will change flags
5360   assert (UseCompressedOops, "should only be used for compressed headers");
5361   assert (Universe::heap() != nullptr, "java heap should be initialized");
5362   // Cannot assert, unverified entry point counts instructions (see .ad file)
5363   // vtableStubs also counts instructions in pd_code_size_limit.
5364   // Also do not verify_oop as this is called by verify_oop.
5365   if (CompressedOops::shift() != 0) {
5366     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5367     shlq(r, LogMinObjAlignmentInBytes);
5368     if (CompressedOops::base() != nullptr) {
5369       addq(r, r12_heapbase);
5370     }
5371   } else {
5372     assert (CompressedOops::base() == nullptr, "sanity");
5373   }
5374 }
5375 
5376 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
5377   // Note: it will change flags
5378   assert (UseCompressedOops, "should only be used for compressed headers");
5379   assert (Universe::heap() != nullptr, "java heap should be initialized");
5380   // Cannot assert, unverified entry point counts instructions (see .ad file)
5381   // vtableStubs also counts instructions in pd_code_size_limit.
5382   // Also do not verify_oop as this is called by verify_oop.
5383   if (CompressedOops::shift() != 0) {
5384     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5385     if (LogMinObjAlignmentInBytes == Address::times_8) {
5386       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
5387     } else {
5388       if (dst != src) {
5389         movq(dst, src);
5390       }
5391       shlq(dst, LogMinObjAlignmentInBytes);
5392       if (CompressedOops::base() != nullptr) {
5393         addq(dst, r12_heapbase);
5394       }
5395     }
5396   } else {
5397     assert (CompressedOops::base() == nullptr, "sanity");
5398     if (dst != src) {
5399       movq(dst, src);
5400     }
5401   }
5402 }
5403 
5404 void MacroAssembler::encode_klass_not_null(Register r, Register tmp) {
5405   assert_different_registers(r, tmp);
5406   if (CompressedKlassPointers::base() != nullptr) {
5407     mov64(tmp, (int64_t)CompressedKlassPointers::base());
5408     subq(r, tmp);
5409   }
5410   if (CompressedKlassPointers::shift() != 0) {
5411     shrq(r, CompressedKlassPointers::shift());
5412   }
5413 }
5414 
5415 void MacroAssembler::encode_and_move_klass_not_null(Register dst, Register src) {
5416   assert_different_registers(src, dst);
5417   if (CompressedKlassPointers::base() != nullptr) {
5418     mov64(dst, -(int64_t)CompressedKlassPointers::base());
5419     addq(dst, src);
5420   } else {
5421     movptr(dst, src);
5422   }
5423   if (CompressedKlassPointers::shift() != 0) {
5424     shrq(dst, CompressedKlassPointers::shift());
5425   }
5426 }
5427 
5428 void  MacroAssembler::decode_klass_not_null(Register r, Register tmp) {
5429   assert_different_registers(r, tmp);
5430   // Note: it will change flags
5431   assert(UseCompressedClassPointers, "should only be used for compressed headers");
5432   // Cannot assert, unverified entry point counts instructions (see .ad file)
5433   // vtableStubs also counts instructions in pd_code_size_limit.
5434   // Also do not verify_oop as this is called by verify_oop.
5435   if (CompressedKlassPointers::shift() != 0) {
5436     shlq(r, CompressedKlassPointers::shift());
5437   }
5438   if (CompressedKlassPointers::base() != nullptr) {
5439     mov64(tmp, (int64_t)CompressedKlassPointers::base());
5440     addq(r, tmp);
5441   }
5442 }
5443 
5444 void  MacroAssembler::decode_and_move_klass_not_null(Register dst, Register src) {
5445   assert_different_registers(src, dst);
5446   // Note: it will change flags
5447   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5448   // Cannot assert, unverified entry point counts instructions (see .ad file)
5449   // vtableStubs also counts instructions in pd_code_size_limit.
5450   // Also do not verify_oop as this is called by verify_oop.
5451 
5452   if (CompressedKlassPointers::base() == nullptr &&
5453       CompressedKlassPointers::shift() == 0) {
5454     // The best case scenario is that there is no base or shift. Then it is already
5455     // a pointer that needs nothing but a register rename.
5456     movl(dst, src);
5457   } else {
5458     if (CompressedKlassPointers::shift() <= Address::times_8) {
5459       if (CompressedKlassPointers::base() != nullptr) {
5460         mov64(dst, (int64_t)CompressedKlassPointers::base());
5461       } else {
5462         xorq(dst, dst);
5463       }
5464       if (CompressedKlassPointers::shift() != 0) {
5465         assert(CompressedKlassPointers::shift() == Address::times_8, "klass not aligned on 64bits?");
5466         leaq(dst, Address(dst, src, Address::times_8, 0));
5467       } else {
5468         addq(dst, src);
5469       }
5470     } else {
5471       if (CompressedKlassPointers::base() != nullptr) {
5472         const uint64_t base_right_shifted =
5473             (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
5474         mov64(dst, base_right_shifted);
5475       } else {
5476         xorq(dst, dst);
5477       }
5478       addq(dst, src);
5479       shlq(dst, CompressedKlassPointers::shift());
5480     }
5481   }
5482 }
5483 
5484 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
5485   assert (UseCompressedOops, "should only be used for compressed headers");
5486   assert (Universe::heap() != nullptr, "java heap should be initialized");
5487   assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5488   int oop_index = oop_recorder()->find_index(obj);
5489   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5490   mov_narrow_oop(dst, oop_index, rspec);
5491 }
5492 
5493 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
5494   assert (UseCompressedOops, "should only be used for compressed headers");
5495   assert (Universe::heap() != nullptr, "java heap should be initialized");
5496   assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5497   int oop_index = oop_recorder()->find_index(obj);
5498   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5499   mov_narrow_oop(dst, oop_index, rspec);
5500 }
5501 
5502 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
5503   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5504   assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5505   int klass_index = oop_recorder()->find_index(k);
5506   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5507   mov_narrow_oop(dst, CompressedKlassPointers::encode(k), rspec);
5508 }
5509 
5510 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
5511   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5512   assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5513   int klass_index = oop_recorder()->find_index(k);
5514   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5515   mov_narrow_oop(dst, CompressedKlassPointers::encode(k), rspec);
5516 }
5517 
5518 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
5519   assert (UseCompressedOops, "should only be used for compressed headers");
5520   assert (Universe::heap() != nullptr, "java heap should be initialized");
5521   assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5522   int oop_index = oop_recorder()->find_index(obj);
5523   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5524   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
5525 }
5526 
5527 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
5528   assert (UseCompressedOops, "should only be used for compressed headers");
5529   assert (Universe::heap() != nullptr, "java heap should be initialized");
5530   assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5531   int oop_index = oop_recorder()->find_index(obj);
5532   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5533   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
5534 }
5535 
5536 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
5537   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5538   assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5539   int klass_index = oop_recorder()->find_index(k);
5540   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5541   Assembler::cmp_narrow_oop(dst, CompressedKlassPointers::encode(k), rspec);
5542 }
5543 
5544 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
5545   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5546   assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5547   int klass_index = oop_recorder()->find_index(k);
5548   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5549   Assembler::cmp_narrow_oop(dst, CompressedKlassPointers::encode(k), rspec);
5550 }
5551 
5552 void MacroAssembler::reinit_heapbase() {
5553   if (UseCompressedOops) {
5554     if (Universe::heap() != nullptr) {
5555       if (CompressedOops::base() == nullptr) {
5556         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
5557       } else {
5558         mov64(r12_heapbase, (int64_t)CompressedOops::base());
5559       }
5560     } else {
5561       movptr(r12_heapbase, ExternalAddress(CompressedOops::base_addr()));
5562     }
5563   }
5564 }
5565 
5566 #if COMPILER2_OR_JVMCI
5567 
5568 // clear memory of size 'cnt' qwords, starting at 'base' using XMM/YMM/ZMM registers
5569 void MacroAssembler::xmm_clear_mem(Register base, Register cnt, Register rtmp, XMMRegister xtmp, KRegister mask) {
5570   // cnt - number of qwords (8-byte words).
5571   // base - start address, qword aligned.
5572   Label L_zero_64_bytes, L_loop, L_sloop, L_tail, L_end;
5573   bool use64byteVector = (MaxVectorSize == 64) && (VM_Version::avx3_threshold() == 0);
5574   if (use64byteVector) {
5575     vpxor(xtmp, xtmp, xtmp, AVX_512bit);
5576   } else if (MaxVectorSize >= 32) {
5577     vpxor(xtmp, xtmp, xtmp, AVX_256bit);
5578   } else {
5579     pxor(xtmp, xtmp);
5580   }
5581   jmp(L_zero_64_bytes);
5582 
5583   BIND(L_loop);
5584   if (MaxVectorSize >= 32) {
5585     fill64(base, 0, xtmp, use64byteVector);
5586   } else {
5587     movdqu(Address(base,  0), xtmp);
5588     movdqu(Address(base, 16), xtmp);
5589     movdqu(Address(base, 32), xtmp);
5590     movdqu(Address(base, 48), xtmp);
5591   }
5592   addptr(base, 64);
5593 
5594   BIND(L_zero_64_bytes);
5595   subptr(cnt, 8);
5596   jccb(Assembler::greaterEqual, L_loop);
5597 
5598   // Copy trailing 64 bytes
5599   if (use64byteVector) {
5600     addptr(cnt, 8);
5601     jccb(Assembler::equal, L_end);
5602     fill64_masked(3, base, 0, xtmp, mask, cnt, rtmp, true);
5603     jmp(L_end);
5604   } else {
5605     addptr(cnt, 4);
5606     jccb(Assembler::less, L_tail);
5607     if (MaxVectorSize >= 32) {
5608       vmovdqu(Address(base, 0), xtmp);
5609     } else {
5610       movdqu(Address(base,  0), xtmp);
5611       movdqu(Address(base, 16), xtmp);
5612     }
5613   }
5614   addptr(base, 32);
5615   subptr(cnt, 4);
5616 
5617   BIND(L_tail);
5618   addptr(cnt, 4);
5619   jccb(Assembler::lessEqual, L_end);
5620   if (UseAVX > 2 && MaxVectorSize >= 32 && VM_Version::supports_avx512vl()) {
5621     fill32_masked(3, base, 0, xtmp, mask, cnt, rtmp);
5622   } else {
5623     decrement(cnt);
5624 
5625     BIND(L_sloop);
5626     movq(Address(base, 0), xtmp);
5627     addptr(base, 8);
5628     decrement(cnt);
5629     jccb(Assembler::greaterEqual, L_sloop);
5630   }
5631   BIND(L_end);
5632 }
5633 
5634 // Clearing constant sized memory using YMM/ZMM registers.
5635 void MacroAssembler::clear_mem(Register base, int cnt, Register rtmp, XMMRegister xtmp, KRegister mask) {
5636   assert(UseAVX > 2 && VM_Version::supports_avx512vl(), "");
5637   bool use64byteVector = (MaxVectorSize > 32) && (VM_Version::avx3_threshold() == 0);
5638 
5639   int vector64_count = (cnt & (~0x7)) >> 3;
5640   cnt = cnt & 0x7;
5641   const int fill64_per_loop = 4;
5642   const int max_unrolled_fill64 = 8;
5643 
5644   // 64 byte initialization loop.
5645   vpxor(xtmp, xtmp, xtmp, use64byteVector ? AVX_512bit : AVX_256bit);
5646   int start64 = 0;
5647   if (vector64_count > max_unrolled_fill64) {
5648     Label LOOP;
5649     Register index = rtmp;
5650 
5651     start64 = vector64_count - (vector64_count % fill64_per_loop);
5652 
5653     movl(index, 0);
5654     BIND(LOOP);
5655     for (int i = 0; i < fill64_per_loop; i++) {
5656       fill64(Address(base, index, Address::times_1, i * 64), xtmp, use64byteVector);
5657     }
5658     addl(index, fill64_per_loop * 64);
5659     cmpl(index, start64 * 64);
5660     jccb(Assembler::less, LOOP);
5661   }
5662   for (int i = start64; i < vector64_count; i++) {
5663     fill64(base, i * 64, xtmp, use64byteVector);
5664   }
5665 
5666   // Clear remaining 64 byte tail.
5667   int disp = vector64_count * 64;
5668   if (cnt) {
5669     switch (cnt) {
5670       case 1:
5671         movq(Address(base, disp), xtmp);
5672         break;
5673       case 2:
5674         evmovdqu(T_LONG, k0, Address(base, disp), xtmp, false, Assembler::AVX_128bit);
5675         break;
5676       case 3:
5677         movl(rtmp, 0x7);
5678         kmovwl(mask, rtmp);
5679         evmovdqu(T_LONG, mask, Address(base, disp), xtmp, true, Assembler::AVX_256bit);
5680         break;
5681       case 4:
5682         evmovdqu(T_LONG, k0, Address(base, disp), xtmp, false, Assembler::AVX_256bit);
5683         break;
5684       case 5:
5685         if (use64byteVector) {
5686           movl(rtmp, 0x1F);
5687           kmovwl(mask, rtmp);
5688           evmovdqu(T_LONG, mask, Address(base, disp), xtmp, true, Assembler::AVX_512bit);
5689         } else {
5690           evmovdqu(T_LONG, k0, Address(base, disp), xtmp, false, Assembler::AVX_256bit);
5691           movq(Address(base, disp + 32), xtmp);
5692         }
5693         break;
5694       case 6:
5695         if (use64byteVector) {
5696           movl(rtmp, 0x3F);
5697           kmovwl(mask, rtmp);
5698           evmovdqu(T_LONG, mask, Address(base, disp), xtmp, true, Assembler::AVX_512bit);
5699         } else {
5700           evmovdqu(T_LONG, k0, Address(base, disp), xtmp, false, Assembler::AVX_256bit);
5701           evmovdqu(T_LONG, k0, Address(base, disp + 32), xtmp, false, Assembler::AVX_128bit);
5702         }
5703         break;
5704       case 7:
5705         if (use64byteVector) {
5706           movl(rtmp, 0x7F);
5707           kmovwl(mask, rtmp);
5708           evmovdqu(T_LONG, mask, Address(base, disp), xtmp, true, Assembler::AVX_512bit);
5709         } else {
5710           evmovdqu(T_LONG, k0, Address(base, disp), xtmp, false, Assembler::AVX_256bit);
5711           movl(rtmp, 0x7);
5712           kmovwl(mask, rtmp);
5713           evmovdqu(T_LONG, mask, Address(base, disp + 32), xtmp, true, Assembler::AVX_256bit);
5714         }
5715         break;
5716       default:
5717         fatal("Unexpected length : %d\n",cnt);
5718         break;
5719     }
5720   }
5721 }
5722 
5723 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, XMMRegister xtmp,
5724                                bool is_large, KRegister mask) {
5725   // cnt      - number of qwords (8-byte words).
5726   // base     - start address, qword aligned.
5727   // is_large - if optimizers know cnt is larger than InitArrayShortSize
5728   assert(base==rdi, "base register must be edi for rep stos");
5729   assert(tmp==rax,   "tmp register must be eax for rep stos");
5730   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
5731   assert(InitArrayShortSize % BytesPerLong == 0,
5732     "InitArrayShortSize should be the multiple of BytesPerLong");
5733 
5734   Label DONE;
5735   if (!is_large || !UseXMMForObjInit) {
5736     xorptr(tmp, tmp);
5737   }
5738 
5739   if (!is_large) {
5740     Label LOOP, LONG;
5741     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
5742     jccb(Assembler::greater, LONG);
5743 
5744     decrement(cnt);
5745     jccb(Assembler::negative, DONE); // Zero length
5746 
5747     // Use individual pointer-sized stores for small counts:
5748     BIND(LOOP);
5749     movptr(Address(base, cnt, Address::times_ptr), tmp);
5750     decrement(cnt);
5751     jccb(Assembler::greaterEqual, LOOP);
5752     jmpb(DONE);
5753 
5754     BIND(LONG);
5755   }
5756 
5757   // Use longer rep-prefixed ops for non-small counts:
5758   if (UseFastStosb) {
5759     shlptr(cnt, 3); // convert to number of bytes
5760     rep_stosb();
5761   } else if (UseXMMForObjInit) {
5762     xmm_clear_mem(base, cnt, tmp, xtmp, mask);
5763   } else {
5764     rep_stos();
5765   }
5766 
5767   BIND(DONE);
5768 }
5769 
5770 #endif //COMPILER2_OR_JVMCI
5771 
5772 
5773 void MacroAssembler::generate_fill(BasicType t, bool aligned,
5774                                    Register to, Register value, Register count,
5775                                    Register rtmp, XMMRegister xtmp) {
5776   ShortBranchVerifier sbv(this);
5777   assert_different_registers(to, value, count, rtmp);
5778   Label L_exit;
5779   Label L_fill_2_bytes, L_fill_4_bytes;
5780 
5781 #if defined(COMPILER2)
5782   if(MaxVectorSize >=32 &&
5783      VM_Version::supports_avx512vlbw() &&
5784      VM_Version::supports_bmi2()) {
5785     generate_fill_avx3(t, to, value, count, rtmp, xtmp);
5786     return;
5787   }
5788 #endif
5789 
5790   int shift = -1;
5791   switch (t) {
5792     case T_BYTE:
5793       shift = 2;
5794       break;
5795     case T_SHORT:
5796       shift = 1;
5797       break;
5798     case T_INT:
5799       shift = 0;
5800       break;
5801     default: ShouldNotReachHere();
5802   }
5803 
5804   if (t == T_BYTE) {
5805     andl(value, 0xff);
5806     movl(rtmp, value);
5807     shll(rtmp, 8);
5808     orl(value, rtmp);
5809   }
5810   if (t == T_SHORT) {
5811     andl(value, 0xffff);
5812   }
5813   if (t == T_BYTE || t == T_SHORT) {
5814     movl(rtmp, value);
5815     shll(rtmp, 16);
5816     orl(value, rtmp);
5817   }
5818 
5819   cmpptr(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
5820   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
5821   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
5822     Label L_skip_align2;
5823     // align source address at 4 bytes address boundary
5824     if (t == T_BYTE) {
5825       Label L_skip_align1;
5826       // One byte misalignment happens only for byte arrays
5827       testptr(to, 1);
5828       jccb(Assembler::zero, L_skip_align1);
5829       movb(Address(to, 0), value);
5830       increment(to);
5831       decrement(count);
5832       BIND(L_skip_align1);
5833     }
5834     // Two bytes misalignment happens only for byte and short (char) arrays
5835     testptr(to, 2);
5836     jccb(Assembler::zero, L_skip_align2);
5837     movw(Address(to, 0), value);
5838     addptr(to, 2);
5839     subptr(count, 1<<(shift-1));
5840     BIND(L_skip_align2);
5841   }
5842   {
5843     Label L_fill_32_bytes;
5844     if (!UseUnalignedLoadStores) {
5845       // align to 8 bytes, we know we are 4 byte aligned to start
5846       testptr(to, 4);
5847       jccb(Assembler::zero, L_fill_32_bytes);
5848       movl(Address(to, 0), value);
5849       addptr(to, 4);
5850       subptr(count, 1<<shift);
5851     }
5852     BIND(L_fill_32_bytes);
5853     {
5854       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
5855       movdl(xtmp, value);
5856       if (UseAVX >= 2 && UseUnalignedLoadStores) {
5857         Label L_check_fill_32_bytes;
5858         if (UseAVX > 2) {
5859           // Fill 64-byte chunks
5860           Label L_fill_64_bytes_loop_avx3, L_check_fill_64_bytes_avx2;
5861 
5862           // If number of bytes to fill < VM_Version::avx3_threshold(), perform fill using AVX2
5863           cmpptr(count, VM_Version::avx3_threshold());
5864           jccb(Assembler::below, L_check_fill_64_bytes_avx2);
5865 
5866           vpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
5867 
5868           subptr(count, 16 << shift);
5869           jccb(Assembler::less, L_check_fill_32_bytes);
5870           align(16);
5871 
5872           BIND(L_fill_64_bytes_loop_avx3);
5873           evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
5874           addptr(to, 64);
5875           subptr(count, 16 << shift);
5876           jcc(Assembler::greaterEqual, L_fill_64_bytes_loop_avx3);
5877           jmpb(L_check_fill_32_bytes);
5878 
5879           BIND(L_check_fill_64_bytes_avx2);
5880         }
5881         // Fill 64-byte chunks
5882         Label L_fill_64_bytes_loop;
5883         vpbroadcastd(xtmp, xtmp, Assembler::AVX_256bit);
5884 
5885         subptr(count, 16 << shift);
5886         jcc(Assembler::less, L_check_fill_32_bytes);
5887         align(16);
5888 
5889         BIND(L_fill_64_bytes_loop);
5890         vmovdqu(Address(to, 0), xtmp);
5891         vmovdqu(Address(to, 32), xtmp);
5892         addptr(to, 64);
5893         subptr(count, 16 << shift);
5894         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
5895 
5896         BIND(L_check_fill_32_bytes);
5897         addptr(count, 8 << shift);
5898         jccb(Assembler::less, L_check_fill_8_bytes);
5899         vmovdqu(Address(to, 0), xtmp);
5900         addptr(to, 32);
5901         subptr(count, 8 << shift);
5902 
5903         BIND(L_check_fill_8_bytes);
5904         // clean upper bits of YMM registers
5905         movdl(xtmp, value);
5906         pshufd(xtmp, xtmp, 0);
5907       } else {
5908         // Fill 32-byte chunks
5909         pshufd(xtmp, xtmp, 0);
5910 
5911         subptr(count, 8 << shift);
5912         jcc(Assembler::less, L_check_fill_8_bytes);
5913         align(16);
5914 
5915         BIND(L_fill_32_bytes_loop);
5916 
5917         if (UseUnalignedLoadStores) {
5918           movdqu(Address(to, 0), xtmp);
5919           movdqu(Address(to, 16), xtmp);
5920         } else {
5921           movq(Address(to, 0), xtmp);
5922           movq(Address(to, 8), xtmp);
5923           movq(Address(to, 16), xtmp);
5924           movq(Address(to, 24), xtmp);
5925         }
5926 
5927         addptr(to, 32);
5928         subptr(count, 8 << shift);
5929         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
5930 
5931         BIND(L_check_fill_8_bytes);
5932       }
5933       addptr(count, 8 << shift);
5934       jccb(Assembler::zero, L_exit);
5935       jmpb(L_fill_8_bytes);
5936 
5937       //
5938       // length is too short, just fill qwords
5939       //
5940       BIND(L_fill_8_bytes_loop);
5941       movq(Address(to, 0), xtmp);
5942       addptr(to, 8);
5943       BIND(L_fill_8_bytes);
5944       subptr(count, 1 << (shift + 1));
5945       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
5946     }
5947   }
5948   // fill trailing 4 bytes
5949   BIND(L_fill_4_bytes);
5950   testl(count, 1<<shift);
5951   jccb(Assembler::zero, L_fill_2_bytes);
5952   movl(Address(to, 0), value);
5953   if (t == T_BYTE || t == T_SHORT) {
5954     Label L_fill_byte;
5955     addptr(to, 4);
5956     BIND(L_fill_2_bytes);
5957     // fill trailing 2 bytes
5958     testl(count, 1<<(shift-1));
5959     jccb(Assembler::zero, L_fill_byte);
5960     movw(Address(to, 0), value);
5961     if (t == T_BYTE) {
5962       addptr(to, 2);
5963       BIND(L_fill_byte);
5964       // fill trailing byte
5965       testl(count, 1);
5966       jccb(Assembler::zero, L_exit);
5967       movb(Address(to, 0), value);
5968     } else {
5969       BIND(L_fill_byte);
5970     }
5971   } else {
5972     BIND(L_fill_2_bytes);
5973   }
5974   BIND(L_exit);
5975 }
5976 
5977 void MacroAssembler::evpbroadcast(BasicType type, XMMRegister dst, Register src, int vector_len) {
5978   switch(type) {
5979     case T_BYTE:
5980     case T_BOOLEAN:
5981       evpbroadcastb(dst, src, vector_len);
5982       break;
5983     case T_SHORT:
5984     case T_CHAR:
5985       evpbroadcastw(dst, src, vector_len);
5986       break;
5987     case T_INT:
5988     case T_FLOAT:
5989       evpbroadcastd(dst, src, vector_len);
5990       break;
5991     case T_LONG:
5992     case T_DOUBLE:
5993       evpbroadcastq(dst, src, vector_len);
5994       break;
5995     default:
5996       fatal("Unhandled type : %s", type2name(type));
5997       break;
5998   }
5999 }
6000 
6001 // encode char[] to byte[] in ISO_8859_1 or ASCII
6002    //@IntrinsicCandidate
6003    //private static int implEncodeISOArray(byte[] sa, int sp,
6004    //byte[] da, int dp, int len) {
6005    //  int i = 0;
6006    //  for (; i < len; i++) {
6007    //    char c = StringUTF16.getChar(sa, sp++);
6008    //    if (c > '\u00FF')
6009    //      break;
6010    //    da[dp++] = (byte)c;
6011    //  }
6012    //  return i;
6013    //}
6014    //
6015    //@IntrinsicCandidate
6016    //private static int implEncodeAsciiArray(char[] sa, int sp,
6017    //    byte[] da, int dp, int len) {
6018    //  int i = 0;
6019    //  for (; i < len; i++) {
6020    //    char c = sa[sp++];
6021    //    if (c >= '\u0080')
6022    //      break;
6023    //    da[dp++] = (byte)c;
6024    //  }
6025    //  return i;
6026    //}
6027 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
6028   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
6029   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
6030   Register tmp5, Register result, bool ascii) {
6031 
6032   // rsi: src
6033   // rdi: dst
6034   // rdx: len
6035   // rcx: tmp5
6036   // rax: result
6037   ShortBranchVerifier sbv(this);
6038   assert_different_registers(src, dst, len, tmp5, result);
6039   Label L_done, L_copy_1_char, L_copy_1_char_exit;
6040 
6041   int mask = ascii ? 0xff80ff80 : 0xff00ff00;
6042   int short_mask = ascii ? 0xff80 : 0xff00;
6043 
6044   // set result
6045   xorl(result, result);
6046   // check for zero length
6047   testl(len, len);
6048   jcc(Assembler::zero, L_done);
6049 
6050   movl(result, len);
6051 
6052   // Setup pointers
6053   lea(src, Address(src, len, Address::times_2)); // char[]
6054   lea(dst, Address(dst, len, Address::times_1)); // byte[]
6055   negptr(len);
6056 
6057   if (UseSSE42Intrinsics || UseAVX >= 2) {
6058     Label L_copy_8_chars, L_copy_8_chars_exit;
6059     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
6060 
6061     if (UseAVX >= 2) {
6062       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
6063       movl(tmp5, mask);   // create mask to test for Unicode or non-ASCII chars in vector
6064       movdl(tmp1Reg, tmp5);
6065       vpbroadcastd(tmp1Reg, tmp1Reg, Assembler::AVX_256bit);
6066       jmp(L_chars_32_check);
6067 
6068       bind(L_copy_32_chars);
6069       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
6070       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
6071       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
6072       vptest(tmp2Reg, tmp1Reg);       // check for Unicode or non-ASCII chars in vector
6073       jccb(Assembler::notZero, L_copy_32_chars_exit);
6074       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
6075       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
6076       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
6077 
6078       bind(L_chars_32_check);
6079       addptr(len, 32);
6080       jcc(Assembler::lessEqual, L_copy_32_chars);
6081 
6082       bind(L_copy_32_chars_exit);
6083       subptr(len, 16);
6084       jccb(Assembler::greater, L_copy_16_chars_exit);
6085 
6086     } else if (UseSSE42Intrinsics) {
6087       movl(tmp5, mask);   // create mask to test for Unicode or non-ASCII chars in vector
6088       movdl(tmp1Reg, tmp5);
6089       pshufd(tmp1Reg, tmp1Reg, 0);
6090       jmpb(L_chars_16_check);
6091     }
6092 
6093     bind(L_copy_16_chars);
6094     if (UseAVX >= 2) {
6095       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
6096       vptest(tmp2Reg, tmp1Reg);
6097       jcc(Assembler::notZero, L_copy_16_chars_exit);
6098       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
6099       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
6100     } else {
6101       if (UseAVX > 0) {
6102         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
6103         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
6104         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
6105       } else {
6106         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
6107         por(tmp2Reg, tmp3Reg);
6108         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
6109         por(tmp2Reg, tmp4Reg);
6110       }
6111       ptest(tmp2Reg, tmp1Reg);       // check for Unicode or non-ASCII chars in vector
6112       jccb(Assembler::notZero, L_copy_16_chars_exit);
6113       packuswb(tmp3Reg, tmp4Reg);
6114     }
6115     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
6116 
6117     bind(L_chars_16_check);
6118     addptr(len, 16);
6119     jcc(Assembler::lessEqual, L_copy_16_chars);
6120 
6121     bind(L_copy_16_chars_exit);
6122     if (UseAVX >= 2) {
6123       // clean upper bits of YMM registers
6124       vpxor(tmp2Reg, tmp2Reg);
6125       vpxor(tmp3Reg, tmp3Reg);
6126       vpxor(tmp4Reg, tmp4Reg);
6127       movdl(tmp1Reg, tmp5);
6128       pshufd(tmp1Reg, tmp1Reg, 0);
6129     }
6130     subptr(len, 8);
6131     jccb(Assembler::greater, L_copy_8_chars_exit);
6132 
6133     bind(L_copy_8_chars);
6134     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
6135     ptest(tmp3Reg, tmp1Reg);
6136     jccb(Assembler::notZero, L_copy_8_chars_exit);
6137     packuswb(tmp3Reg, tmp1Reg);
6138     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
6139     addptr(len, 8);
6140     jccb(Assembler::lessEqual, L_copy_8_chars);
6141 
6142     bind(L_copy_8_chars_exit);
6143     subptr(len, 8);
6144     jccb(Assembler::zero, L_done);
6145   }
6146 
6147   bind(L_copy_1_char);
6148   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
6149   testl(tmp5, short_mask);      // check if Unicode or non-ASCII char
6150   jccb(Assembler::notZero, L_copy_1_char_exit);
6151   movb(Address(dst, len, Address::times_1, 0), tmp5);
6152   addptr(len, 1);
6153   jccb(Assembler::less, L_copy_1_char);
6154 
6155   bind(L_copy_1_char_exit);
6156   addptr(result, len); // len is negative count of not processed elements
6157 
6158   bind(L_done);
6159 }
6160 
6161 /**
6162  * Helper for multiply_to_len().
6163  */
6164 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
6165   addq(dest_lo, src1);
6166   adcq(dest_hi, 0);
6167   addq(dest_lo, src2);
6168   adcq(dest_hi, 0);
6169 }
6170 
6171 /**
6172  * Multiply 64 bit by 64 bit first loop.
6173  */
6174 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
6175                                            Register y, Register y_idx, Register z,
6176                                            Register carry, Register product,
6177                                            Register idx, Register kdx) {
6178   //
6179   //  jlong carry, x[], y[], z[];
6180   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
6181   //    huge_128 product = y[idx] * x[xstart] + carry;
6182   //    z[kdx] = (jlong)product;
6183   //    carry  = (jlong)(product >>> 64);
6184   //  }
6185   //  z[xstart] = carry;
6186   //
6187 
6188   Label L_first_loop, L_first_loop_exit;
6189   Label L_one_x, L_one_y, L_multiply;
6190 
6191   decrementl(xstart);
6192   jcc(Assembler::negative, L_one_x);
6193 
6194   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
6195   rorq(x_xstart, 32); // convert big-endian to little-endian
6196 
6197   bind(L_first_loop);
6198   decrementl(idx);
6199   jcc(Assembler::negative, L_first_loop_exit);
6200   decrementl(idx);
6201   jcc(Assembler::negative, L_one_y);
6202   movq(y_idx, Address(y, idx, Address::times_4,  0));
6203   rorq(y_idx, 32); // convert big-endian to little-endian
6204   bind(L_multiply);
6205   movq(product, x_xstart);
6206   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
6207   addq(product, carry);
6208   adcq(rdx, 0);
6209   subl(kdx, 2);
6210   movl(Address(z, kdx, Address::times_4,  4), product);
6211   shrq(product, 32);
6212   movl(Address(z, kdx, Address::times_4,  0), product);
6213   movq(carry, rdx);
6214   jmp(L_first_loop);
6215 
6216   bind(L_one_y);
6217   movl(y_idx, Address(y,  0));
6218   jmp(L_multiply);
6219 
6220   bind(L_one_x);
6221   movl(x_xstart, Address(x,  0));
6222   jmp(L_first_loop);
6223 
6224   bind(L_first_loop_exit);
6225 }
6226 
6227 /**
6228  * Multiply 64 bit by 64 bit and add 128 bit.
6229  */
6230 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
6231                                             Register yz_idx, Register idx,
6232                                             Register carry, Register product, int offset) {
6233   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
6234   //     z[kdx] = (jlong)product;
6235 
6236   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
6237   rorq(yz_idx, 32); // convert big-endian to little-endian
6238   movq(product, x_xstart);
6239   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
6240   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
6241   rorq(yz_idx, 32); // convert big-endian to little-endian
6242 
6243   add2_with_carry(rdx, product, carry, yz_idx);
6244 
6245   movl(Address(z, idx, Address::times_4,  offset+4), product);
6246   shrq(product, 32);
6247   movl(Address(z, idx, Address::times_4,  offset), product);
6248 
6249 }
6250 
6251 /**
6252  * Multiply 128 bit by 128 bit. Unrolled inner loop.
6253  */
6254 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
6255                                              Register yz_idx, Register idx, Register jdx,
6256                                              Register carry, Register product,
6257                                              Register carry2) {
6258   //   jlong carry, x[], y[], z[];
6259   //   int kdx = ystart+1;
6260   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
6261   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
6262   //     z[kdx+idx+1] = (jlong)product;
6263   //     jlong carry2  = (jlong)(product >>> 64);
6264   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
6265   //     z[kdx+idx] = (jlong)product;
6266   //     carry  = (jlong)(product >>> 64);
6267   //   }
6268   //   idx += 2;
6269   //   if (idx > 0) {
6270   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
6271   //     z[kdx+idx] = (jlong)product;
6272   //     carry  = (jlong)(product >>> 64);
6273   //   }
6274   //
6275 
6276   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
6277 
6278   movl(jdx, idx);
6279   andl(jdx, 0xFFFFFFFC);
6280   shrl(jdx, 2);
6281 
6282   bind(L_third_loop);
6283   subl(jdx, 1);
6284   jcc(Assembler::negative, L_third_loop_exit);
6285   subl(idx, 4);
6286 
6287   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
6288   movq(carry2, rdx);
6289 
6290   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
6291   movq(carry, rdx);
6292   jmp(L_third_loop);
6293 
6294   bind (L_third_loop_exit);
6295 
6296   andl (idx, 0x3);
6297   jcc(Assembler::zero, L_post_third_loop_done);
6298 
6299   Label L_check_1;
6300   subl(idx, 2);
6301   jcc(Assembler::negative, L_check_1);
6302 
6303   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
6304   movq(carry, rdx);
6305 
6306   bind (L_check_1);
6307   addl (idx, 0x2);
6308   andl (idx, 0x1);
6309   subl(idx, 1);
6310   jcc(Assembler::negative, L_post_third_loop_done);
6311 
6312   movl(yz_idx, Address(y, idx, Address::times_4,  0));
6313   movq(product, x_xstart);
6314   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
6315   movl(yz_idx, Address(z, idx, Address::times_4,  0));
6316 
6317   add2_with_carry(rdx, product, yz_idx, carry);
6318 
6319   movl(Address(z, idx, Address::times_4,  0), product);
6320   shrq(product, 32);
6321 
6322   shlq(rdx, 32);
6323   orq(product, rdx);
6324   movq(carry, product);
6325 
6326   bind(L_post_third_loop_done);
6327 }
6328 
6329 /**
6330  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
6331  *
6332  */
6333 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
6334                                                   Register carry, Register carry2,
6335                                                   Register idx, Register jdx,
6336                                                   Register yz_idx1, Register yz_idx2,
6337                                                   Register tmp, Register tmp3, Register tmp4) {
6338   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
6339 
6340   //   jlong carry, x[], y[], z[];
6341   //   int kdx = ystart+1;
6342   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
6343   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
6344   //     jlong carry2  = (jlong)(tmp3 >>> 64);
6345   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
6346   //     carry  = (jlong)(tmp4 >>> 64);
6347   //     z[kdx+idx+1] = (jlong)tmp3;
6348   //     z[kdx+idx] = (jlong)tmp4;
6349   //   }
6350   //   idx += 2;
6351   //   if (idx > 0) {
6352   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
6353   //     z[kdx+idx] = (jlong)yz_idx1;
6354   //     carry  = (jlong)(yz_idx1 >>> 64);
6355   //   }
6356   //
6357 
6358   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
6359 
6360   movl(jdx, idx);
6361   andl(jdx, 0xFFFFFFFC);
6362   shrl(jdx, 2);
6363 
6364   bind(L_third_loop);
6365   subl(jdx, 1);
6366   jcc(Assembler::negative, L_third_loop_exit);
6367   subl(idx, 4);
6368 
6369   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
6370   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
6371   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
6372   rorxq(yz_idx2, yz_idx2, 32);
6373 
6374   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
6375   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
6376 
6377   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
6378   rorxq(yz_idx1, yz_idx1, 32);
6379   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
6380   rorxq(yz_idx2, yz_idx2, 32);
6381 
6382   if (VM_Version::supports_adx()) {
6383     adcxq(tmp3, carry);
6384     adoxq(tmp3, yz_idx1);
6385 
6386     adcxq(tmp4, tmp);
6387     adoxq(tmp4, yz_idx2);
6388 
6389     movl(carry, 0); // does not affect flags
6390     adcxq(carry2, carry);
6391     adoxq(carry2, carry);
6392   } else {
6393     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
6394     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
6395   }
6396   movq(carry, carry2);
6397 
6398   movl(Address(z, idx, Address::times_4, 12), tmp3);
6399   shrq(tmp3, 32);
6400   movl(Address(z, idx, Address::times_4,  8), tmp3);
6401 
6402   movl(Address(z, idx, Address::times_4,  4), tmp4);
6403   shrq(tmp4, 32);
6404   movl(Address(z, idx, Address::times_4,  0), tmp4);
6405 
6406   jmp(L_third_loop);
6407 
6408   bind (L_third_loop_exit);
6409 
6410   andl (idx, 0x3);
6411   jcc(Assembler::zero, L_post_third_loop_done);
6412 
6413   Label L_check_1;
6414   subl(idx, 2);
6415   jcc(Assembler::negative, L_check_1);
6416 
6417   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
6418   rorxq(yz_idx1, yz_idx1, 32);
6419   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
6420   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
6421   rorxq(yz_idx2, yz_idx2, 32);
6422 
6423   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
6424 
6425   movl(Address(z, idx, Address::times_4,  4), tmp3);
6426   shrq(tmp3, 32);
6427   movl(Address(z, idx, Address::times_4,  0), tmp3);
6428   movq(carry, tmp4);
6429 
6430   bind (L_check_1);
6431   addl (idx, 0x2);
6432   andl (idx, 0x1);
6433   subl(idx, 1);
6434   jcc(Assembler::negative, L_post_third_loop_done);
6435   movl(tmp4, Address(y, idx, Address::times_4,  0));
6436   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
6437   movl(tmp4, Address(z, idx, Address::times_4,  0));
6438 
6439   add2_with_carry(carry2, tmp3, tmp4, carry);
6440 
6441   movl(Address(z, idx, Address::times_4,  0), tmp3);
6442   shrq(tmp3, 32);
6443 
6444   shlq(carry2, 32);
6445   orq(tmp3, carry2);
6446   movq(carry, tmp3);
6447 
6448   bind(L_post_third_loop_done);
6449 }
6450 
6451 /**
6452  * Code for BigInteger::multiplyToLen() intrinsic.
6453  *
6454  * rdi: x
6455  * rax: xlen
6456  * rsi: y
6457  * rcx: ylen
6458  * r8:  z
6459  * r11: tmp0
6460  * r12: tmp1
6461  * r13: tmp2
6462  * r14: tmp3
6463  * r15: tmp4
6464  * rbx: tmp5
6465  *
6466  */
6467 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register tmp0,
6468                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
6469   ShortBranchVerifier sbv(this);
6470   assert_different_registers(x, xlen, y, ylen, z, tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
6471 
6472   push(tmp0);
6473   push(tmp1);
6474   push(tmp2);
6475   push(tmp3);
6476   push(tmp4);
6477   push(tmp5);
6478 
6479   push(xlen);
6480 
6481   const Register idx = tmp1;
6482   const Register kdx = tmp2;
6483   const Register xstart = tmp3;
6484 
6485   const Register y_idx = tmp4;
6486   const Register carry = tmp5;
6487   const Register product  = xlen;
6488   const Register x_xstart = tmp0;
6489 
6490   // First Loop.
6491   //
6492   //  final static long LONG_MASK = 0xffffffffL;
6493   //  int xstart = xlen - 1;
6494   //  int ystart = ylen - 1;
6495   //  long carry = 0;
6496   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
6497   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
6498   //    z[kdx] = (int)product;
6499   //    carry = product >>> 32;
6500   //  }
6501   //  z[xstart] = (int)carry;
6502   //
6503 
6504   movl(idx, ylen);               // idx = ylen;
6505   lea(kdx, Address(xlen, ylen)); // kdx = xlen+ylen;
6506   xorq(carry, carry);            // carry = 0;
6507 
6508   Label L_done;
6509 
6510   movl(xstart, xlen);
6511   decrementl(xstart);
6512   jcc(Assembler::negative, L_done);
6513 
6514   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
6515 
6516   Label L_second_loop;
6517   testl(kdx, kdx);
6518   jcc(Assembler::zero, L_second_loop);
6519 
6520   Label L_carry;
6521   subl(kdx, 1);
6522   jcc(Assembler::zero, L_carry);
6523 
6524   movl(Address(z, kdx, Address::times_4,  0), carry);
6525   shrq(carry, 32);
6526   subl(kdx, 1);
6527 
6528   bind(L_carry);
6529   movl(Address(z, kdx, Address::times_4,  0), carry);
6530 
6531   // Second and third (nested) loops.
6532   //
6533   // for (int i = xstart-1; i >= 0; i--) { // Second loop
6534   //   carry = 0;
6535   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
6536   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
6537   //                    (z[k] & LONG_MASK) + carry;
6538   //     z[k] = (int)product;
6539   //     carry = product >>> 32;
6540   //   }
6541   //   z[i] = (int)carry;
6542   // }
6543   //
6544   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
6545 
6546   const Register jdx = tmp1;
6547 
6548   bind(L_second_loop);
6549   xorl(carry, carry);    // carry = 0;
6550   movl(jdx, ylen);       // j = ystart+1
6551 
6552   subl(xstart, 1);       // i = xstart-1;
6553   jcc(Assembler::negative, L_done);
6554 
6555   push (z);
6556 
6557   Label L_last_x;
6558   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
6559   subl(xstart, 1);       // i = xstart-1;
6560   jcc(Assembler::negative, L_last_x);
6561 
6562   if (UseBMI2Instructions) {
6563     movq(rdx,  Address(x, xstart, Address::times_4,  0));
6564     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
6565   } else {
6566     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
6567     rorq(x_xstart, 32);  // convert big-endian to little-endian
6568   }
6569 
6570   Label L_third_loop_prologue;
6571   bind(L_third_loop_prologue);
6572 
6573   push (x);
6574   push (xstart);
6575   push (ylen);
6576 
6577 
6578   if (UseBMI2Instructions) {
6579     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
6580   } else { // !UseBMI2Instructions
6581     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
6582   }
6583 
6584   pop(ylen);
6585   pop(xlen);
6586   pop(x);
6587   pop(z);
6588 
6589   movl(tmp3, xlen);
6590   addl(tmp3, 1);
6591   movl(Address(z, tmp3, Address::times_4,  0), carry);
6592   subl(tmp3, 1);
6593   jccb(Assembler::negative, L_done);
6594 
6595   shrq(carry, 32);
6596   movl(Address(z, tmp3, Address::times_4,  0), carry);
6597   jmp(L_second_loop);
6598 
6599   // Next infrequent code is moved outside loops.
6600   bind(L_last_x);
6601   if (UseBMI2Instructions) {
6602     movl(rdx, Address(x,  0));
6603   } else {
6604     movl(x_xstart, Address(x,  0));
6605   }
6606   jmp(L_third_loop_prologue);
6607 
6608   bind(L_done);
6609 
6610   pop(xlen);
6611 
6612   pop(tmp5);
6613   pop(tmp4);
6614   pop(tmp3);
6615   pop(tmp2);
6616   pop(tmp1);
6617   pop(tmp0);
6618 }
6619 
6620 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
6621   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
6622   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
6623   Label VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
6624   Label VECTOR8_TAIL, VECTOR4_TAIL;
6625   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
6626   Label SAME_TILL_END, DONE;
6627   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
6628 
6629   //scale is in rcx in both Win64 and Unix
6630   ShortBranchVerifier sbv(this);
6631 
6632   shlq(length);
6633   xorq(result, result);
6634 
6635   if ((AVX3Threshold == 0) && (UseAVX > 2) &&
6636       VM_Version::supports_avx512vlbw()) {
6637     Label VECTOR64_LOOP, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
6638 
6639     cmpq(length, 64);
6640     jcc(Assembler::less, VECTOR32_TAIL);
6641 
6642     movq(tmp1, length);
6643     andq(tmp1, 0x3F);      // tail count
6644     andq(length, ~(0x3F)); //vector count
6645 
6646     bind(VECTOR64_LOOP);
6647     // AVX512 code to compare 64 byte vectors.
6648     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
6649     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
6650     kortestql(k7, k7);
6651     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
6652     addq(result, 64);
6653     subq(length, 64);
6654     jccb(Assembler::notZero, VECTOR64_LOOP);
6655 
6656     //bind(VECTOR64_TAIL);
6657     testq(tmp1, tmp1);
6658     jcc(Assembler::zero, SAME_TILL_END);
6659 
6660     //bind(VECTOR64_TAIL);
6661     // AVX512 code to compare up to 63 byte vectors.
6662     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
6663     shlxq(tmp2, tmp2, tmp1);
6664     notq(tmp2);
6665     kmovql(k3, tmp2);
6666 
6667     evmovdqub(rymm0, k3, Address(obja, result), false, Assembler::AVX_512bit);
6668     evpcmpeqb(k7, k3, rymm0, Address(objb, result), Assembler::AVX_512bit);
6669 
6670     ktestql(k7, k3);
6671     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
6672 
6673     bind(VECTOR64_NOT_EQUAL);
6674     kmovql(tmp1, k7);
6675     notq(tmp1);
6676     tzcntq(tmp1, tmp1);
6677     addq(result, tmp1);
6678     shrq(result);
6679     jmp(DONE);
6680     bind(VECTOR32_TAIL);
6681   }
6682 
6683   cmpq(length, 8);
6684   jcc(Assembler::equal, VECTOR8_LOOP);
6685   jcc(Assembler::less, VECTOR4_TAIL);
6686 
6687   if (UseAVX >= 2) {
6688     Label VECTOR16_TAIL, VECTOR32_LOOP;
6689 
6690     cmpq(length, 16);
6691     jcc(Assembler::equal, VECTOR16_LOOP);
6692     jcc(Assembler::less, VECTOR8_LOOP);
6693 
6694     cmpq(length, 32);
6695     jccb(Assembler::less, VECTOR16_TAIL);
6696 
6697     subq(length, 32);
6698     bind(VECTOR32_LOOP);
6699     vmovdqu(rymm0, Address(obja, result));
6700     vmovdqu(rymm1, Address(objb, result));
6701     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
6702     vptest(rymm2, rymm2);
6703     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
6704     addq(result, 32);
6705     subq(length, 32);
6706     jcc(Assembler::greaterEqual, VECTOR32_LOOP);
6707     addq(length, 32);
6708     jcc(Assembler::equal, SAME_TILL_END);
6709     //falling through if less than 32 bytes left //close the branch here.
6710 
6711     bind(VECTOR16_TAIL);
6712     cmpq(length, 16);
6713     jccb(Assembler::less, VECTOR8_TAIL);
6714     bind(VECTOR16_LOOP);
6715     movdqu(rymm0, Address(obja, result));
6716     movdqu(rymm1, Address(objb, result));
6717     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
6718     ptest(rymm2, rymm2);
6719     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
6720     addq(result, 16);
6721     subq(length, 16);
6722     jcc(Assembler::equal, SAME_TILL_END);
6723     //falling through if less than 16 bytes left
6724   } else {//regular intrinsics
6725 
6726     cmpq(length, 16);
6727     jccb(Assembler::less, VECTOR8_TAIL);
6728 
6729     subq(length, 16);
6730     bind(VECTOR16_LOOP);
6731     movdqu(rymm0, Address(obja, result));
6732     movdqu(rymm1, Address(objb, result));
6733     pxor(rymm0, rymm1);
6734     ptest(rymm0, rymm0);
6735     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
6736     addq(result, 16);
6737     subq(length, 16);
6738     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
6739     addq(length, 16);
6740     jcc(Assembler::equal, SAME_TILL_END);
6741     //falling through if less than 16 bytes left
6742   }
6743 
6744   bind(VECTOR8_TAIL);
6745   cmpq(length, 8);
6746   jccb(Assembler::less, VECTOR4_TAIL);
6747   bind(VECTOR8_LOOP);
6748   movq(tmp1, Address(obja, result));
6749   movq(tmp2, Address(objb, result));
6750   xorq(tmp1, tmp2);
6751   testq(tmp1, tmp1);
6752   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
6753   addq(result, 8);
6754   subq(length, 8);
6755   jcc(Assembler::equal, SAME_TILL_END);
6756   //falling through if less than 8 bytes left
6757 
6758   bind(VECTOR4_TAIL);
6759   cmpq(length, 4);
6760   jccb(Assembler::less, BYTES_TAIL);
6761   bind(VECTOR4_LOOP);
6762   movl(tmp1, Address(obja, result));
6763   xorl(tmp1, Address(objb, result));
6764   testl(tmp1, tmp1);
6765   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
6766   addq(result, 4);
6767   subq(length, 4);
6768   jcc(Assembler::equal, SAME_TILL_END);
6769   //falling through if less than 4 bytes left
6770 
6771   bind(BYTES_TAIL);
6772   bind(BYTES_LOOP);
6773   load_unsigned_byte(tmp1, Address(obja, result));
6774   load_unsigned_byte(tmp2, Address(objb, result));
6775   xorl(tmp1, tmp2);
6776   testl(tmp1, tmp1);
6777   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
6778   decq(length);
6779   jcc(Assembler::zero, SAME_TILL_END);
6780   incq(result);
6781   load_unsigned_byte(tmp1, Address(obja, result));
6782   load_unsigned_byte(tmp2, Address(objb, result));
6783   xorl(tmp1, tmp2);
6784   testl(tmp1, tmp1);
6785   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
6786   decq(length);
6787   jcc(Assembler::zero, SAME_TILL_END);
6788   incq(result);
6789   load_unsigned_byte(tmp1, Address(obja, result));
6790   load_unsigned_byte(tmp2, Address(objb, result));
6791   xorl(tmp1, tmp2);
6792   testl(tmp1, tmp1);
6793   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
6794   jmp(SAME_TILL_END);
6795 
6796   if (UseAVX >= 2) {
6797     bind(VECTOR32_NOT_EQUAL);
6798     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
6799     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
6800     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
6801     vpmovmskb(tmp1, rymm0);
6802     bsfq(tmp1, tmp1);
6803     addq(result, tmp1);
6804     shrq(result);
6805     jmp(DONE);
6806   }
6807 
6808   bind(VECTOR16_NOT_EQUAL);
6809   if (UseAVX >= 2) {
6810     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
6811     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
6812     pxor(rymm0, rymm2);
6813   } else {
6814     pcmpeqb(rymm2, rymm2);
6815     pxor(rymm0, rymm1);
6816     pcmpeqb(rymm0, rymm1);
6817     pxor(rymm0, rymm2);
6818   }
6819   pmovmskb(tmp1, rymm0);
6820   bsfq(tmp1, tmp1);
6821   addq(result, tmp1);
6822   shrq(result);
6823   jmpb(DONE);
6824 
6825   bind(VECTOR8_NOT_EQUAL);
6826   bind(VECTOR4_NOT_EQUAL);
6827   bsfq(tmp1, tmp1);
6828   shrq(tmp1, 3);
6829   addq(result, tmp1);
6830   bind(BYTES_NOT_EQUAL);
6831   shrq(result);
6832   jmpb(DONE);
6833 
6834   bind(SAME_TILL_END);
6835   mov64(result, -1);
6836 
6837   bind(DONE);
6838 }
6839 
6840 //Helper functions for square_to_len()
6841 
6842 /**
6843  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
6844  * Preserves x and z and modifies rest of the registers.
6845  */
6846 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
6847   // Perform square and right shift by 1
6848   // Handle odd xlen case first, then for even xlen do the following
6849   // jlong carry = 0;
6850   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
6851   //     huge_128 product = x[j:j+1] * x[j:j+1];
6852   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
6853   //     z[i+2:i+3] = (jlong)(product >>> 1);
6854   //     carry = (jlong)product;
6855   // }
6856 
6857   xorq(tmp5, tmp5);     // carry
6858   xorq(rdxReg, rdxReg);
6859   xorl(tmp1, tmp1);     // index for x
6860   xorl(tmp4, tmp4);     // index for z
6861 
6862   Label L_first_loop, L_first_loop_exit;
6863 
6864   testl(xlen, 1);
6865   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
6866 
6867   // Square and right shift by 1 the odd element using 32 bit multiply
6868   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
6869   imulq(raxReg, raxReg);
6870   shrq(raxReg, 1);
6871   adcq(tmp5, 0);
6872   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
6873   incrementl(tmp1);
6874   addl(tmp4, 2);
6875 
6876   // Square and  right shift by 1 the rest using 64 bit multiply
6877   bind(L_first_loop);
6878   cmpptr(tmp1, xlen);
6879   jccb(Assembler::equal, L_first_loop_exit);
6880 
6881   // Square
6882   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
6883   rorq(raxReg, 32);    // convert big-endian to little-endian
6884   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
6885 
6886   // Right shift by 1 and save carry
6887   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
6888   rcrq(rdxReg, 1);
6889   rcrq(raxReg, 1);
6890   adcq(tmp5, 0);
6891 
6892   // Store result in z
6893   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
6894   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
6895 
6896   // Update indices for x and z
6897   addl(tmp1, 2);
6898   addl(tmp4, 4);
6899   jmp(L_first_loop);
6900 
6901   bind(L_first_loop_exit);
6902 }
6903 
6904 
6905 /**
6906  * Perform the following multiply add operation using BMI2 instructions
6907  * carry:sum = sum + op1*op2 + carry
6908  * op2 should be in rdx
6909  * op2 is preserved, all other registers are modified
6910  */
6911 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
6912   // assert op2 is rdx
6913   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
6914   addq(sum, carry);
6915   adcq(tmp2, 0);
6916   addq(sum, op1);
6917   adcq(tmp2, 0);
6918   movq(carry, tmp2);
6919 }
6920 
6921 /**
6922  * Perform the following multiply add operation:
6923  * carry:sum = sum + op1*op2 + carry
6924  * Preserves op1, op2 and modifies rest of registers
6925  */
6926 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
6927   // rdx:rax = op1 * op2
6928   movq(raxReg, op2);
6929   mulq(op1);
6930 
6931   //  rdx:rax = sum + carry + rdx:rax
6932   addq(sum, carry);
6933   adcq(rdxReg, 0);
6934   addq(sum, raxReg);
6935   adcq(rdxReg, 0);
6936 
6937   // carry:sum = rdx:sum
6938   movq(carry, rdxReg);
6939 }
6940 
6941 /**
6942  * Add 64 bit long carry into z[] with carry propagation.
6943  * Preserves z and carry register values and modifies rest of registers.
6944  *
6945  */
6946 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
6947   Label L_fourth_loop, L_fourth_loop_exit;
6948 
6949   movl(tmp1, 1);
6950   subl(zlen, 2);
6951   addq(Address(z, zlen, Address::times_4, 0), carry);
6952 
6953   bind(L_fourth_loop);
6954   jccb(Assembler::carryClear, L_fourth_loop_exit);
6955   subl(zlen, 2);
6956   jccb(Assembler::negative, L_fourth_loop_exit);
6957   addq(Address(z, zlen, Address::times_4, 0), tmp1);
6958   jmp(L_fourth_loop);
6959   bind(L_fourth_loop_exit);
6960 }
6961 
6962 /**
6963  * Shift z[] left by 1 bit.
6964  * Preserves x, len, z and zlen registers and modifies rest of the registers.
6965  *
6966  */
6967 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
6968 
6969   Label L_fifth_loop, L_fifth_loop_exit;
6970 
6971   // Fifth loop
6972   // Perform primitiveLeftShift(z, zlen, 1)
6973 
6974   const Register prev_carry = tmp1;
6975   const Register new_carry = tmp4;
6976   const Register value = tmp2;
6977   const Register zidx = tmp3;
6978 
6979   // int zidx, carry;
6980   // long value;
6981   // carry = 0;
6982   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
6983   //    (carry:value)  = (z[i] << 1) | carry ;
6984   //    z[i] = value;
6985   // }
6986 
6987   movl(zidx, zlen);
6988   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
6989 
6990   bind(L_fifth_loop);
6991   decl(zidx);  // Use decl to preserve carry flag
6992   decl(zidx);
6993   jccb(Assembler::negative, L_fifth_loop_exit);
6994 
6995   if (UseBMI2Instructions) {
6996      movq(value, Address(z, zidx, Address::times_4, 0));
6997      rclq(value, 1);
6998      rorxq(value, value, 32);
6999      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
7000   }
7001   else {
7002     // clear new_carry
7003     xorl(new_carry, new_carry);
7004 
7005     // Shift z[i] by 1, or in previous carry and save new carry
7006     movq(value, Address(z, zidx, Address::times_4, 0));
7007     shlq(value, 1);
7008     adcl(new_carry, 0);
7009 
7010     orq(value, prev_carry);
7011     rorq(value, 0x20);
7012     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
7013 
7014     // Set previous carry = new carry
7015     movl(prev_carry, new_carry);
7016   }
7017   jmp(L_fifth_loop);
7018 
7019   bind(L_fifth_loop_exit);
7020 }
7021 
7022 
7023 /**
7024  * Code for BigInteger::squareToLen() intrinsic
7025  *
7026  * rdi: x
7027  * rsi: len
7028  * r8:  z
7029  * rcx: zlen
7030  * r12: tmp1
7031  * r13: tmp2
7032  * r14: tmp3
7033  * r15: tmp4
7034  * rbx: tmp5
7035  *
7036  */
7037 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) {
7038 
7039   Label L_second_loop, L_second_loop_exit, L_third_loop, L_third_loop_exit, L_last_x, L_multiply;
7040   push(tmp1);
7041   push(tmp2);
7042   push(tmp3);
7043   push(tmp4);
7044   push(tmp5);
7045 
7046   // First loop
7047   // Store the squares, right shifted one bit (i.e., divided by 2).
7048   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
7049 
7050   // Add in off-diagonal sums.
7051   //
7052   // Second, third (nested) and fourth loops.
7053   // zlen +=2;
7054   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
7055   //    carry = 0;
7056   //    long op2 = x[xidx:xidx+1];
7057   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
7058   //       k -= 2;
7059   //       long op1 = x[j:j+1];
7060   //       long sum = z[k:k+1];
7061   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
7062   //       z[k:k+1] = sum;
7063   //    }
7064   //    add_one_64(z, k, carry, tmp_regs);
7065   // }
7066 
7067   const Register carry = tmp5;
7068   const Register sum = tmp3;
7069   const Register op1 = tmp4;
7070   Register op2 = tmp2;
7071 
7072   push(zlen);
7073   push(len);
7074   addl(zlen,2);
7075   bind(L_second_loop);
7076   xorq(carry, carry);
7077   subl(zlen, 4);
7078   subl(len, 2);
7079   push(zlen);
7080   push(len);
7081   cmpl(len, 0);
7082   jccb(Assembler::lessEqual, L_second_loop_exit);
7083 
7084   // Multiply an array by one 64 bit long.
7085   if (UseBMI2Instructions) {
7086     op2 = rdxReg;
7087     movq(op2, Address(x, len, Address::times_4,  0));
7088     rorxq(op2, op2, 32);
7089   }
7090   else {
7091     movq(op2, Address(x, len, Address::times_4,  0));
7092     rorq(op2, 32);
7093   }
7094 
7095   bind(L_third_loop);
7096   decrementl(len);
7097   jccb(Assembler::negative, L_third_loop_exit);
7098   decrementl(len);
7099   jccb(Assembler::negative, L_last_x);
7100 
7101   movq(op1, Address(x, len, Address::times_4,  0));
7102   rorq(op1, 32);
7103 
7104   bind(L_multiply);
7105   subl(zlen, 2);
7106   movq(sum, Address(z, zlen, Address::times_4,  0));
7107 
7108   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
7109   if (UseBMI2Instructions) {
7110     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
7111   }
7112   else {
7113     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
7114   }
7115 
7116   movq(Address(z, zlen, Address::times_4, 0), sum);
7117 
7118   jmp(L_third_loop);
7119   bind(L_third_loop_exit);
7120 
7121   // Fourth loop
7122   // Add 64 bit long carry into z with carry propagation.
7123   // Uses offsetted zlen.
7124   add_one_64(z, zlen, carry, tmp1);
7125 
7126   pop(len);
7127   pop(zlen);
7128   jmp(L_second_loop);
7129 
7130   // Next infrequent code is moved outside loops.
7131   bind(L_last_x);
7132   movl(op1, Address(x, 0));
7133   jmp(L_multiply);
7134 
7135   bind(L_second_loop_exit);
7136   pop(len);
7137   pop(zlen);
7138   pop(len);
7139   pop(zlen);
7140 
7141   // Fifth loop
7142   // Shift z left 1 bit.
7143   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
7144 
7145   // z[zlen-1] |= x[len-1] & 1;
7146   movl(tmp3, Address(x, len, Address::times_4, -4));
7147   andl(tmp3, 1);
7148   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
7149 
7150   pop(tmp5);
7151   pop(tmp4);
7152   pop(tmp3);
7153   pop(tmp2);
7154   pop(tmp1);
7155 }
7156 
7157 /**
7158  * Helper function for mul_add()
7159  * Multiply the in[] by int k and add to out[] starting at offset offs using
7160  * 128 bit by 32 bit multiply and return the carry in tmp5.
7161  * Only quad int aligned length of in[] is operated on in this function.
7162  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
7163  * This function preserves out, in and k registers.
7164  * len and offset point to the appropriate index in "in" & "out" correspondingly
7165  * tmp5 has the carry.
7166  * other registers are temporary and are modified.
7167  *
7168  */
7169 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
7170   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
7171   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
7172 
7173   Label L_first_loop, L_first_loop_exit;
7174 
7175   movl(tmp1, len);
7176   shrl(tmp1, 2);
7177 
7178   bind(L_first_loop);
7179   subl(tmp1, 1);
7180   jccb(Assembler::negative, L_first_loop_exit);
7181 
7182   subl(len, 4);
7183   subl(offset, 4);
7184 
7185   Register op2 = tmp2;
7186   const Register sum = tmp3;
7187   const Register op1 = tmp4;
7188   const Register carry = tmp5;
7189 
7190   if (UseBMI2Instructions) {
7191     op2 = rdxReg;
7192   }
7193 
7194   movq(op1, Address(in, len, Address::times_4,  8));
7195   rorq(op1, 32);
7196   movq(sum, Address(out, offset, Address::times_4,  8));
7197   rorq(sum, 32);
7198   if (UseBMI2Instructions) {
7199     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
7200   }
7201   else {
7202     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
7203   }
7204   // Store back in big endian from little endian
7205   rorq(sum, 0x20);
7206   movq(Address(out, offset, Address::times_4,  8), sum);
7207 
7208   movq(op1, Address(in, len, Address::times_4,  0));
7209   rorq(op1, 32);
7210   movq(sum, Address(out, offset, Address::times_4,  0));
7211   rorq(sum, 32);
7212   if (UseBMI2Instructions) {
7213     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
7214   }
7215   else {
7216     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
7217   }
7218   // Store back in big endian from little endian
7219   rorq(sum, 0x20);
7220   movq(Address(out, offset, Address::times_4,  0), sum);
7221 
7222   jmp(L_first_loop);
7223   bind(L_first_loop_exit);
7224 }
7225 
7226 /**
7227  * Code for BigInteger::mulAdd() intrinsic
7228  *
7229  * rdi: out
7230  * rsi: in
7231  * r11: offs (out.length - offset)
7232  * rcx: len
7233  * r8:  k
7234  * r12: tmp1
7235  * r13: tmp2
7236  * r14: tmp3
7237  * r15: tmp4
7238  * rbx: tmp5
7239  * Multiply the in[] by word k and add to out[], return the carry in rax
7240  */
7241 void MacroAssembler::mul_add(Register out, Register in, Register offs,
7242    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
7243    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
7244 
7245   Label L_carry, L_last_in, L_done;
7246 
7247 // carry = 0;
7248 // for (int j=len-1; j >= 0; j--) {
7249 //    long product = (in[j] & LONG_MASK) * kLong +
7250 //                   (out[offs] & LONG_MASK) + carry;
7251 //    out[offs--] = (int)product;
7252 //    carry = product >>> 32;
7253 // }
7254 //
7255   push(tmp1);
7256   push(tmp2);
7257   push(tmp3);
7258   push(tmp4);
7259   push(tmp5);
7260 
7261   Register op2 = tmp2;
7262   const Register sum = tmp3;
7263   const Register op1 = tmp4;
7264   const Register carry =  tmp5;
7265 
7266   if (UseBMI2Instructions) {
7267     op2 = rdxReg;
7268     movl(op2, k);
7269   }
7270   else {
7271     movl(op2, k);
7272   }
7273 
7274   xorq(carry, carry);
7275 
7276   //First loop
7277 
7278   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
7279   //The carry is in tmp5
7280   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
7281 
7282   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
7283   decrementl(len);
7284   jccb(Assembler::negative, L_carry);
7285   decrementl(len);
7286   jccb(Assembler::negative, L_last_in);
7287 
7288   movq(op1, Address(in, len, Address::times_4,  0));
7289   rorq(op1, 32);
7290 
7291   subl(offs, 2);
7292   movq(sum, Address(out, offs, Address::times_4,  0));
7293   rorq(sum, 32);
7294 
7295   if (UseBMI2Instructions) {
7296     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
7297   }
7298   else {
7299     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
7300   }
7301 
7302   // Store back in big endian from little endian
7303   rorq(sum, 0x20);
7304   movq(Address(out, offs, Address::times_4,  0), sum);
7305 
7306   testl(len, len);
7307   jccb(Assembler::zero, L_carry);
7308 
7309   //Multiply the last in[] entry, if any
7310   bind(L_last_in);
7311   movl(op1, Address(in, 0));
7312   movl(sum, Address(out, offs, Address::times_4,  -4));
7313 
7314   movl(raxReg, k);
7315   mull(op1); //tmp4 * eax -> edx:eax
7316   addl(sum, carry);
7317   adcl(rdxReg, 0);
7318   addl(sum, raxReg);
7319   adcl(rdxReg, 0);
7320   movl(carry, rdxReg);
7321 
7322   movl(Address(out, offs, Address::times_4,  -4), sum);
7323 
7324   bind(L_carry);
7325   //return tmp5/carry as carry in rax
7326   movl(rax, carry);
7327 
7328   bind(L_done);
7329   pop(tmp5);
7330   pop(tmp4);
7331   pop(tmp3);
7332   pop(tmp2);
7333   pop(tmp1);
7334 }
7335 
7336 /**
7337  * Emits code to update CRC-32 with a byte value according to constants in table
7338  *
7339  * @param [in,out]crc   Register containing the crc.
7340  * @param [in]val       Register containing the byte to fold into the CRC.
7341  * @param [in]table     Register containing the table of crc constants.
7342  *
7343  * uint32_t crc;
7344  * val = crc_table[(val ^ crc) & 0xFF];
7345  * crc = val ^ (crc >> 8);
7346  *
7347  */
7348 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
7349   xorl(val, crc);
7350   andl(val, 0xFF);
7351   shrl(crc, 8); // unsigned shift
7352   xorl(crc, Address(table, val, Address::times_4, 0));
7353 }
7354 
7355 /**
7356  * Fold 128-bit data chunk
7357  */
7358 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
7359   if (UseAVX > 0) {
7360     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
7361     vpclmulldq(xcrc, xK, xcrc); // [63:0]
7362     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
7363     pxor(xcrc, xtmp);
7364   } else {
7365     movdqa(xtmp, xcrc);
7366     pclmulhdq(xtmp, xK);   // [123:64]
7367     pclmulldq(xcrc, xK);   // [63:0]
7368     pxor(xcrc, xtmp);
7369     movdqu(xtmp, Address(buf, offset));
7370     pxor(xcrc, xtmp);
7371   }
7372 }
7373 
7374 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
7375   if (UseAVX > 0) {
7376     vpclmulhdq(xtmp, xK, xcrc);
7377     vpclmulldq(xcrc, xK, xcrc);
7378     pxor(xcrc, xbuf);
7379     pxor(xcrc, xtmp);
7380   } else {
7381     movdqa(xtmp, xcrc);
7382     pclmulhdq(xtmp, xK);
7383     pclmulldq(xcrc, xK);
7384     pxor(xcrc, xbuf);
7385     pxor(xcrc, xtmp);
7386   }
7387 }
7388 
7389 /**
7390  * 8-bit folds to compute 32-bit CRC
7391  *
7392  * uint64_t xcrc;
7393  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
7394  */
7395 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
7396   movdl(tmp, xcrc);
7397   andl(tmp, 0xFF);
7398   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
7399   psrldq(xcrc, 1); // unsigned shift one byte
7400   pxor(xcrc, xtmp);
7401 }
7402 
7403 /**
7404  * uint32_t crc;
7405  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
7406  */
7407 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
7408   movl(tmp, crc);
7409   andl(tmp, 0xFF);
7410   shrl(crc, 8);
7411   xorl(crc, Address(table, tmp, Address::times_4, 0));
7412 }
7413 
7414 /**
7415  * @param crc   register containing existing CRC (32-bit)
7416  * @param buf   register pointing to input byte buffer (byte*)
7417  * @param len   register containing number of bytes
7418  * @param table register that will contain address of CRC table
7419  * @param tmp   scratch register
7420  */
7421 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
7422   assert_different_registers(crc, buf, len, table, tmp, rax);
7423 
7424   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
7425   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
7426 
7427   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
7428   // context for the registers used, where all instructions below are using 128-bit mode
7429   // On EVEX without VL and BW, these instructions will all be AVX.
7430   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
7431   notl(crc); // ~crc
7432   cmpl(len, 16);
7433   jcc(Assembler::less, L_tail);
7434 
7435   // Align buffer to 16 bytes
7436   movl(tmp, buf);
7437   andl(tmp, 0xF);
7438   jccb(Assembler::zero, L_aligned);
7439   subl(tmp,  16);
7440   addl(len, tmp);
7441 
7442   align(4);
7443   BIND(L_align_loop);
7444   movsbl(rax, Address(buf, 0)); // load byte with sign extension
7445   update_byte_crc32(crc, rax, table);
7446   increment(buf);
7447   incrementl(tmp);
7448   jccb(Assembler::less, L_align_loop);
7449 
7450   BIND(L_aligned);
7451   movl(tmp, len); // save
7452   shrl(len, 4);
7453   jcc(Assembler::zero, L_tail_restore);
7454 
7455   // Fold crc into first bytes of vector
7456   movdqa(xmm1, Address(buf, 0));
7457   movdl(rax, xmm1);
7458   xorl(crc, rax);
7459   if (VM_Version::supports_sse4_1()) {
7460     pinsrd(xmm1, crc, 0);
7461   } else {
7462     pinsrw(xmm1, crc, 0);
7463     shrl(crc, 16);
7464     pinsrw(xmm1, crc, 1);
7465   }
7466   addptr(buf, 16);
7467   subl(len, 4); // len > 0
7468   jcc(Assembler::less, L_fold_tail);
7469 
7470   movdqa(xmm2, Address(buf,  0));
7471   movdqa(xmm3, Address(buf, 16));
7472   movdqa(xmm4, Address(buf, 32));
7473   addptr(buf, 48);
7474   subl(len, 3);
7475   jcc(Assembler::lessEqual, L_fold_512b);
7476 
7477   // Fold total 512 bits of polynomial on each iteration,
7478   // 128 bits per each of 4 parallel streams.
7479   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32), rscratch1);
7480 
7481   align32();
7482   BIND(L_fold_512b_loop);
7483   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
7484   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
7485   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
7486   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
7487   addptr(buf, 64);
7488   subl(len, 4);
7489   jcc(Assembler::greater, L_fold_512b_loop);
7490 
7491   // Fold 512 bits to 128 bits.
7492   BIND(L_fold_512b);
7493   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16), rscratch1);
7494   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
7495   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
7496   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
7497 
7498   // Fold the rest of 128 bits data chunks
7499   BIND(L_fold_tail);
7500   addl(len, 3);
7501   jccb(Assembler::lessEqual, L_fold_128b);
7502   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16), rscratch1);
7503 
7504   BIND(L_fold_tail_loop);
7505   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
7506   addptr(buf, 16);
7507   decrementl(len);
7508   jccb(Assembler::greater, L_fold_tail_loop);
7509 
7510   // Fold 128 bits in xmm1 down into 32 bits in crc register.
7511   BIND(L_fold_128b);
7512   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()), rscratch1);
7513   if (UseAVX > 0) {
7514     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
7515     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
7516     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
7517   } else {
7518     movdqa(xmm2, xmm0);
7519     pclmulqdq(xmm2, xmm1, 0x1);
7520     movdqa(xmm3, xmm0);
7521     pand(xmm3, xmm2);
7522     pclmulqdq(xmm0, xmm3, 0x1);
7523   }
7524   psrldq(xmm1, 8);
7525   psrldq(xmm2, 4);
7526   pxor(xmm0, xmm1);
7527   pxor(xmm0, xmm2);
7528 
7529   // 8 8-bit folds to compute 32-bit CRC.
7530   for (int j = 0; j < 4; j++) {
7531     fold_8bit_crc32(xmm0, table, xmm1, rax);
7532   }
7533   movdl(crc, xmm0); // mov 32 bits to general register
7534   for (int j = 0; j < 4; j++) {
7535     fold_8bit_crc32(crc, table, rax);
7536   }
7537 
7538   BIND(L_tail_restore);
7539   movl(len, tmp); // restore
7540   BIND(L_tail);
7541   andl(len, 0xf);
7542   jccb(Assembler::zero, L_exit);
7543 
7544   // Fold the rest of bytes
7545   align(4);
7546   BIND(L_tail_loop);
7547   movsbl(rax, Address(buf, 0)); // load byte with sign extension
7548   update_byte_crc32(crc, rax, table);
7549   increment(buf);
7550   decrementl(len);
7551   jccb(Assembler::greater, L_tail_loop);
7552 
7553   BIND(L_exit);
7554   notl(crc); // ~c
7555 }
7556 
7557 // Helper function for AVX 512 CRC32
7558 // Fold 512-bit data chunks
7559 void MacroAssembler::fold512bit_crc32_avx512(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf,
7560                                              Register pos, int offset) {
7561   evmovdquq(xmm3, Address(buf, pos, Address::times_1, offset), Assembler::AVX_512bit);
7562   evpclmulqdq(xtmp, xcrc, xK, 0x10, Assembler::AVX_512bit); // [123:64]
7563   evpclmulqdq(xmm2, xcrc, xK, 0x01, Assembler::AVX_512bit); // [63:0]
7564   evpxorq(xcrc, xtmp, xmm2, Assembler::AVX_512bit /* vector_len */);
7565   evpxorq(xcrc, xcrc, xmm3, Assembler::AVX_512bit /* vector_len */);
7566 }
7567 
7568 // Helper function for AVX 512 CRC32
7569 // Compute CRC32 for < 256B buffers
7570 void MacroAssembler::kernel_crc32_avx512_256B(Register crc, Register buf, Register len, Register table, Register pos,
7571                                               Register tmp1, Register tmp2, Label& L_barrett, Label& L_16B_reduction_loop,
7572                                               Label& L_get_last_two_xmms, Label& L_128_done, Label& L_cleanup) {
7573 
7574   Label L_less_than_32, L_exact_16_left, L_less_than_16_left;
7575   Label L_less_than_8_left, L_less_than_4_left, L_less_than_2_left, L_zero_left;
7576   Label L_only_less_than_4, L_only_less_than_3, L_only_less_than_2;
7577 
7578   // check if there is enough buffer to be able to fold 16B at a time
7579   cmpl(len, 32);
7580   jcc(Assembler::less, L_less_than_32);
7581 
7582   // if there is, load the constants
7583   movdqu(xmm10, Address(table, 1 * 16));    //rk1 and rk2 in xmm10
7584   movdl(xmm0, crc);                        // get the initial crc value
7585   movdqu(xmm7, Address(buf, pos, Address::times_1, 0 * 16)); //load the plaintext
7586   pxor(xmm7, xmm0);
7587 
7588   // update the buffer pointer
7589   addl(pos, 16);
7590   //update the counter.subtract 32 instead of 16 to save one instruction from the loop
7591   subl(len, 32);
7592   jmp(L_16B_reduction_loop);
7593 
7594   bind(L_less_than_32);
7595   //mov initial crc to the return value. this is necessary for zero - length buffers.
7596   movl(rax, crc);
7597   testl(len, len);
7598   jcc(Assembler::equal, L_cleanup);
7599 
7600   movdl(xmm0, crc);                        //get the initial crc value
7601 
7602   cmpl(len, 16);
7603   jcc(Assembler::equal, L_exact_16_left);
7604   jcc(Assembler::less, L_less_than_16_left);
7605 
7606   movdqu(xmm7, Address(buf, pos, Address::times_1, 0 * 16)); //load the plaintext
7607   pxor(xmm7, xmm0);                       //xor the initial crc value
7608   addl(pos, 16);
7609   subl(len, 16);
7610   movdqu(xmm10, Address(table, 1 * 16));    // rk1 and rk2 in xmm10
7611   jmp(L_get_last_two_xmms);
7612 
7613   bind(L_less_than_16_left);
7614   //use stack space to load data less than 16 bytes, zero - out the 16B in memory first.
7615   pxor(xmm1, xmm1);
7616   movptr(tmp1, rsp);
7617   movdqu(Address(tmp1, 0 * 16), xmm1);
7618 
7619   cmpl(len, 4);
7620   jcc(Assembler::less, L_only_less_than_4);
7621 
7622   //backup the counter value
7623   movl(tmp2, len);
7624   cmpl(len, 8);
7625   jcc(Assembler::less, L_less_than_8_left);
7626 
7627   //load 8 Bytes
7628   movq(rax, Address(buf, pos, Address::times_1, 0 * 16));
7629   movq(Address(tmp1, 0 * 16), rax);
7630   addptr(tmp1, 8);
7631   subl(len, 8);
7632   addl(pos, 8);
7633 
7634   bind(L_less_than_8_left);
7635   cmpl(len, 4);
7636   jcc(Assembler::less, L_less_than_4_left);
7637 
7638   //load 4 Bytes
7639   movl(rax, Address(buf, pos, Address::times_1, 0));
7640   movl(Address(tmp1, 0 * 16), rax);
7641   addptr(tmp1, 4);
7642   subl(len, 4);
7643   addl(pos, 4);
7644 
7645   bind(L_less_than_4_left);
7646   cmpl(len, 2);
7647   jcc(Assembler::less, L_less_than_2_left);
7648 
7649   // load 2 Bytes
7650   movw(rax, Address(buf, pos, Address::times_1, 0));
7651   movl(Address(tmp1, 0 * 16), rax);
7652   addptr(tmp1, 2);
7653   subl(len, 2);
7654   addl(pos, 2);
7655 
7656   bind(L_less_than_2_left);
7657   cmpl(len, 1);
7658   jcc(Assembler::less, L_zero_left);
7659 
7660   // load 1 Byte
7661   movb(rax, Address(buf, pos, Address::times_1, 0));
7662   movb(Address(tmp1, 0 * 16), rax);
7663 
7664   bind(L_zero_left);
7665   movdqu(xmm7, Address(rsp, 0));
7666   pxor(xmm7, xmm0);                       //xor the initial crc value
7667 
7668   lea(rax, ExternalAddress(StubRoutines::x86::shuf_table_crc32_avx512_addr()));
7669   movdqu(xmm0, Address(rax, tmp2));
7670   pshufb(xmm7, xmm0);
7671   jmp(L_128_done);
7672 
7673   bind(L_exact_16_left);
7674   movdqu(xmm7, Address(buf, pos, Address::times_1, 0));
7675   pxor(xmm7, xmm0);                       //xor the initial crc value
7676   jmp(L_128_done);
7677 
7678   bind(L_only_less_than_4);
7679   cmpl(len, 3);
7680   jcc(Assembler::less, L_only_less_than_3);
7681 
7682   // load 3 Bytes
7683   movb(rax, Address(buf, pos, Address::times_1, 0));
7684   movb(Address(tmp1, 0), rax);
7685 
7686   movb(rax, Address(buf, pos, Address::times_1, 1));
7687   movb(Address(tmp1, 1), rax);
7688 
7689   movb(rax, Address(buf, pos, Address::times_1, 2));
7690   movb(Address(tmp1, 2), rax);
7691 
7692   movdqu(xmm7, Address(rsp, 0));
7693   pxor(xmm7, xmm0);                     //xor the initial crc value
7694 
7695   pslldq(xmm7, 0x5);
7696   jmp(L_barrett);
7697   bind(L_only_less_than_3);
7698   cmpl(len, 2);
7699   jcc(Assembler::less, L_only_less_than_2);
7700 
7701   // load 2 Bytes
7702   movb(rax, Address(buf, pos, Address::times_1, 0));
7703   movb(Address(tmp1, 0), rax);
7704 
7705   movb(rax, Address(buf, pos, Address::times_1, 1));
7706   movb(Address(tmp1, 1), rax);
7707 
7708   movdqu(xmm7, Address(rsp, 0));
7709   pxor(xmm7, xmm0);                     //xor the initial crc value
7710 
7711   pslldq(xmm7, 0x6);
7712   jmp(L_barrett);
7713 
7714   bind(L_only_less_than_2);
7715   //load 1 Byte
7716   movb(rax, Address(buf, pos, Address::times_1, 0));
7717   movb(Address(tmp1, 0), rax);
7718 
7719   movdqu(xmm7, Address(rsp, 0));
7720   pxor(xmm7, xmm0);                     //xor the initial crc value
7721 
7722   pslldq(xmm7, 0x7);
7723 }
7724 
7725 /**
7726 * Compute CRC32 using AVX512 instructions
7727 * param crc   register containing existing CRC (32-bit)
7728 * param buf   register pointing to input byte buffer (byte*)
7729 * param len   register containing number of bytes
7730 * param table address of crc or crc32c table
7731 * param tmp1  scratch register
7732 * param tmp2  scratch register
7733 * return rax  result register
7734 *
7735 * This routine is identical for crc32c with the exception of the precomputed constant
7736 * table which will be passed as the table argument.  The calculation steps are
7737 * the same for both variants.
7738 */
7739 void MacroAssembler::kernel_crc32_avx512(Register crc, Register buf, Register len, Register table, Register tmp1, Register tmp2) {
7740   assert_different_registers(crc, buf, len, table, tmp1, tmp2, rax, r12);
7741 
7742   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
7743   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
7744   Label L_less_than_256, L_fold_128_B_loop, L_fold_256_B_loop;
7745   Label L_fold_128_B_register, L_final_reduction_for_128, L_16B_reduction_loop;
7746   Label L_128_done, L_get_last_two_xmms, L_barrett, L_cleanup;
7747 
7748   const Register pos = r12;
7749   push(r12);
7750   subptr(rsp, 16 * 2 + 8);
7751 
7752   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
7753   // context for the registers used, where all instructions below are using 128-bit mode
7754   // On EVEX without VL and BW, these instructions will all be AVX.
7755   movl(pos, 0);
7756 
7757   // check if smaller than 256B
7758   cmpl(len, 256);
7759   jcc(Assembler::less, L_less_than_256);
7760 
7761   // load the initial crc value
7762   movdl(xmm10, crc);
7763 
7764   // receive the initial 64B data, xor the initial crc value
7765   evmovdquq(xmm0, Address(buf, pos, Address::times_1, 0 * 64), Assembler::AVX_512bit);
7766   evmovdquq(xmm4, Address(buf, pos, Address::times_1, 1 * 64), Assembler::AVX_512bit);
7767   evpxorq(xmm0, xmm0, xmm10, Assembler::AVX_512bit);
7768   evbroadcasti32x4(xmm10, Address(table, 2 * 16), Assembler::AVX_512bit); //zmm10 has rk3 and rk4
7769 
7770   subl(len, 256);
7771   cmpl(len, 256);
7772   jcc(Assembler::less, L_fold_128_B_loop);
7773 
7774   evmovdquq(xmm7, Address(buf, pos, Address::times_1, 2 * 64), Assembler::AVX_512bit);
7775   evmovdquq(xmm8, Address(buf, pos, Address::times_1, 3 * 64), Assembler::AVX_512bit);
7776   evbroadcasti32x4(xmm16, Address(table, 0 * 16), Assembler::AVX_512bit); //zmm16 has rk-1 and rk-2
7777   subl(len, 256);
7778 
7779   bind(L_fold_256_B_loop);
7780   addl(pos, 256);
7781   fold512bit_crc32_avx512(xmm0, xmm16, xmm1, buf, pos, 0 * 64);
7782   fold512bit_crc32_avx512(xmm4, xmm16, xmm1, buf, pos, 1 * 64);
7783   fold512bit_crc32_avx512(xmm7, xmm16, xmm1, buf, pos, 2 * 64);
7784   fold512bit_crc32_avx512(xmm8, xmm16, xmm1, buf, pos, 3 * 64);
7785 
7786   subl(len, 256);
7787   jcc(Assembler::greaterEqual, L_fold_256_B_loop);
7788 
7789   // Fold 256 into 128
7790   addl(pos, 256);
7791   evpclmulqdq(xmm1, xmm0, xmm10, 0x01, Assembler::AVX_512bit);
7792   evpclmulqdq(xmm2, xmm0, xmm10, 0x10, Assembler::AVX_512bit);
7793   vpternlogq(xmm7, 0x96, xmm1, xmm2, Assembler::AVX_512bit); // xor ABC
7794 
7795   evpclmulqdq(xmm5, xmm4, xmm10, 0x01, Assembler::AVX_512bit);
7796   evpclmulqdq(xmm6, xmm4, xmm10, 0x10, Assembler::AVX_512bit);
7797   vpternlogq(xmm8, 0x96, xmm5, xmm6, Assembler::AVX_512bit); // xor ABC
7798 
7799   evmovdquq(xmm0, xmm7, Assembler::AVX_512bit);
7800   evmovdquq(xmm4, xmm8, Assembler::AVX_512bit);
7801 
7802   addl(len, 128);
7803   jmp(L_fold_128_B_register);
7804 
7805   // at this section of the code, there is 128 * x + y(0 <= y<128) bytes of buffer.The fold_128_B_loop
7806   // loop will fold 128B at a time until we have 128 + y Bytes of buffer
7807 
7808   // fold 128B at a time.This section of the code folds 8 xmm registers in parallel
7809   bind(L_fold_128_B_loop);
7810   addl(pos, 128);
7811   fold512bit_crc32_avx512(xmm0, xmm10, xmm1, buf, pos, 0 * 64);
7812   fold512bit_crc32_avx512(xmm4, xmm10, xmm1, buf, pos, 1 * 64);
7813 
7814   subl(len, 128);
7815   jcc(Assembler::greaterEqual, L_fold_128_B_loop);
7816 
7817   addl(pos, 128);
7818 
7819   // at this point, the buffer pointer is pointing at the last y Bytes of the buffer, where 0 <= y < 128
7820   // the 128B of folded data is in 8 of the xmm registers : xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7
7821   bind(L_fold_128_B_register);
7822   evmovdquq(xmm16, Address(table, 5 * 16), Assembler::AVX_512bit); // multiply by rk9-rk16
7823   evmovdquq(xmm11, Address(table, 9 * 16), Assembler::AVX_512bit); // multiply by rk17-rk20, rk1,rk2, 0,0
7824   evpclmulqdq(xmm1, xmm0, xmm16, 0x01, Assembler::AVX_512bit);
7825   evpclmulqdq(xmm2, xmm0, xmm16, 0x10, Assembler::AVX_512bit);
7826   // save last that has no multiplicand
7827   vextracti64x2(xmm7, xmm4, 3);
7828 
7829   evpclmulqdq(xmm5, xmm4, xmm11, 0x01, Assembler::AVX_512bit);
7830   evpclmulqdq(xmm6, xmm4, xmm11, 0x10, Assembler::AVX_512bit);
7831   // Needed later in reduction loop
7832   movdqu(xmm10, Address(table, 1 * 16));
7833   vpternlogq(xmm1, 0x96, xmm2, xmm5, Assembler::AVX_512bit); // xor ABC
7834   vpternlogq(xmm1, 0x96, xmm6, xmm7, Assembler::AVX_512bit); // xor ABC
7835 
7836   // Swap 1,0,3,2 - 01 00 11 10
7837   evshufi64x2(xmm8, xmm1, xmm1, 0x4e, Assembler::AVX_512bit);
7838   evpxorq(xmm8, xmm8, xmm1, Assembler::AVX_256bit);
7839   vextracti128(xmm5, xmm8, 1);
7840   evpxorq(xmm7, xmm5, xmm8, Assembler::AVX_128bit);
7841 
7842   // instead of 128, we add 128 - 16 to the loop counter to save 1 instruction from the loop
7843   // instead of a cmp instruction, we use the negative flag with the jl instruction
7844   addl(len, 128 - 16);
7845   jcc(Assembler::less, L_final_reduction_for_128);
7846 
7847   bind(L_16B_reduction_loop);
7848   vpclmulqdq(xmm8, xmm7, xmm10, 0x01);
7849   vpclmulqdq(xmm7, xmm7, xmm10, 0x10);
7850   vpxor(xmm7, xmm7, xmm8, Assembler::AVX_128bit);
7851   movdqu(xmm0, Address(buf, pos, Address::times_1, 0 * 16));
7852   vpxor(xmm7, xmm7, xmm0, Assembler::AVX_128bit);
7853   addl(pos, 16);
7854   subl(len, 16);
7855   jcc(Assembler::greaterEqual, L_16B_reduction_loop);
7856 
7857   bind(L_final_reduction_for_128);
7858   addl(len, 16);
7859   jcc(Assembler::equal, L_128_done);
7860 
7861   bind(L_get_last_two_xmms);
7862   movdqu(xmm2, xmm7);
7863   addl(pos, len);
7864   movdqu(xmm1, Address(buf, pos, Address::times_1, -16));
7865   subl(pos, len);
7866 
7867   // get rid of the extra data that was loaded before
7868   // load the shift constant
7869   lea(rax, ExternalAddress(StubRoutines::x86::shuf_table_crc32_avx512_addr()));
7870   movdqu(xmm0, Address(rax, len));
7871   addl(rax, len);
7872 
7873   vpshufb(xmm7, xmm7, xmm0, Assembler::AVX_128bit);
7874   //Change mask to 512
7875   vpxor(xmm0, xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_avx512_addr() + 2 * 16), Assembler::AVX_128bit, tmp2);
7876   vpshufb(xmm2, xmm2, xmm0, Assembler::AVX_128bit);
7877 
7878   blendvpb(xmm2, xmm2, xmm1, xmm0, Assembler::AVX_128bit);
7879   vpclmulqdq(xmm8, xmm7, xmm10, 0x01);
7880   vpclmulqdq(xmm7, xmm7, xmm10, 0x10);
7881   vpxor(xmm7, xmm7, xmm8, Assembler::AVX_128bit);
7882   vpxor(xmm7, xmm7, xmm2, Assembler::AVX_128bit);
7883 
7884   bind(L_128_done);
7885   // compute crc of a 128-bit value
7886   movdqu(xmm10, Address(table, 3 * 16));
7887   movdqu(xmm0, xmm7);
7888 
7889   // 64b fold
7890   vpclmulqdq(xmm7, xmm7, xmm10, 0x0);
7891   vpsrldq(xmm0, xmm0, 0x8, Assembler::AVX_128bit);
7892   vpxor(xmm7, xmm7, xmm0, Assembler::AVX_128bit);
7893 
7894   // 32b fold
7895   movdqu(xmm0, xmm7);
7896   vpslldq(xmm7, xmm7, 0x4, Assembler::AVX_128bit);
7897   vpclmulqdq(xmm7, xmm7, xmm10, 0x10);
7898   vpxor(xmm7, xmm7, xmm0, Assembler::AVX_128bit);
7899   jmp(L_barrett);
7900 
7901   bind(L_less_than_256);
7902   kernel_crc32_avx512_256B(crc, buf, len, table, pos, tmp1, tmp2, L_barrett, L_16B_reduction_loop, L_get_last_two_xmms, L_128_done, L_cleanup);
7903 
7904   //barrett reduction
7905   bind(L_barrett);
7906   vpand(xmm7, xmm7, ExternalAddress(StubRoutines::x86::crc_by128_masks_avx512_addr() + 1 * 16), Assembler::AVX_128bit, tmp2);
7907   movdqu(xmm1, xmm7);
7908   movdqu(xmm2, xmm7);
7909   movdqu(xmm10, Address(table, 4 * 16));
7910 
7911   pclmulqdq(xmm7, xmm10, 0x0);
7912   pxor(xmm7, xmm2);
7913   vpand(xmm7, xmm7, ExternalAddress(StubRoutines::x86::crc_by128_masks_avx512_addr()), Assembler::AVX_128bit, tmp2);
7914   movdqu(xmm2, xmm7);
7915   pclmulqdq(xmm7, xmm10, 0x10);
7916   pxor(xmm7, xmm2);
7917   pxor(xmm7, xmm1);
7918   pextrd(crc, xmm7, 2);
7919 
7920   bind(L_cleanup);
7921   addptr(rsp, 16 * 2 + 8);
7922   pop(r12);
7923 }
7924 
7925 // S. Gueron / Information Processing Letters 112 (2012) 184
7926 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
7927 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
7928 // Output: the 64-bit carry-less product of B * CONST
7929 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
7930                                      Register tmp1, Register tmp2, Register tmp3) {
7931   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
7932   if (n > 0) {
7933     addq(tmp3, n * 256 * 8);
7934   }
7935   //    Q1 = TABLEExt[n][B & 0xFF];
7936   movl(tmp1, in);
7937   andl(tmp1, 0x000000FF);
7938   shll(tmp1, 3);
7939   addq(tmp1, tmp3);
7940   movq(tmp1, Address(tmp1, 0));
7941 
7942   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
7943   movl(tmp2, in);
7944   shrl(tmp2, 8);
7945   andl(tmp2, 0x000000FF);
7946   shll(tmp2, 3);
7947   addq(tmp2, tmp3);
7948   movq(tmp2, Address(tmp2, 0));
7949 
7950   shlq(tmp2, 8);
7951   xorq(tmp1, tmp2);
7952 
7953   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
7954   movl(tmp2, in);
7955   shrl(tmp2, 16);
7956   andl(tmp2, 0x000000FF);
7957   shll(tmp2, 3);
7958   addq(tmp2, tmp3);
7959   movq(tmp2, Address(tmp2, 0));
7960 
7961   shlq(tmp2, 16);
7962   xorq(tmp1, tmp2);
7963 
7964   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
7965   shrl(in, 24);
7966   andl(in, 0x000000FF);
7967   shll(in, 3);
7968   addq(in, tmp3);
7969   movq(in, Address(in, 0));
7970 
7971   shlq(in, 24);
7972   xorq(in, tmp1);
7973   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
7974 }
7975 
7976 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
7977                                       Register in_out,
7978                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
7979                                       XMMRegister w_xtmp2,
7980                                       Register tmp1,
7981                                       Register n_tmp2, Register n_tmp3) {
7982   if (is_pclmulqdq_supported) {
7983     movdl(w_xtmp1, in_out); // modified blindly
7984 
7985     movl(tmp1, const_or_pre_comp_const_index);
7986     movdl(w_xtmp2, tmp1);
7987     pclmulqdq(w_xtmp1, w_xtmp2, 0);
7988 
7989     movdq(in_out, w_xtmp1);
7990   } else {
7991     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
7992   }
7993 }
7994 
7995 // Recombination Alternative 2: No bit-reflections
7996 // T1 = (CRC_A * U1) << 1
7997 // T2 = (CRC_B * U2) << 1
7998 // C1 = T1 >> 32
7999 // C2 = T2 >> 32
8000 // T1 = T1 & 0xFFFFFFFF
8001 // T2 = T2 & 0xFFFFFFFF
8002 // T1 = CRC32(0, T1)
8003 // T2 = CRC32(0, T2)
8004 // C1 = C1 ^ T1
8005 // C2 = C2 ^ T2
8006 // CRC = C1 ^ C2 ^ CRC_C
8007 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,
8008                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
8009                                      Register tmp1, Register tmp2,
8010                                      Register n_tmp3) {
8011   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
8012   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
8013   shlq(in_out, 1);
8014   movl(tmp1, in_out);
8015   shrq(in_out, 32);
8016   xorl(tmp2, tmp2);
8017   crc32(tmp2, tmp1, 4);
8018   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
8019   shlq(in1, 1);
8020   movl(tmp1, in1);
8021   shrq(in1, 32);
8022   xorl(tmp2, tmp2);
8023   crc32(tmp2, tmp1, 4);
8024   xorl(in1, tmp2);
8025   xorl(in_out, in1);
8026   xorl(in_out, in2);
8027 }
8028 
8029 // Set N to predefined value
8030 // Subtract from a length of a buffer
8031 // execute in a loop:
8032 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
8033 // for i = 1 to N do
8034 //  CRC_A = CRC32(CRC_A, A[i])
8035 //  CRC_B = CRC32(CRC_B, B[i])
8036 //  CRC_C = CRC32(CRC_C, C[i])
8037 // end for
8038 // Recombine
8039 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,
8040                                        Register in_out1, Register in_out2, Register in_out3,
8041                                        Register tmp1, Register tmp2, Register tmp3,
8042                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
8043                                        Register tmp4, Register tmp5,
8044                                        Register n_tmp6) {
8045   Label L_processPartitions;
8046   Label L_processPartition;
8047   Label L_exit;
8048 
8049   bind(L_processPartitions);
8050   cmpl(in_out1, 3 * size);
8051   jcc(Assembler::less, L_exit);
8052     xorl(tmp1, tmp1);
8053     xorl(tmp2, tmp2);
8054     movq(tmp3, in_out2);
8055     addq(tmp3, size);
8056 
8057     bind(L_processPartition);
8058       crc32(in_out3, Address(in_out2, 0), 8);
8059       crc32(tmp1, Address(in_out2, size), 8);
8060       crc32(tmp2, Address(in_out2, size * 2), 8);
8061       addq(in_out2, 8);
8062       cmpq(in_out2, tmp3);
8063       jcc(Assembler::less, L_processPartition);
8064     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
8065             w_xtmp1, w_xtmp2, w_xtmp3,
8066             tmp4, tmp5,
8067             n_tmp6);
8068     addq(in_out2, 2 * size);
8069     subl(in_out1, 3 * size);
8070     jmp(L_processPartitions);
8071 
8072   bind(L_exit);
8073 }
8074 
8075 // Algorithm 2: Pipelined usage of the CRC32 instruction.
8076 // Input: A buffer I of L bytes.
8077 // Output: the CRC32C value of the buffer.
8078 // Notations:
8079 // Write L = 24N + r, with N = floor (L/24).
8080 // r = L mod 24 (0 <= r < 24).
8081 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
8082 // N quadwords, and R consists of r bytes.
8083 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
8084 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
8085 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
8086 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
8087 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
8088                                           Register tmp1, Register tmp2, Register tmp3,
8089                                           Register tmp4, Register tmp5, Register tmp6,
8090                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
8091                                           bool is_pclmulqdq_supported) {
8092   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
8093   Label L_wordByWord;
8094   Label L_byteByByteProlog;
8095   Label L_byteByByte;
8096   Label L_exit;
8097 
8098   if (is_pclmulqdq_supported ) {
8099     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::crc32c_table_addr();
8100     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::crc32c_table_addr() + 1);
8101 
8102     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::crc32c_table_addr() + 2);
8103     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::crc32c_table_addr() + 3);
8104 
8105     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::crc32c_table_addr() + 4);
8106     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::crc32c_table_addr() + 5);
8107     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
8108   } else {
8109     const_or_pre_comp_const_index[0] = 1;
8110     const_or_pre_comp_const_index[1] = 0;
8111 
8112     const_or_pre_comp_const_index[2] = 3;
8113     const_or_pre_comp_const_index[3] = 2;
8114 
8115     const_or_pre_comp_const_index[4] = 5;
8116     const_or_pre_comp_const_index[5] = 4;
8117    }
8118   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
8119                     in2, in1, in_out,
8120                     tmp1, tmp2, tmp3,
8121                     w_xtmp1, w_xtmp2, w_xtmp3,
8122                     tmp4, tmp5,
8123                     tmp6);
8124   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
8125                     in2, in1, in_out,
8126                     tmp1, tmp2, tmp3,
8127                     w_xtmp1, w_xtmp2, w_xtmp3,
8128                     tmp4, tmp5,
8129                     tmp6);
8130   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
8131                     in2, in1, in_out,
8132                     tmp1, tmp2, tmp3,
8133                     w_xtmp1, w_xtmp2, w_xtmp3,
8134                     tmp4, tmp5,
8135                     tmp6);
8136   movl(tmp1, in2);
8137   andl(tmp1, 0x00000007);
8138   negl(tmp1);
8139   addl(tmp1, in2);
8140   addq(tmp1, in1);
8141 
8142   cmpq(in1, tmp1);
8143   jccb(Assembler::greaterEqual, L_byteByByteProlog);
8144   align(16);
8145   BIND(L_wordByWord);
8146     crc32(in_out, Address(in1, 0), 8);
8147     addq(in1, 8);
8148     cmpq(in1, tmp1);
8149     jcc(Assembler::less, L_wordByWord);
8150 
8151   BIND(L_byteByByteProlog);
8152   andl(in2, 0x00000007);
8153   movl(tmp2, 1);
8154 
8155   cmpl(tmp2, in2);
8156   jccb(Assembler::greater, L_exit);
8157   BIND(L_byteByByte);
8158     crc32(in_out, Address(in1, 0), 1);
8159     incq(in1);
8160     incl(tmp2);
8161     cmpl(tmp2, in2);
8162     jcc(Assembler::lessEqual, L_byteByByte);
8163 
8164   BIND(L_exit);
8165 }
8166 #undef BIND
8167 #undef BLOCK_COMMENT
8168 
8169 // Compress char[] array to byte[].
8170 // Intrinsic for java.lang.StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
8171 // Return the array length if every element in array can be encoded,
8172 // otherwise, the index of first non-latin1 (> 0xff) character.
8173 //   @IntrinsicCandidate
8174 //   public static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
8175 //     for (int i = 0; i < len; i++) {
8176 //       char c = src[srcOff];
8177 //       if (c > 0xff) {
8178 //           return i;  // return index of non-latin1 char
8179 //       }
8180 //       dst[dstOff] = (byte)c;
8181 //       srcOff++;
8182 //       dstOff++;
8183 //     }
8184 //     return len;
8185 //   }
8186 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
8187   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8188   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8189   Register tmp5, Register result, KRegister mask1, KRegister mask2) {
8190   Label copy_chars_loop, done, reset_sp, copy_tail;
8191 
8192   // rsi: src
8193   // rdi: dst
8194   // rdx: len
8195   // rcx: tmp5
8196   // rax: result
8197 
8198   // rsi holds start addr of source char[] to be compressed
8199   // rdi holds start addr of destination byte[]
8200   // rdx holds length
8201 
8202   assert(len != result, "");
8203 
8204   // save length for return
8205   movl(result, len);
8206 
8207   if ((AVX3Threshold == 0) && (UseAVX > 2) && // AVX512
8208     VM_Version::supports_avx512vlbw() &&
8209     VM_Version::supports_bmi2()) {
8210 
8211     Label copy_32_loop, copy_loop_tail, below_threshold, reset_for_copy_tail;
8212 
8213     // alignment
8214     Label post_alignment;
8215 
8216     // if length of the string is less than 32, handle it the old fashioned way
8217     testl(len, -32);
8218     jcc(Assembler::zero, below_threshold);
8219 
8220     // First check whether a character is compressible ( <= 0xFF).
8221     // Create mask to test for Unicode chars inside zmm vector
8222     movl(tmp5, 0x00FF);
8223     evpbroadcastw(tmp2Reg, tmp5, Assembler::AVX_512bit);
8224 
8225     testl(len, -64);
8226     jccb(Assembler::zero, post_alignment);
8227 
8228     movl(tmp5, dst);
8229     andl(tmp5, (32 - 1));
8230     negl(tmp5);
8231     andl(tmp5, (32 - 1));
8232 
8233     // bail out when there is nothing to be done
8234     testl(tmp5, 0xFFFFFFFF);
8235     jccb(Assembler::zero, post_alignment);
8236 
8237     // ~(~0 << len), where len is the # of remaining elements to process
8238     movl(len, 0xFFFFFFFF);
8239     shlxl(len, len, tmp5);
8240     notl(len);
8241     kmovdl(mask2, len);
8242     movl(len, result);
8243 
8244     evmovdquw(tmp1Reg, mask2, Address(src, 0), /*merge*/ false, Assembler::AVX_512bit);
8245     evpcmpw(mask1, mask2, tmp1Reg, tmp2Reg, Assembler::le, /*signed*/ false, Assembler::AVX_512bit);
8246     ktestd(mask1, mask2);
8247     jcc(Assembler::carryClear, copy_tail);
8248 
8249     evpmovwb(Address(dst, 0), mask2, tmp1Reg, Assembler::AVX_512bit);
8250 
8251     addptr(src, tmp5);
8252     addptr(src, tmp5);
8253     addptr(dst, tmp5);
8254     subl(len, tmp5);
8255 
8256     bind(post_alignment);
8257     // end of alignment
8258 
8259     movl(tmp5, len);
8260     andl(tmp5, (32 - 1));    // tail count (in chars)
8261     andl(len, ~(32 - 1));    // vector count (in chars)
8262     jccb(Assembler::zero, copy_loop_tail);
8263 
8264     lea(src, Address(src, len, Address::times_2));
8265     lea(dst, Address(dst, len, Address::times_1));
8266     negptr(len);
8267 
8268     bind(copy_32_loop);
8269     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
8270     evpcmpuw(mask1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
8271     kortestdl(mask1, mask1);
8272     jccb(Assembler::carryClear, reset_for_copy_tail);
8273 
8274     // All elements in current processed chunk are valid candidates for
8275     // compression. Write a truncated byte elements to the memory.
8276     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
8277     addptr(len, 32);
8278     jccb(Assembler::notZero, copy_32_loop);
8279 
8280     bind(copy_loop_tail);
8281     // bail out when there is nothing to be done
8282     testl(tmp5, 0xFFFFFFFF);
8283     jcc(Assembler::zero, done);
8284 
8285     movl(len, tmp5);
8286 
8287     // ~(~0 << len), where len is the # of remaining elements to process
8288     movl(tmp5, 0xFFFFFFFF);
8289     shlxl(tmp5, tmp5, len);
8290     notl(tmp5);
8291 
8292     kmovdl(mask2, tmp5);
8293 
8294     evmovdquw(tmp1Reg, mask2, Address(src, 0), /*merge*/ false, Assembler::AVX_512bit);
8295     evpcmpw(mask1, mask2, tmp1Reg, tmp2Reg, Assembler::le, /*signed*/ false, Assembler::AVX_512bit);
8296     ktestd(mask1, mask2);
8297     jcc(Assembler::carryClear, copy_tail);
8298 
8299     evpmovwb(Address(dst, 0), mask2, tmp1Reg, Assembler::AVX_512bit);
8300     jmp(done);
8301 
8302     bind(reset_for_copy_tail);
8303     lea(src, Address(src, tmp5, Address::times_2));
8304     lea(dst, Address(dst, tmp5, Address::times_1));
8305     subptr(len, tmp5);
8306     jmp(copy_chars_loop);
8307 
8308     bind(below_threshold);
8309   }
8310 
8311   if (UseSSE42Intrinsics) {
8312     Label copy_32_loop, copy_16, copy_tail_sse, reset_for_copy_tail;
8313 
8314     // vectored compression
8315     testl(len, 0xfffffff8);
8316     jcc(Assembler::zero, copy_tail);
8317 
8318     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
8319     movdl(tmp1Reg, tmp5);
8320     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
8321 
8322     andl(len, 0xfffffff0);
8323     jccb(Assembler::zero, copy_16);
8324 
8325     // compress 16 chars per iter
8326     pxor(tmp4Reg, tmp4Reg);
8327 
8328     lea(src, Address(src, len, Address::times_2));
8329     lea(dst, Address(dst, len, Address::times_1));
8330     negptr(len);
8331 
8332     bind(copy_32_loop);
8333     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
8334     por(tmp4Reg, tmp2Reg);
8335     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
8336     por(tmp4Reg, tmp3Reg);
8337     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
8338     jccb(Assembler::notZero, reset_for_copy_tail);
8339     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
8340     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
8341     addptr(len, 16);
8342     jccb(Assembler::notZero, copy_32_loop);
8343 
8344     // compress next vector of 8 chars (if any)
8345     bind(copy_16);
8346     // len = 0
8347     testl(result, 0x00000008);     // check if there's a block of 8 chars to compress
8348     jccb(Assembler::zero, copy_tail_sse);
8349 
8350     pxor(tmp3Reg, tmp3Reg);
8351 
8352     movdqu(tmp2Reg, Address(src, 0));
8353     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
8354     jccb(Assembler::notZero, reset_for_copy_tail);
8355     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
8356     movq(Address(dst, 0), tmp2Reg);
8357     addptr(src, 16);
8358     addptr(dst, 8);
8359     jmpb(copy_tail_sse);
8360 
8361     bind(reset_for_copy_tail);
8362     movl(tmp5, result);
8363     andl(tmp5, 0x0000000f);
8364     lea(src, Address(src, tmp5, Address::times_2));
8365     lea(dst, Address(dst, tmp5, Address::times_1));
8366     subptr(len, tmp5);
8367     jmpb(copy_chars_loop);
8368 
8369     bind(copy_tail_sse);
8370     movl(len, result);
8371     andl(len, 0x00000007);    // tail count (in chars)
8372   }
8373   // compress 1 char per iter
8374   bind(copy_tail);
8375   testl(len, len);
8376   jccb(Assembler::zero, done);
8377   lea(src, Address(src, len, Address::times_2));
8378   lea(dst, Address(dst, len, Address::times_1));
8379   negptr(len);
8380 
8381   bind(copy_chars_loop);
8382   load_unsigned_short(tmp5, Address(src, len, Address::times_2));
8383   testl(tmp5, 0xff00);      // check if Unicode char
8384   jccb(Assembler::notZero, reset_sp);
8385   movb(Address(dst, len, Address::times_1), tmp5);  // ASCII char; compress to 1 byte
8386   increment(len);
8387   jccb(Assembler::notZero, copy_chars_loop);
8388 
8389   // add len then return (len will be zero if compress succeeded, otherwise negative)
8390   bind(reset_sp);
8391   addl(result, len);
8392 
8393   bind(done);
8394 }
8395 
8396 // Inflate byte[] array to char[].
8397 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
8398 //   @IntrinsicCandidate
8399 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
8400 //     for (int i = 0; i < len; i++) {
8401 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
8402 //     }
8403 //   }
8404 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
8405   XMMRegister tmp1, Register tmp2, KRegister mask) {
8406   Label copy_chars_loop, done, below_threshold, avx3_threshold;
8407   // rsi: src
8408   // rdi: dst
8409   // rdx: len
8410   // rcx: tmp2
8411 
8412   // rsi holds start addr of source byte[] to be inflated
8413   // rdi holds start addr of destination char[]
8414   // rdx holds length
8415   assert_different_registers(src, dst, len, tmp2);
8416   movl(tmp2, len);
8417   if ((UseAVX > 2) && // AVX512
8418     VM_Version::supports_avx512vlbw() &&
8419     VM_Version::supports_bmi2()) {
8420 
8421     Label copy_32_loop, copy_tail;
8422     Register tmp3_aliased = len;
8423 
8424     // if length of the string is less than 16, handle it in an old fashioned way
8425     testl(len, -16);
8426     jcc(Assembler::zero, below_threshold);
8427 
8428     testl(len, -1 * AVX3Threshold);
8429     jcc(Assembler::zero, avx3_threshold);
8430 
8431     // In order to use only one arithmetic operation for the main loop we use
8432     // this pre-calculation
8433     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
8434     andl(len, -32);     // vector count
8435     jccb(Assembler::zero, copy_tail);
8436 
8437     lea(src, Address(src, len, Address::times_1));
8438     lea(dst, Address(dst, len, Address::times_2));
8439     negptr(len);
8440 
8441 
8442     // inflate 32 chars per iter
8443     bind(copy_32_loop);
8444     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
8445     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
8446     addptr(len, 32);
8447     jcc(Assembler::notZero, copy_32_loop);
8448 
8449     bind(copy_tail);
8450     // bail out when there is nothing to be done
8451     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
8452     jcc(Assembler::zero, done);
8453 
8454     // ~(~0 << length), where length is the # of remaining elements to process
8455     movl(tmp3_aliased, -1);
8456     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
8457     notl(tmp3_aliased);
8458     kmovdl(mask, tmp3_aliased);
8459     evpmovzxbw(tmp1, mask, Address(src, 0), Assembler::AVX_512bit);
8460     evmovdquw(Address(dst, 0), mask, tmp1, /*merge*/ true, Assembler::AVX_512bit);
8461 
8462     jmp(done);
8463     bind(avx3_threshold);
8464   }
8465   if (UseSSE42Intrinsics) {
8466     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
8467 
8468     if (UseAVX > 1) {
8469       andl(tmp2, (16 - 1));
8470       andl(len, -16);
8471       jccb(Assembler::zero, copy_new_tail);
8472     } else {
8473       andl(tmp2, 0x00000007);   // tail count (in chars)
8474       andl(len, 0xfffffff8);    // vector count (in chars)
8475       jccb(Assembler::zero, copy_tail);
8476     }
8477 
8478     // vectored inflation
8479     lea(src, Address(src, len, Address::times_1));
8480     lea(dst, Address(dst, len, Address::times_2));
8481     negptr(len);
8482 
8483     if (UseAVX > 1) {
8484       bind(copy_16_loop);
8485       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
8486       vmovdqu(Address(dst, len, Address::times_2), tmp1);
8487       addptr(len, 16);
8488       jcc(Assembler::notZero, copy_16_loop);
8489 
8490       bind(below_threshold);
8491       bind(copy_new_tail);
8492       movl(len, tmp2);
8493       andl(tmp2, 0x00000007);
8494       andl(len, 0xFFFFFFF8);
8495       jccb(Assembler::zero, copy_tail);
8496 
8497       pmovzxbw(tmp1, Address(src, 0));
8498       movdqu(Address(dst, 0), tmp1);
8499       addptr(src, 8);
8500       addptr(dst, 2 * 8);
8501 
8502       jmp(copy_tail, true);
8503     }
8504 
8505     // inflate 8 chars per iter
8506     bind(copy_8_loop);
8507     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
8508     movdqu(Address(dst, len, Address::times_2), tmp1);
8509     addptr(len, 8);
8510     jcc(Assembler::notZero, copy_8_loop);
8511 
8512     bind(copy_tail);
8513     movl(len, tmp2);
8514 
8515     cmpl(len, 4);
8516     jccb(Assembler::less, copy_bytes);
8517 
8518     movdl(tmp1, Address(src, 0));  // load 4 byte chars
8519     pmovzxbw(tmp1, tmp1);
8520     movq(Address(dst, 0), tmp1);
8521     subptr(len, 4);
8522     addptr(src, 4);
8523     addptr(dst, 8);
8524 
8525     bind(copy_bytes);
8526   } else {
8527     bind(below_threshold);
8528   }
8529 
8530   testl(len, len);
8531   jccb(Assembler::zero, done);
8532   lea(src, Address(src, len, Address::times_1));
8533   lea(dst, Address(dst, len, Address::times_2));
8534   negptr(len);
8535 
8536   // inflate 1 char per iter
8537   bind(copy_chars_loop);
8538   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
8539   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
8540   increment(len);
8541   jcc(Assembler::notZero, copy_chars_loop);
8542 
8543   bind(done);
8544 }
8545 
8546 void MacroAssembler::evmovdqu(BasicType type, KRegister kmask, XMMRegister dst, XMMRegister src, bool merge, int vector_len) {
8547   switch(type) {
8548     case T_BYTE:
8549     case T_BOOLEAN:
8550       evmovdqub(dst, kmask, src, merge, vector_len);
8551       break;
8552     case T_CHAR:
8553     case T_SHORT:
8554       evmovdquw(dst, kmask, src, merge, vector_len);
8555       break;
8556     case T_INT:
8557     case T_FLOAT:
8558       evmovdqul(dst, kmask, src, merge, vector_len);
8559       break;
8560     case T_LONG:
8561     case T_DOUBLE:
8562       evmovdquq(dst, kmask, src, merge, vector_len);
8563       break;
8564     default:
8565       fatal("Unexpected type argument %s", type2name(type));
8566       break;
8567   }
8568 }
8569 
8570 
8571 void MacroAssembler::evmovdqu(BasicType type, KRegister kmask, XMMRegister dst, Address src, bool merge, int vector_len) {
8572   switch(type) {
8573     case T_BYTE:
8574     case T_BOOLEAN:
8575       evmovdqub(dst, kmask, src, merge, vector_len);
8576       break;
8577     case T_CHAR:
8578     case T_SHORT:
8579       evmovdquw(dst, kmask, src, merge, vector_len);
8580       break;
8581     case T_INT:
8582     case T_FLOAT:
8583       evmovdqul(dst, kmask, src, merge, vector_len);
8584       break;
8585     case T_LONG:
8586     case T_DOUBLE:
8587       evmovdquq(dst, kmask, src, merge, vector_len);
8588       break;
8589     default:
8590       fatal("Unexpected type argument %s", type2name(type));
8591       break;
8592   }
8593 }
8594 
8595 void MacroAssembler::evmovdqu(BasicType type, KRegister kmask, Address dst, XMMRegister src, bool merge, int vector_len) {
8596   switch(type) {
8597     case T_BYTE:
8598     case T_BOOLEAN:
8599       evmovdqub(dst, kmask, src, merge, vector_len);
8600       break;
8601     case T_CHAR:
8602     case T_SHORT:
8603       evmovdquw(dst, kmask, src, merge, vector_len);
8604       break;
8605     case T_INT:
8606     case T_FLOAT:
8607       evmovdqul(dst, kmask, src, merge, vector_len);
8608       break;
8609     case T_LONG:
8610     case T_DOUBLE:
8611       evmovdquq(dst, kmask, src, merge, vector_len);
8612       break;
8613     default:
8614       fatal("Unexpected type argument %s", type2name(type));
8615       break;
8616   }
8617 }
8618 
8619 void MacroAssembler::knot(uint masklen, KRegister dst, KRegister src, KRegister ktmp, Register rtmp) {
8620   switch(masklen) {
8621     case 2:
8622        knotbl(dst, src);
8623        movl(rtmp, 3);
8624        kmovbl(ktmp, rtmp);
8625        kandbl(dst, ktmp, dst);
8626        break;
8627     case 4:
8628        knotbl(dst, src);
8629        movl(rtmp, 15);
8630        kmovbl(ktmp, rtmp);
8631        kandbl(dst, ktmp, dst);
8632        break;
8633     case 8:
8634        knotbl(dst, src);
8635        break;
8636     case 16:
8637        knotwl(dst, src);
8638        break;
8639     case 32:
8640        knotdl(dst, src);
8641        break;
8642     case 64:
8643        knotql(dst, src);
8644        break;
8645     default:
8646       fatal("Unexpected vector length %d", masklen);
8647       break;
8648   }
8649 }
8650 
8651 void MacroAssembler::kand(BasicType type, KRegister dst, KRegister src1, KRegister src2) {
8652   switch(type) {
8653     case T_BOOLEAN:
8654     case T_BYTE:
8655        kandbl(dst, src1, src2);
8656        break;
8657     case T_CHAR:
8658     case T_SHORT:
8659        kandwl(dst, src1, src2);
8660        break;
8661     case T_INT:
8662     case T_FLOAT:
8663        kanddl(dst, src1, src2);
8664        break;
8665     case T_LONG:
8666     case T_DOUBLE:
8667        kandql(dst, src1, src2);
8668        break;
8669     default:
8670       fatal("Unexpected type argument %s", type2name(type));
8671       break;
8672   }
8673 }
8674 
8675 void MacroAssembler::kor(BasicType type, KRegister dst, KRegister src1, KRegister src2) {
8676   switch(type) {
8677     case T_BOOLEAN:
8678     case T_BYTE:
8679        korbl(dst, src1, src2);
8680        break;
8681     case T_CHAR:
8682     case T_SHORT:
8683        korwl(dst, src1, src2);
8684        break;
8685     case T_INT:
8686     case T_FLOAT:
8687        kordl(dst, src1, src2);
8688        break;
8689     case T_LONG:
8690     case T_DOUBLE:
8691        korql(dst, src1, src2);
8692        break;
8693     default:
8694       fatal("Unexpected type argument %s", type2name(type));
8695       break;
8696   }
8697 }
8698 
8699 void MacroAssembler::kxor(BasicType type, KRegister dst, KRegister src1, KRegister src2) {
8700   switch(type) {
8701     case T_BOOLEAN:
8702     case T_BYTE:
8703        kxorbl(dst, src1, src2);
8704        break;
8705     case T_CHAR:
8706     case T_SHORT:
8707        kxorwl(dst, src1, src2);
8708        break;
8709     case T_INT:
8710     case T_FLOAT:
8711        kxordl(dst, src1, src2);
8712        break;
8713     case T_LONG:
8714     case T_DOUBLE:
8715        kxorql(dst, src1, src2);
8716        break;
8717     default:
8718       fatal("Unexpected type argument %s", type2name(type));
8719       break;
8720   }
8721 }
8722 
8723 void MacroAssembler::evperm(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, XMMRegister src, bool merge, int vector_len) {
8724   switch(type) {
8725     case T_BOOLEAN:
8726     case T_BYTE:
8727       evpermb(dst, mask, nds, src, merge, vector_len); break;
8728     case T_CHAR:
8729     case T_SHORT:
8730       evpermw(dst, mask, nds, src, merge, vector_len); break;
8731     case T_INT:
8732     case T_FLOAT:
8733       evpermd(dst, mask, nds, src, merge, vector_len); break;
8734     case T_LONG:
8735     case T_DOUBLE:
8736       evpermq(dst, mask, nds, src, merge, vector_len); break;
8737     default:
8738       fatal("Unexpected type argument %s", type2name(type)); break;
8739   }
8740 }
8741 
8742 void MacroAssembler::evperm(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, Address src, bool merge, int vector_len) {
8743   switch(type) {
8744     case T_BOOLEAN:
8745     case T_BYTE:
8746       evpermb(dst, mask, nds, src, merge, vector_len); break;
8747     case T_CHAR:
8748     case T_SHORT:
8749       evpermw(dst, mask, nds, src, merge, vector_len); break;
8750     case T_INT:
8751     case T_FLOAT:
8752       evpermd(dst, mask, nds, src, merge, vector_len); break;
8753     case T_LONG:
8754     case T_DOUBLE:
8755       evpermq(dst, mask, nds, src, merge, vector_len); break;
8756     default:
8757       fatal("Unexpected type argument %s", type2name(type)); break;
8758   }
8759 }
8760 
8761 void MacroAssembler::evpminu(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, Address src, bool merge, int vector_len) {
8762   switch(type) {
8763     case T_BYTE:
8764       evpminub(dst, mask, nds, src, merge, vector_len); break;
8765     case T_SHORT:
8766       evpminuw(dst, mask, nds, src, merge, vector_len); break;
8767     case T_INT:
8768       evpminud(dst, mask, nds, src, merge, vector_len); break;
8769     case T_LONG:
8770       evpminuq(dst, mask, nds, src, merge, vector_len); break;
8771     default:
8772       fatal("Unexpected type argument %s", type2name(type)); break;
8773   }
8774 }
8775 
8776 void MacroAssembler::evpmaxu(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, Address src, bool merge, int vector_len) {
8777   switch(type) {
8778     case T_BYTE:
8779       evpmaxub(dst, mask, nds, src, merge, vector_len); break;
8780     case T_SHORT:
8781       evpmaxuw(dst, mask, nds, src, merge, vector_len); break;
8782     case T_INT:
8783       evpmaxud(dst, mask, nds, src, merge, vector_len); break;
8784     case T_LONG:
8785       evpmaxuq(dst, mask, nds, src, merge, vector_len); break;
8786     default:
8787       fatal("Unexpected type argument %s", type2name(type)); break;
8788   }
8789 }
8790 
8791 void MacroAssembler::evpminu(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, XMMRegister src, bool merge, int vector_len) {
8792   switch(type) {
8793     case T_BYTE:
8794       evpminub(dst, mask, nds, src, merge, vector_len); break;
8795     case T_SHORT:
8796       evpminuw(dst, mask, nds, src, merge, vector_len); break;
8797     case T_INT:
8798       evpminud(dst, mask, nds, src, merge, vector_len); break;
8799     case T_LONG:
8800       evpminuq(dst, mask, nds, src, merge, vector_len); break;
8801     default:
8802       fatal("Unexpected type argument %s", type2name(type)); break;
8803   }
8804 }
8805 
8806 void MacroAssembler::evpmaxu(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, XMMRegister src, bool merge, int vector_len) {
8807   switch(type) {
8808     case T_BYTE:
8809       evpmaxub(dst, mask, nds, src, merge, vector_len); break;
8810     case T_SHORT:
8811       evpmaxuw(dst, mask, nds, src, merge, vector_len); break;
8812     case T_INT:
8813       evpmaxud(dst, mask, nds, src, merge, vector_len); break;
8814     case T_LONG:
8815       evpmaxuq(dst, mask, nds, src, merge, vector_len); break;
8816     default:
8817       fatal("Unexpected type argument %s", type2name(type)); break;
8818   }
8819 }
8820 
8821 void MacroAssembler::evpmins(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, Address src, bool merge, int vector_len) {
8822   switch(type) {
8823     case T_BYTE:
8824       evpminsb(dst, mask, nds, src, merge, vector_len); break;
8825     case T_SHORT:
8826       evpminsw(dst, mask, nds, src, merge, vector_len); break;
8827     case T_INT:
8828       evpminsd(dst, mask, nds, src, merge, vector_len); break;
8829     case T_LONG:
8830       evpminsq(dst, mask, nds, src, merge, vector_len); break;
8831     default:
8832       fatal("Unexpected type argument %s", type2name(type)); break;
8833   }
8834 }
8835 
8836 void MacroAssembler::evpmaxs(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, Address src, bool merge, int vector_len) {
8837   switch(type) {
8838     case T_BYTE:
8839       evpmaxsb(dst, mask, nds, src, merge, vector_len); break;
8840     case T_SHORT:
8841       evpmaxsw(dst, mask, nds, src, merge, vector_len); break;
8842     case T_INT:
8843       evpmaxsd(dst, mask, nds, src, merge, vector_len); break;
8844     case T_LONG:
8845       evpmaxsq(dst, mask, nds, src, merge, vector_len); break;
8846     default:
8847       fatal("Unexpected type argument %s", type2name(type)); break;
8848   }
8849 }
8850 
8851 void MacroAssembler::evpmins(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, XMMRegister src, bool merge, int vector_len) {
8852   switch(type) {
8853     case T_BYTE:
8854       evpminsb(dst, mask, nds, src, merge, vector_len); break;
8855     case T_SHORT:
8856       evpminsw(dst, mask, nds, src, merge, vector_len); break;
8857     case T_INT:
8858       evpminsd(dst, mask, nds, src, merge, vector_len); break;
8859     case T_LONG:
8860       evpminsq(dst, mask, nds, src, merge, vector_len); break;
8861     default:
8862       fatal("Unexpected type argument %s", type2name(type)); break;
8863   }
8864 }
8865 
8866 void MacroAssembler::evpmaxs(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, XMMRegister src, bool merge, int vector_len) {
8867   switch(type) {
8868     case T_BYTE:
8869       evpmaxsb(dst, mask, nds, src, merge, vector_len); break;
8870     case T_SHORT:
8871       evpmaxsw(dst, mask, nds, src, merge, vector_len); break;
8872     case T_INT:
8873       evpmaxsd(dst, mask, nds, src, merge, vector_len); break;
8874     case T_LONG:
8875       evpmaxsq(dst, mask, nds, src, merge, vector_len); break;
8876     default:
8877       fatal("Unexpected type argument %s", type2name(type)); break;
8878   }
8879 }
8880 
8881 void MacroAssembler::evxor(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, XMMRegister src, bool merge, int vector_len) {
8882   switch(type) {
8883     case T_INT:
8884       evpxord(dst, mask, nds, src, merge, vector_len); break;
8885     case T_LONG:
8886       evpxorq(dst, mask, nds, src, merge, vector_len); break;
8887     default:
8888       fatal("Unexpected type argument %s", type2name(type)); break;
8889   }
8890 }
8891 
8892 void MacroAssembler::evxor(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, Address src, bool merge, int vector_len) {
8893   switch(type) {
8894     case T_INT:
8895       evpxord(dst, mask, nds, src, merge, vector_len); break;
8896     case T_LONG:
8897       evpxorq(dst, mask, nds, src, merge, vector_len); break;
8898     default:
8899       fatal("Unexpected type argument %s", type2name(type)); break;
8900   }
8901 }
8902 
8903 void MacroAssembler::evor(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, XMMRegister src, bool merge, int vector_len) {
8904   switch(type) {
8905     case T_INT:
8906       Assembler::evpord(dst, mask, nds, src, merge, vector_len); break;
8907     case T_LONG:
8908       evporq(dst, mask, nds, src, merge, vector_len); break;
8909     default:
8910       fatal("Unexpected type argument %s", type2name(type)); break;
8911   }
8912 }
8913 
8914 void MacroAssembler::evor(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, Address src, bool merge, int vector_len) {
8915   switch(type) {
8916     case T_INT:
8917       Assembler::evpord(dst, mask, nds, src, merge, vector_len); break;
8918     case T_LONG:
8919       evporq(dst, mask, nds, src, merge, vector_len); break;
8920     default:
8921       fatal("Unexpected type argument %s", type2name(type)); break;
8922   }
8923 }
8924 
8925 void MacroAssembler::evand(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, XMMRegister src, bool merge, int vector_len) {
8926   switch(type) {
8927     case T_INT:
8928       evpandd(dst, mask, nds, src, merge, vector_len); break;
8929     case T_LONG:
8930       evpandq(dst, mask, nds, src, merge, vector_len); break;
8931     default:
8932       fatal("Unexpected type argument %s", type2name(type)); break;
8933   }
8934 }
8935 
8936 void MacroAssembler::evand(BasicType type, XMMRegister dst, KRegister mask, XMMRegister nds, Address src, bool merge, int vector_len) {
8937   switch(type) {
8938     case T_INT:
8939       evpandd(dst, mask, nds, src, merge, vector_len); break;
8940     case T_LONG:
8941       evpandq(dst, mask, nds, src, merge, vector_len); break;
8942     default:
8943       fatal("Unexpected type argument %s", type2name(type)); break;
8944   }
8945 }
8946 
8947 void MacroAssembler::kortest(uint masklen, KRegister src1, KRegister src2) {
8948   switch(masklen) {
8949     case 8:
8950        kortestbl(src1, src2);
8951        break;
8952     case 16:
8953        kortestwl(src1, src2);
8954        break;
8955     case 32:
8956        kortestdl(src1, src2);
8957        break;
8958     case 64:
8959        kortestql(src1, src2);
8960        break;
8961     default:
8962       fatal("Unexpected mask length %d", masklen);
8963       break;
8964   }
8965 }
8966 
8967 
8968 void MacroAssembler::ktest(uint masklen, KRegister src1, KRegister src2) {
8969   switch(masklen)  {
8970     case 8:
8971        ktestbl(src1, src2);
8972        break;
8973     case 16:
8974        ktestwl(src1, src2);
8975        break;
8976     case 32:
8977        ktestdl(src1, src2);
8978        break;
8979     case 64:
8980        ktestql(src1, src2);
8981        break;
8982     default:
8983       fatal("Unexpected mask length %d", masklen);
8984       break;
8985   }
8986 }
8987 
8988 void MacroAssembler::evrold(BasicType type, XMMRegister dst, KRegister mask, XMMRegister src, int shift, bool merge, int vlen_enc) {
8989   switch(type) {
8990     case T_INT:
8991       evprold(dst, mask, src, shift, merge, vlen_enc); break;
8992     case T_LONG:
8993       evprolq(dst, mask, src, shift, merge, vlen_enc); break;
8994     default:
8995       fatal("Unexpected type argument %s", type2name(type)); break;
8996       break;
8997   }
8998 }
8999 
9000 void MacroAssembler::evrord(BasicType type, XMMRegister dst, KRegister mask, XMMRegister src, int shift, bool merge, int vlen_enc) {
9001   switch(type) {
9002     case T_INT:
9003       evprord(dst, mask, src, shift, merge, vlen_enc); break;
9004     case T_LONG:
9005       evprorq(dst, mask, src, shift, merge, vlen_enc); break;
9006     default:
9007       fatal("Unexpected type argument %s", type2name(type)); break;
9008   }
9009 }
9010 
9011 void MacroAssembler::evrold(BasicType type, XMMRegister dst, KRegister mask, XMMRegister src1, XMMRegister src2, bool merge, int vlen_enc) {
9012   switch(type) {
9013     case T_INT:
9014       evprolvd(dst, mask, src1, src2, merge, vlen_enc); break;
9015     case T_LONG:
9016       evprolvq(dst, mask, src1, src2, merge, vlen_enc); break;
9017     default:
9018       fatal("Unexpected type argument %s", type2name(type)); break;
9019   }
9020 }
9021 
9022 void MacroAssembler::evrord(BasicType type, XMMRegister dst, KRegister mask, XMMRegister src1, XMMRegister src2, bool merge, int vlen_enc) {
9023   switch(type) {
9024     case T_INT:
9025       evprorvd(dst, mask, src1, src2, merge, vlen_enc); break;
9026     case T_LONG:
9027       evprorvq(dst, mask, src1, src2, merge, vlen_enc); break;
9028     default:
9029       fatal("Unexpected type argument %s", type2name(type)); break;
9030   }
9031 }
9032 
9033 void MacroAssembler::evpandq(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
9034   assert(rscratch != noreg || always_reachable(src), "missing");
9035 
9036   if (reachable(src)) {
9037     evpandq(dst, nds, as_Address(src), vector_len);
9038   } else {
9039     lea(rscratch, src);
9040     evpandq(dst, nds, Address(rscratch, 0), vector_len);
9041   }
9042 }
9043 
9044 void MacroAssembler::evpaddq(XMMRegister dst, KRegister mask, XMMRegister nds, AddressLiteral src, bool merge, int vector_len, Register rscratch) {
9045   assert(rscratch != noreg || always_reachable(src), "missing");
9046 
9047   if (reachable(src)) {
9048     Assembler::evpaddq(dst, mask, nds, as_Address(src), merge, vector_len);
9049   } else {
9050     lea(rscratch, src);
9051     Assembler::evpaddq(dst, mask, nds, Address(rscratch, 0), merge, vector_len);
9052   }
9053 }
9054 
9055 void MacroAssembler::evporq(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
9056   assert(rscratch != noreg || always_reachable(src), "missing");
9057 
9058   if (reachable(src)) {
9059     evporq(dst, nds, as_Address(src), vector_len);
9060   } else {
9061     lea(rscratch, src);
9062     evporq(dst, nds, Address(rscratch, 0), vector_len);
9063   }
9064 }
9065 
9066 void MacroAssembler::vpshufb(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
9067   assert(rscratch != noreg || always_reachable(src), "missing");
9068 
9069   if (reachable(src)) {
9070     vpshufb(dst, nds, as_Address(src), vector_len);
9071   } else {
9072     lea(rscratch, src);
9073     vpshufb(dst, nds, Address(rscratch, 0), vector_len);
9074   }
9075 }
9076 
9077 void MacroAssembler::vpor(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len, Register rscratch) {
9078   assert(rscratch != noreg || always_reachable(src), "missing");
9079 
9080   if (reachable(src)) {
9081     Assembler::vpor(dst, nds, as_Address(src), vector_len);
9082   } else {
9083     lea(rscratch, src);
9084     Assembler::vpor(dst, nds, Address(rscratch, 0), vector_len);
9085   }
9086 }
9087 
9088 void MacroAssembler::vpternlogq(XMMRegister dst, int imm8, XMMRegister src2, AddressLiteral src3, int vector_len, Register rscratch) {
9089   assert(rscratch != noreg || always_reachable(src3), "missing");
9090 
9091   if (reachable(src3)) {
9092     vpternlogq(dst, imm8, src2, as_Address(src3), vector_len);
9093   } else {
9094     lea(rscratch, src3);
9095     vpternlogq(dst, imm8, src2, Address(rscratch, 0), vector_len);
9096   }
9097 }
9098 
9099 #if COMPILER2_OR_JVMCI
9100 
9101 void MacroAssembler::fill_masked(BasicType bt, Address dst, XMMRegister xmm, KRegister mask,
9102                                  Register length, Register temp, int vec_enc) {
9103   // Computing mask for predicated vector store.
9104   movptr(temp, -1);
9105   bzhiq(temp, temp, length);
9106   kmov(mask, temp);
9107   evmovdqu(bt, mask, dst, xmm, true, vec_enc);
9108 }
9109 
9110 // Set memory operation for length "less than" 64 bytes.
9111 void MacroAssembler::fill64_masked(uint shift, Register dst, int disp,
9112                                        XMMRegister xmm, KRegister mask, Register length,
9113                                        Register temp, bool use64byteVector) {
9114   assert(MaxVectorSize >= 32, "vector length should be >= 32");
9115   const BasicType type[] = { T_BYTE, T_SHORT, T_INT, T_LONG};
9116   if (!use64byteVector) {
9117     fill32(dst, disp, xmm);
9118     subptr(length, 32 >> shift);
9119     fill32_masked(shift, dst, disp + 32, xmm, mask, length, temp);
9120   } else {
9121     assert(MaxVectorSize == 64, "vector length != 64");
9122     fill_masked(type[shift], Address(dst, disp), xmm, mask, length, temp, Assembler::AVX_512bit);
9123   }
9124 }
9125 
9126 
9127 void MacroAssembler::fill32_masked(uint shift, Register dst, int disp,
9128                                        XMMRegister xmm, KRegister mask, Register length,
9129                                        Register temp) {
9130   assert(MaxVectorSize >= 32, "vector length should be >= 32");
9131   const BasicType type[] = { T_BYTE, T_SHORT, T_INT, T_LONG};
9132   fill_masked(type[shift], Address(dst, disp), xmm, mask, length, temp, Assembler::AVX_256bit);
9133 }
9134 
9135 
9136 void MacroAssembler::fill32(Address dst, XMMRegister xmm) {
9137   assert(MaxVectorSize >= 32, "vector length should be >= 32");
9138   vmovdqu(dst, xmm);
9139 }
9140 
9141 void MacroAssembler::fill32(Register dst, int disp, XMMRegister xmm) {
9142   fill32(Address(dst, disp), xmm);
9143 }
9144 
9145 void MacroAssembler::fill64(Address dst, XMMRegister xmm, bool use64byteVector) {
9146   assert(MaxVectorSize >= 32, "vector length should be >= 32");
9147   if (!use64byteVector) {
9148     fill32(dst, xmm);
9149     fill32(dst.plus_disp(32), xmm);
9150   } else {
9151     evmovdquq(dst, xmm, Assembler::AVX_512bit);
9152   }
9153 }
9154 
9155 void MacroAssembler::fill64(Register dst, int disp, XMMRegister xmm, bool use64byteVector) {
9156   fill64(Address(dst, disp), xmm, use64byteVector);
9157 }
9158 
9159 void MacroAssembler::generate_fill_avx3(BasicType type, Register to, Register value,
9160                                         Register count, Register rtmp, XMMRegister xtmp) {
9161   Label L_exit;
9162   Label L_fill_start;
9163   Label L_fill_64_bytes;
9164   Label L_fill_96_bytes;
9165   Label L_fill_128_bytes;
9166   Label L_fill_128_bytes_loop;
9167   Label L_fill_128_loop_header;
9168   Label L_fill_128_bytes_loop_header;
9169   Label L_fill_128_bytes_loop_pre_header;
9170   Label L_fill_zmm_sequence;
9171 
9172   int shift = -1;
9173   int avx3threshold = VM_Version::avx3_threshold();
9174   switch(type) {
9175     case T_BYTE:  shift = 0;
9176       break;
9177     case T_SHORT: shift = 1;
9178       break;
9179     case T_INT:   shift = 2;
9180       break;
9181     /* Uncomment when LONG fill stubs are supported.
9182     case T_LONG:  shift = 3;
9183       break;
9184     */
9185     default:
9186       fatal("Unhandled type: %s\n", type2name(type));
9187   }
9188 
9189   if ((avx3threshold != 0)  || (MaxVectorSize == 32)) {
9190 
9191     if (MaxVectorSize == 64) {
9192       cmpq(count, avx3threshold >> shift);
9193       jcc(Assembler::greater, L_fill_zmm_sequence);
9194     }
9195 
9196     evpbroadcast(type, xtmp, value, Assembler::AVX_256bit);
9197 
9198     bind(L_fill_start);
9199 
9200     cmpq(count, 32 >> shift);
9201     jccb(Assembler::greater, L_fill_64_bytes);
9202     fill32_masked(shift, to, 0, xtmp, k2, count, rtmp);
9203     jmp(L_exit);
9204 
9205     bind(L_fill_64_bytes);
9206     cmpq(count, 64 >> shift);
9207     jccb(Assembler::greater, L_fill_96_bytes);
9208     fill64_masked(shift, to, 0, xtmp, k2, count, rtmp);
9209     jmp(L_exit);
9210 
9211     bind(L_fill_96_bytes);
9212     cmpq(count, 96 >> shift);
9213     jccb(Assembler::greater, L_fill_128_bytes);
9214     fill64(to, 0, xtmp);
9215     subq(count, 64 >> shift);
9216     fill32_masked(shift, to, 64, xtmp, k2, count, rtmp);
9217     jmp(L_exit);
9218 
9219     bind(L_fill_128_bytes);
9220     cmpq(count, 128 >> shift);
9221     jccb(Assembler::greater, L_fill_128_bytes_loop_pre_header);
9222     fill64(to, 0, xtmp);
9223     fill32(to, 64, xtmp);
9224     subq(count, 96 >> shift);
9225     fill32_masked(shift, to, 96, xtmp, k2, count, rtmp);
9226     jmp(L_exit);
9227 
9228     bind(L_fill_128_bytes_loop_pre_header);
9229     {
9230       mov(rtmp, to);
9231       andq(rtmp, 31);
9232       jccb(Assembler::zero, L_fill_128_bytes_loop_header);
9233       negq(rtmp);
9234       addq(rtmp, 32);
9235       mov64(r8, -1L);
9236       bzhiq(r8, r8, rtmp);
9237       kmovql(k2, r8);
9238       evmovdqu(T_BYTE, k2, Address(to, 0), xtmp, true, Assembler::AVX_256bit);
9239       addq(to, rtmp);
9240       shrq(rtmp, shift);
9241       subq(count, rtmp);
9242     }
9243 
9244     cmpq(count, 128 >> shift);
9245     jcc(Assembler::less, L_fill_start);
9246 
9247     bind(L_fill_128_bytes_loop_header);
9248     subq(count, 128 >> shift);
9249 
9250     align32();
9251     bind(L_fill_128_bytes_loop);
9252       fill64(to, 0, xtmp);
9253       fill64(to, 64, xtmp);
9254       addq(to, 128);
9255       subq(count, 128 >> shift);
9256       jccb(Assembler::greaterEqual, L_fill_128_bytes_loop);
9257 
9258     addq(count, 128 >> shift);
9259     jcc(Assembler::zero, L_exit);
9260     jmp(L_fill_start);
9261   }
9262 
9263   if (MaxVectorSize == 64) {
9264     // Sequence using 64 byte ZMM register.
9265     Label L_fill_128_bytes_zmm;
9266     Label L_fill_192_bytes_zmm;
9267     Label L_fill_192_bytes_loop_zmm;
9268     Label L_fill_192_bytes_loop_header_zmm;
9269     Label L_fill_192_bytes_loop_pre_header_zmm;
9270     Label L_fill_start_zmm_sequence;
9271 
9272     bind(L_fill_zmm_sequence);
9273     evpbroadcast(type, xtmp, value, Assembler::AVX_512bit);
9274 
9275     bind(L_fill_start_zmm_sequence);
9276     cmpq(count, 64 >> shift);
9277     jccb(Assembler::greater, L_fill_128_bytes_zmm);
9278     fill64_masked(shift, to, 0, xtmp, k2, count, rtmp, true);
9279     jmp(L_exit);
9280 
9281     bind(L_fill_128_bytes_zmm);
9282     cmpq(count, 128 >> shift);
9283     jccb(Assembler::greater, L_fill_192_bytes_zmm);
9284     fill64(to, 0, xtmp, true);
9285     subq(count, 64 >> shift);
9286     fill64_masked(shift, to, 64, xtmp, k2, count, rtmp, true);
9287     jmp(L_exit);
9288 
9289     bind(L_fill_192_bytes_zmm);
9290     cmpq(count, 192 >> shift);
9291     jccb(Assembler::greater, L_fill_192_bytes_loop_pre_header_zmm);
9292     fill64(to, 0, xtmp, true);
9293     fill64(to, 64, xtmp, true);
9294     subq(count, 128 >> shift);
9295     fill64_masked(shift, to, 128, xtmp, k2, count, rtmp, true);
9296     jmp(L_exit);
9297 
9298     bind(L_fill_192_bytes_loop_pre_header_zmm);
9299     {
9300       movq(rtmp, to);
9301       andq(rtmp, 63);
9302       jccb(Assembler::zero, L_fill_192_bytes_loop_header_zmm);
9303       negq(rtmp);
9304       addq(rtmp, 64);
9305       mov64(r8, -1L);
9306       bzhiq(r8, r8, rtmp);
9307       kmovql(k2, r8);
9308       evmovdqu(T_BYTE, k2, Address(to, 0), xtmp, true, Assembler::AVX_512bit);
9309       addq(to, rtmp);
9310       shrq(rtmp, shift);
9311       subq(count, rtmp);
9312     }
9313 
9314     cmpq(count, 192 >> shift);
9315     jcc(Assembler::less, L_fill_start_zmm_sequence);
9316 
9317     bind(L_fill_192_bytes_loop_header_zmm);
9318     subq(count, 192 >> shift);
9319 
9320     align32();
9321     bind(L_fill_192_bytes_loop_zmm);
9322       fill64(to, 0, xtmp, true);
9323       fill64(to, 64, xtmp, true);
9324       fill64(to, 128, xtmp, true);
9325       addq(to, 192);
9326       subq(count, 192 >> shift);
9327       jccb(Assembler::greaterEqual, L_fill_192_bytes_loop_zmm);
9328 
9329     addq(count, 192 >> shift);
9330     jcc(Assembler::zero, L_exit);
9331     jmp(L_fill_start_zmm_sequence);
9332   }
9333   bind(L_exit);
9334 }
9335 #endif //COMPILER2_OR_JVMCI
9336 
9337 
9338 void MacroAssembler::convert_f2i(Register dst, XMMRegister src) {
9339   Label done;
9340   cvttss2sil(dst, src);
9341   // Conversion instructions do not match JLS for overflow, underflow and NaN -> fixup in stub
9342   cmpl(dst, 0x80000000); // float_sign_flip
9343   jccb(Assembler::notEqual, done);
9344   subptr(rsp, 8);
9345   movflt(Address(rsp, 0), src);
9346   call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::f2i_fixup())));
9347   pop(dst);
9348   bind(done);
9349 }
9350 
9351 void MacroAssembler::convert_d2i(Register dst, XMMRegister src) {
9352   Label done;
9353   cvttsd2sil(dst, src);
9354   // Conversion instructions do not match JLS for overflow, underflow and NaN -> fixup in stub
9355   cmpl(dst, 0x80000000); // float_sign_flip
9356   jccb(Assembler::notEqual, done);
9357   subptr(rsp, 8);
9358   movdbl(Address(rsp, 0), src);
9359   call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::d2i_fixup())));
9360   pop(dst);
9361   bind(done);
9362 }
9363 
9364 void MacroAssembler::convert_f2l(Register dst, XMMRegister src) {
9365   Label done;
9366   cvttss2siq(dst, src);
9367   cmp64(dst, ExternalAddress((address) StubRoutines::x86::double_sign_flip()));
9368   jccb(Assembler::notEqual, done);
9369   subptr(rsp, 8);
9370   movflt(Address(rsp, 0), src);
9371   call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::f2l_fixup())));
9372   pop(dst);
9373   bind(done);
9374 }
9375 
9376 void MacroAssembler::round_float(Register dst, XMMRegister src, Register rtmp, Register rcx) {
9377   // Following code is line by line assembly translation rounding algorithm.
9378   // Please refer to java.lang.Math.round(float) algorithm for details.
9379   const int32_t FloatConsts_EXP_BIT_MASK = 0x7F800000;
9380   const int32_t FloatConsts_SIGNIFICAND_WIDTH = 24;
9381   const int32_t FloatConsts_EXP_BIAS = 127;
9382   const int32_t FloatConsts_SIGNIF_BIT_MASK = 0x007FFFFF;
9383   const int32_t MINUS_32 = 0xFFFFFFE0;
9384   Label L_special_case, L_block1, L_exit;
9385   movl(rtmp, FloatConsts_EXP_BIT_MASK);
9386   movdl(dst, src);
9387   andl(dst, rtmp);
9388   sarl(dst, FloatConsts_SIGNIFICAND_WIDTH - 1);
9389   movl(rtmp, FloatConsts_SIGNIFICAND_WIDTH - 2 + FloatConsts_EXP_BIAS);
9390   subl(rtmp, dst);
9391   movl(rcx, rtmp);
9392   movl(dst, MINUS_32);
9393   testl(rtmp, dst);
9394   jccb(Assembler::notEqual, L_special_case);
9395   movdl(dst, src);
9396   andl(dst, FloatConsts_SIGNIF_BIT_MASK);
9397   orl(dst, FloatConsts_SIGNIF_BIT_MASK + 1);
9398   movdl(rtmp, src);
9399   testl(rtmp, rtmp);
9400   jccb(Assembler::greaterEqual, L_block1);
9401   negl(dst);
9402   bind(L_block1);
9403   sarl(dst);
9404   addl(dst, 0x1);
9405   sarl(dst, 0x1);
9406   jmp(L_exit);
9407   bind(L_special_case);
9408   convert_f2i(dst, src);
9409   bind(L_exit);
9410 }
9411 
9412 void MacroAssembler::round_double(Register dst, XMMRegister src, Register rtmp, Register rcx) {
9413   // Following code is line by line assembly translation rounding algorithm.
9414   // Please refer to java.lang.Math.round(double) algorithm for details.
9415   const int64_t DoubleConsts_EXP_BIT_MASK = 0x7FF0000000000000L;
9416   const int64_t DoubleConsts_SIGNIFICAND_WIDTH = 53;
9417   const int64_t DoubleConsts_EXP_BIAS = 1023;
9418   const int64_t DoubleConsts_SIGNIF_BIT_MASK = 0x000FFFFFFFFFFFFFL;
9419   const int64_t MINUS_64 = 0xFFFFFFFFFFFFFFC0L;
9420   Label L_special_case, L_block1, L_exit;
9421   mov64(rtmp, DoubleConsts_EXP_BIT_MASK);
9422   movq(dst, src);
9423   andq(dst, rtmp);
9424   sarq(dst, DoubleConsts_SIGNIFICAND_WIDTH - 1);
9425   mov64(rtmp, DoubleConsts_SIGNIFICAND_WIDTH - 2 + DoubleConsts_EXP_BIAS);
9426   subq(rtmp, dst);
9427   movq(rcx, rtmp);
9428   mov64(dst, MINUS_64);
9429   testq(rtmp, dst);
9430   jccb(Assembler::notEqual, L_special_case);
9431   movq(dst, src);
9432   mov64(rtmp, DoubleConsts_SIGNIF_BIT_MASK);
9433   andq(dst, rtmp);
9434   mov64(rtmp, DoubleConsts_SIGNIF_BIT_MASK + 1);
9435   orq(dst, rtmp);
9436   movq(rtmp, src);
9437   testq(rtmp, rtmp);
9438   jccb(Assembler::greaterEqual, L_block1);
9439   negq(dst);
9440   bind(L_block1);
9441   sarq(dst);
9442   addq(dst, 0x1);
9443   sarq(dst, 0x1);
9444   jmp(L_exit);
9445   bind(L_special_case);
9446   convert_d2l(dst, src);
9447   bind(L_exit);
9448 }
9449 
9450 void MacroAssembler::convert_d2l(Register dst, XMMRegister src) {
9451   Label done;
9452   cvttsd2siq(dst, src);
9453   cmp64(dst, ExternalAddress((address) StubRoutines::x86::double_sign_flip()));
9454   jccb(Assembler::notEqual, done);
9455   subptr(rsp, 8);
9456   movdbl(Address(rsp, 0), src);
9457   call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::d2l_fixup())));
9458   pop(dst);
9459   bind(done);
9460 }
9461 
9462 void MacroAssembler::cache_wb(Address line)
9463 {
9464   // 64 bit cpus always support clflush
9465   assert(VM_Version::supports_clflush(), "clflush should be available");
9466   bool optimized = VM_Version::supports_clflushopt();
9467   bool no_evict = VM_Version::supports_clwb();
9468 
9469   // prefer clwb (writeback without evict) otherwise
9470   // prefer clflushopt (potentially parallel writeback with evict)
9471   // otherwise fallback on clflush (serial writeback with evict)
9472 
9473   if (optimized) {
9474     if (no_evict) {
9475       clwb(line);
9476     } else {
9477       clflushopt(line);
9478     }
9479   } else {
9480     // no need for fence when using CLFLUSH
9481     clflush(line);
9482   }
9483 }
9484 
9485 void MacroAssembler::cache_wbsync(bool is_pre)
9486 {
9487   assert(VM_Version::supports_clflush(), "clflush should be available");
9488   bool optimized = VM_Version::supports_clflushopt();
9489   bool no_evict = VM_Version::supports_clwb();
9490 
9491   // pick the correct implementation
9492 
9493   if (!is_pre && (optimized || no_evict)) {
9494     // need an sfence for post flush when using clflushopt or clwb
9495     // otherwise no no need for any synchroniaztion
9496 
9497     sfence();
9498   }
9499 }
9500 
9501 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
9502   switch (cond) {
9503     // Note some conditions are synonyms for others
9504     case Assembler::zero:         return Assembler::notZero;
9505     case Assembler::notZero:      return Assembler::zero;
9506     case Assembler::less:         return Assembler::greaterEqual;
9507     case Assembler::lessEqual:    return Assembler::greater;
9508     case Assembler::greater:      return Assembler::lessEqual;
9509     case Assembler::greaterEqual: return Assembler::less;
9510     case Assembler::below:        return Assembler::aboveEqual;
9511     case Assembler::belowEqual:   return Assembler::above;
9512     case Assembler::above:        return Assembler::belowEqual;
9513     case Assembler::aboveEqual:   return Assembler::below;
9514     case Assembler::overflow:     return Assembler::noOverflow;
9515     case Assembler::noOverflow:   return Assembler::overflow;
9516     case Assembler::negative:     return Assembler::positive;
9517     case Assembler::positive:     return Assembler::negative;
9518     case Assembler::parity:       return Assembler::noParity;
9519     case Assembler::noParity:     return Assembler::parity;
9520   }
9521   ShouldNotReachHere(); return Assembler::overflow;
9522 }
9523 
9524 // This is simply a call to Thread::current()
9525 void MacroAssembler::get_thread_slow(Register thread) {
9526   if (thread != rax) {
9527     push(rax);
9528   }
9529   push(rdi);
9530   push(rsi);
9531   push(rdx);
9532   push(rcx);
9533   push(r8);
9534   push(r9);
9535   push(r10);
9536   push(r11);
9537 
9538   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
9539 
9540   pop(r11);
9541   pop(r10);
9542   pop(r9);
9543   pop(r8);
9544   pop(rcx);
9545   pop(rdx);
9546   pop(rsi);
9547   pop(rdi);
9548   if (thread != rax) {
9549     mov(thread, rax);
9550     pop(rax);
9551   }
9552 }
9553 
9554 void MacroAssembler::check_stack_alignment(Register sp, const char* msg, unsigned bias, Register tmp) {
9555   Label L_stack_ok;
9556   if (bias == 0) {
9557     testptr(sp, 2 * wordSize - 1);
9558   } else {
9559     // lea(tmp, Address(rsp, bias);
9560     mov(tmp, sp);
9561     addptr(tmp, bias);
9562     testptr(tmp, 2 * wordSize - 1);
9563   }
9564   jcc(Assembler::equal, L_stack_ok);
9565   block_comment(msg);
9566   stop(msg);
9567   bind(L_stack_ok);
9568 }
9569 
9570 // Implements lightweight-locking.
9571 //
9572 // obj: the object to be locked
9573 // reg_rax: rax
9574 // thread: the thread which attempts to lock obj
9575 // tmp: a temporary register
9576 void MacroAssembler::lightweight_lock(Register basic_lock, Register obj, Register reg_rax, Register tmp, Label& slow) {
9577   Register thread = r15_thread;
9578 
9579   assert(reg_rax == rax, "");
9580   assert_different_registers(basic_lock, obj, reg_rax, thread, tmp);
9581 
9582   Label push;
9583   const Register top = tmp;
9584 
9585   // Preload the markWord. It is important that this is the first
9586   // instruction emitted as it is part of C1's null check semantics.
9587   movptr(reg_rax, Address(obj, oopDesc::mark_offset_in_bytes()));
9588 
9589   if (UseObjectMonitorTable) {
9590     // Clear cache in case fast locking succeeds or we need to take the slow-path.
9591     movptr(Address(basic_lock, BasicObjectLock::lock_offset() + in_ByteSize((BasicLock::object_monitor_cache_offset_in_bytes()))), 0);
9592   }
9593 
9594   if (DiagnoseSyncOnValueBasedClasses != 0) {
9595     load_klass(tmp, obj, rscratch1);
9596     testb(Address(tmp, Klass::misc_flags_offset()), KlassFlags::_misc_is_value_based_class);
9597     jcc(Assembler::notZero, slow);
9598   }
9599 
9600   // Load top.
9601   movl(top, Address(thread, JavaThread::lock_stack_top_offset()));
9602 
9603   // Check if the lock-stack is full.
9604   cmpl(top, LockStack::end_offset());
9605   jcc(Assembler::greaterEqual, slow);
9606 
9607   // Check for recursion.
9608   cmpptr(obj, Address(thread, top, Address::times_1, -oopSize));
9609   jcc(Assembler::equal, push);
9610 
9611   // Check header for monitor (0b10).
9612   testptr(reg_rax, markWord::monitor_value);
9613   jcc(Assembler::notZero, slow);
9614 
9615   // Try to lock. Transition lock bits 0b01 => 0b00
9616   movptr(tmp, reg_rax);
9617   andptr(tmp, ~(int32_t)markWord::unlocked_value);
9618   orptr(reg_rax, markWord::unlocked_value);
9619   lock(); cmpxchgptr(tmp, Address(obj, oopDesc::mark_offset_in_bytes()));
9620   jcc(Assembler::notEqual, slow);
9621 
9622   // Restore top, CAS clobbers register.
9623   movl(top, Address(thread, JavaThread::lock_stack_top_offset()));
9624 
9625   bind(push);
9626   // After successful lock, push object on lock-stack.
9627   movptr(Address(thread, top), obj);
9628   incrementl(top, oopSize);
9629   movl(Address(thread, JavaThread::lock_stack_top_offset()), top);
9630 }
9631 
9632 // Implements lightweight-unlocking.
9633 //
9634 // obj: the object to be unlocked
9635 // reg_rax: rax
9636 // thread: the thread
9637 // tmp: a temporary register
9638 void MacroAssembler::lightweight_unlock(Register obj, Register reg_rax, Register tmp, Label& slow) {
9639   Register thread = r15_thread;
9640 
9641   assert(reg_rax == rax, "");
9642   assert_different_registers(obj, reg_rax, thread, tmp);
9643 
9644   Label unlocked, push_and_slow;
9645   const Register top = tmp;
9646 
9647   // Check if obj is top of lock-stack.
9648   movl(top, Address(thread, JavaThread::lock_stack_top_offset()));
9649   cmpptr(obj, Address(thread, top, Address::times_1, -oopSize));
9650   jcc(Assembler::notEqual, slow);
9651 
9652   // Pop lock-stack.
9653   DEBUG_ONLY(movptr(Address(thread, top, Address::times_1, -oopSize), 0);)
9654   subl(Address(thread, JavaThread::lock_stack_top_offset()), oopSize);
9655 
9656   // Check if recursive.
9657   cmpptr(obj, Address(thread, top, Address::times_1, -2 * oopSize));
9658   jcc(Assembler::equal, unlocked);
9659 
9660   // Not recursive. Check header for monitor (0b10).
9661   movptr(reg_rax, Address(obj, oopDesc::mark_offset_in_bytes()));
9662   testptr(reg_rax, markWord::monitor_value);
9663   jcc(Assembler::notZero, push_and_slow);
9664 
9665 #ifdef ASSERT
9666   // Check header not unlocked (0b01).
9667   Label not_unlocked;
9668   testptr(reg_rax, markWord::unlocked_value);
9669   jcc(Assembler::zero, not_unlocked);
9670   stop("lightweight_unlock already unlocked");
9671   bind(not_unlocked);
9672 #endif
9673 
9674   // Try to unlock. Transition lock bits 0b00 => 0b01
9675   movptr(tmp, reg_rax);
9676   orptr(tmp, markWord::unlocked_value);
9677   lock(); cmpxchgptr(tmp, Address(obj, oopDesc::mark_offset_in_bytes()));
9678   jcc(Assembler::equal, unlocked);
9679 
9680   bind(push_and_slow);
9681   // Restore lock-stack and handle the unlock in runtime.
9682 #ifdef ASSERT
9683   movl(top, Address(thread, JavaThread::lock_stack_top_offset()));
9684   movptr(Address(thread, top), obj);
9685 #endif
9686   addl(Address(thread, JavaThread::lock_stack_top_offset()), oopSize);
9687   jmp(slow);
9688 
9689   bind(unlocked);
9690 }
9691 
9692 // Saves legacy GPRs state on stack.
9693 void MacroAssembler::save_legacy_gprs() {
9694   subq(rsp, 16 * wordSize);
9695   movq(Address(rsp, 15 * wordSize), rax);
9696   movq(Address(rsp, 14 * wordSize), rcx);
9697   movq(Address(rsp, 13 * wordSize), rdx);
9698   movq(Address(rsp, 12 * wordSize), rbx);
9699   movq(Address(rsp, 10 * wordSize), rbp);
9700   movq(Address(rsp, 9 * wordSize), rsi);
9701   movq(Address(rsp, 8 * wordSize), rdi);
9702   movq(Address(rsp, 7 * wordSize), r8);
9703   movq(Address(rsp, 6 * wordSize), r9);
9704   movq(Address(rsp, 5 * wordSize), r10);
9705   movq(Address(rsp, 4 * wordSize), r11);
9706   movq(Address(rsp, 3 * wordSize), r12);
9707   movq(Address(rsp, 2 * wordSize), r13);
9708   movq(Address(rsp, wordSize), r14);
9709   movq(Address(rsp, 0), r15);
9710 }
9711 
9712 // Resotres back legacy GPRs state from stack.
9713 void MacroAssembler::restore_legacy_gprs() {
9714   movq(r15, Address(rsp, 0));
9715   movq(r14, Address(rsp, wordSize));
9716   movq(r13, Address(rsp, 2 * wordSize));
9717   movq(r12, Address(rsp, 3 * wordSize));
9718   movq(r11, Address(rsp, 4 * wordSize));
9719   movq(r10, Address(rsp, 5 * wordSize));
9720   movq(r9,  Address(rsp, 6 * wordSize));
9721   movq(r8,  Address(rsp, 7 * wordSize));
9722   movq(rdi, Address(rsp, 8 * wordSize));
9723   movq(rsi, Address(rsp, 9 * wordSize));
9724   movq(rbp, Address(rsp, 10 * wordSize));
9725   movq(rbx, Address(rsp, 12 * wordSize));
9726   movq(rdx, Address(rsp, 13 * wordSize));
9727   movq(rcx, Address(rsp, 14 * wordSize));
9728   movq(rax, Address(rsp, 15 * wordSize));
9729   addq(rsp, 16 * wordSize);
9730 }
9731 
9732 void MacroAssembler::setcc(Assembler::Condition comparison, Register dst) {
9733   if (VM_Version::supports_apx_f()) {
9734     esetzucc(comparison, dst);
9735   } else {
9736     setb(comparison, dst);
9737     movzbl(dst, dst);
9738   }
9739 }