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