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