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