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