1 /*
   2  * Copyright (c) 1997, 2018, 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/klass.inline.hpp"
  38 #include "prims/methodHandles.hpp"
  39 #include "runtime/biasedLocking.hpp"
  40 #include "runtime/flags/flagSetting.hpp"
  41 #include "runtime/interfaceSupport.inline.hpp"
  42 #include "runtime/objectMonitor.hpp"
  43 #include "runtime/os.hpp"
  44 #include "runtime/safepoint.hpp"
  45 #include "runtime/safepointMechanism.hpp"
  46 #include "runtime/sharedRuntime.hpp"
  47 #include "runtime/stubRoutines.hpp"
  48 #include "runtime/thread.hpp"
  49 #include "utilities/macros.hpp"
  50 #include "crc32c.h"
  51 #ifdef COMPILER2
  52 #include "opto/intrinsicnode.hpp"
  53 #endif
  54 
  55 #ifdef PRODUCT
  56 #define BLOCK_COMMENT(str) /* nothing */
  57 #define STOP(error) stop(error)
  58 #else
  59 #define BLOCK_COMMENT(str) block_comment(str)
  60 #define STOP(error) block_comment(error); stop(error)
  61 #endif
  62 
  63 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  64 
  65 #ifdef ASSERT
  66 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  67 #endif
  68 
  69 static Assembler::Condition reverse[] = {
  70     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  71     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  72     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  73     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  74     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  75     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  76     Assembler::above          /* belowEqual    = 0x6 */ ,
  77     Assembler::belowEqual     /* above         = 0x7 */ ,
  78     Assembler::positive       /* negative      = 0x8 */ ,
  79     Assembler::negative       /* positive      = 0x9 */ ,
  80     Assembler::noParity       /* parity        = 0xa */ ,
  81     Assembler::parity         /* noParity      = 0xb */ ,
  82     Assembler::greaterEqual   /* less          = 0xc */ ,
  83     Assembler::less           /* greaterEqual  = 0xd */ ,
  84     Assembler::greater        /* lessEqual     = 0xe */ ,
  85     Assembler::lessEqual      /* greater       = 0xf, */
  86 
  87 };
  88 
  89 
  90 // Implementation of MacroAssembler
  91 
  92 // First all the versions that have distinct versions depending on 32/64 bit
  93 // Unless the difference is trivial (1 line or so).
  94 
  95 #ifndef _LP64
  96 
  97 // 32bit versions
  98 
  99 Address MacroAssembler::as_Address(AddressLiteral adr) {
 100   return Address(adr.target(), adr.rspec());
 101 }
 102 
 103 Address MacroAssembler::as_Address(ArrayAddress adr) {
 104   return Address::make_array(adr);
 105 }
 106 
 107 void MacroAssembler::call_VM_leaf_base(address entry_point,
 108                                        int number_of_arguments) {
 109   call(RuntimeAddress(entry_point));
 110   increment(rsp, number_of_arguments * wordSize);
 111 }
 112 
 113 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 114   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 115 }
 116 
 117 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 118   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 119 }
 120 
 121 void MacroAssembler::cmpoop_raw(Address src1, jobject obj) {
 122   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 123 }
 124 
 125 void MacroAssembler::cmpoop_raw(Register src1, jobject obj) {
 126   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 127 }
 128 
 129 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 130   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
 131   bs->obj_equals(this, src1, obj);
 132 }
 133 
 134 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 135   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
 136   bs->obj_equals(this, src1, obj);
 137 }
 138 
 139 void MacroAssembler::extend_sign(Register hi, Register lo) {
 140   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 141   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 142     cdql();
 143   } else {
 144     movl(hi, lo);
 145     sarl(hi, 31);
 146   }
 147 }
 148 
 149 void MacroAssembler::jC2(Register tmp, Label& L) {
 150   // set parity bit if FPU flag C2 is set (via rax)
 151   save_rax(tmp);
 152   fwait(); fnstsw_ax();
 153   sahf();
 154   restore_rax(tmp);
 155   // branch
 156   jcc(Assembler::parity, L);
 157 }
 158 
 159 void MacroAssembler::jnC2(Register tmp, Label& L) {
 160   // set parity bit if FPU flag C2 is set (via rax)
 161   save_rax(tmp);
 162   fwait(); fnstsw_ax();
 163   sahf();
 164   restore_rax(tmp);
 165   // branch
 166   jcc(Assembler::noParity, L);
 167 }
 168 
 169 // 32bit can do a case table jump in one instruction but we no longer allow the base
 170 // to be installed in the Address class
 171 void MacroAssembler::jump(ArrayAddress entry) {
 172   jmp(as_Address(entry));
 173 }
 174 
 175 // Note: y_lo will be destroyed
 176 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 177   // Long compare for Java (semantics as described in JVM spec.)
 178   Label high, low, done;
 179 
 180   cmpl(x_hi, y_hi);
 181   jcc(Assembler::less, low);
 182   jcc(Assembler::greater, high);
 183   // x_hi is the return register
 184   xorl(x_hi, x_hi);
 185   cmpl(x_lo, y_lo);
 186   jcc(Assembler::below, low);
 187   jcc(Assembler::equal, done);
 188 
 189   bind(high);
 190   xorl(x_hi, x_hi);
 191   increment(x_hi);
 192   jmp(done);
 193 
 194   bind(low);
 195   xorl(x_hi, x_hi);
 196   decrementl(x_hi);
 197 
 198   bind(done);
 199 }
 200 
 201 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 202     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 203 }
 204 
 205 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 206   // leal(dst, as_Address(adr));
 207   // see note in movl as to why we must use a move
 208   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 209 }
 210 
 211 void MacroAssembler::leave() {
 212   mov(rsp, rbp);
 213   pop(rbp);
 214 }
 215 
 216 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 217   // Multiplication of two Java long values stored on the stack
 218   // as illustrated below. Result is in rdx:rax.
 219   //
 220   // rsp ---> [  ??  ] \               \
 221   //            ....    | y_rsp_offset  |
 222   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 223   //          [ y_hi ]                  | (in bytes)
 224   //            ....                    |
 225   //          [ x_lo ]                 /
 226   //          [ x_hi ]
 227   //            ....
 228   //
 229   // Basic idea: lo(result) = lo(x_lo * y_lo)
 230   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 231   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 232   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 233   Label quick;
 234   // load x_hi, y_hi and check if quick
 235   // multiplication is possible
 236   movl(rbx, x_hi);
 237   movl(rcx, y_hi);
 238   movl(rax, rbx);
 239   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 240   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 241   // do full multiplication
 242   // 1st step
 243   mull(y_lo);                                    // x_hi * y_lo
 244   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 245   // 2nd step
 246   movl(rax, x_lo);
 247   mull(rcx);                                     // x_lo * y_hi
 248   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 249   // 3rd step
 250   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 251   movl(rax, x_lo);
 252   mull(y_lo);                                    // x_lo * y_lo
 253   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 254 }
 255 
 256 void MacroAssembler::lneg(Register hi, Register lo) {
 257   negl(lo);
 258   adcl(hi, 0);
 259   negl(hi);
 260 }
 261 
 262 void MacroAssembler::lshl(Register hi, Register lo) {
 263   // Java shift left long support (semantics as described in JVM spec., p.305)
 264   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 265   // shift value is in rcx !
 266   assert(hi != rcx, "must not use rcx");
 267   assert(lo != rcx, "must not use rcx");
 268   const Register s = rcx;                        // shift count
 269   const int      n = BitsPerWord;
 270   Label L;
 271   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 272   cmpl(s, n);                                    // if (s < n)
 273   jcc(Assembler::less, L);                       // else (s >= n)
 274   movl(hi, lo);                                  // x := x << n
 275   xorl(lo, lo);
 276   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 277   bind(L);                                       // s (mod n) < n
 278   shldl(hi, lo);                                 // x := x << s
 279   shll(lo);
 280 }
 281 
 282 
 283 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 284   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 285   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 286   assert(hi != rcx, "must not use rcx");
 287   assert(lo != rcx, "must not use rcx");
 288   const Register s = rcx;                        // shift count
 289   const int      n = BitsPerWord;
 290   Label L;
 291   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 292   cmpl(s, n);                                    // if (s < n)
 293   jcc(Assembler::less, L);                       // else (s >= n)
 294   movl(lo, hi);                                  // x := x >> n
 295   if (sign_extension) sarl(hi, 31);
 296   else                xorl(hi, hi);
 297   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 298   bind(L);                                       // s (mod n) < n
 299   shrdl(lo, hi);                                 // x := x >> s
 300   if (sign_extension) sarl(hi);
 301   else                shrl(hi);
 302 }
 303 
 304 void MacroAssembler::movoop(Register dst, jobject obj) {
 305   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 306 }
 307 
 308 void MacroAssembler::movoop(Address dst, jobject obj) {
 309   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 310 }
 311 
 312 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 313   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 314 }
 315 
 316 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 317   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 318 }
 319 
 320 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 321   // scratch register is not used,
 322   // it is defined to match parameters of 64-bit version of this method.
 323   if (src.is_lval()) {
 324     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 325   } else {
 326     movl(dst, as_Address(src));
 327   }
 328 }
 329 
 330 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 331   movl(as_Address(dst), src);
 332 }
 333 
 334 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 335   movl(dst, as_Address(src));
 336 }
 337 
 338 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 339 void MacroAssembler::movptr(Address dst, intptr_t src) {
 340   movl(dst, src);
 341 }
 342 
 343 
 344 void MacroAssembler::pop_callee_saved_registers() {
 345   pop(rcx);
 346   pop(rdx);
 347   pop(rdi);
 348   pop(rsi);
 349 }
 350 
 351 void MacroAssembler::pop_fTOS() {
 352   fld_d(Address(rsp, 0));
 353   addl(rsp, 2 * wordSize);
 354 }
 355 
 356 void MacroAssembler::push_callee_saved_registers() {
 357   push(rsi);
 358   push(rdi);
 359   push(rdx);
 360   push(rcx);
 361 }
 362 
 363 void MacroAssembler::push_fTOS() {
 364   subl(rsp, 2 * wordSize);
 365   fstp_d(Address(rsp, 0));
 366 }
 367 
 368 
 369 void MacroAssembler::pushoop(jobject obj) {
 370   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 371 }
 372 
 373 void MacroAssembler::pushklass(Metadata* obj) {
 374   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 375 }
 376 
 377 void MacroAssembler::pushptr(AddressLiteral src) {
 378   if (src.is_lval()) {
 379     push_literal32((int32_t)src.target(), src.rspec());
 380   } else {
 381     pushl(as_Address(src));
 382   }
 383 }
 384 
 385 void MacroAssembler::set_word_if_not_zero(Register dst) {
 386   xorl(dst, dst);
 387   set_byte_if_not_zero(dst);
 388 }
 389 
 390 static void pass_arg0(MacroAssembler* masm, Register arg) {
 391   masm->push(arg);
 392 }
 393 
 394 static void pass_arg1(MacroAssembler* masm, Register arg) {
 395   masm->push(arg);
 396 }
 397 
 398 static void pass_arg2(MacroAssembler* masm, Register arg) {
 399   masm->push(arg);
 400 }
 401 
 402 static void pass_arg3(MacroAssembler* masm, Register arg) {
 403   masm->push(arg);
 404 }
 405 
 406 #ifndef PRODUCT
 407 extern "C" void findpc(intptr_t x);
 408 #endif
 409 
 410 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 411   // In order to get locks to work, we need to fake a in_VM state
 412   JavaThread* thread = JavaThread::current();
 413   JavaThreadState saved_state = thread->thread_state();
 414   thread->set_thread_state(_thread_in_vm);
 415   if (ShowMessageBoxOnError) {
 416     JavaThread* thread = JavaThread::current();
 417     JavaThreadState saved_state = thread->thread_state();
 418     thread->set_thread_state(_thread_in_vm);
 419     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 420       ttyLocker ttyl;
 421       BytecodeCounter::print();
 422     }
 423     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 424     // This is the value of eip which points to where verify_oop will return.
 425     if (os::message_box(msg, "Execution stopped, print registers?")) {
 426       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 427       BREAKPOINT;
 428     }
 429   } else {
 430     ttyLocker ttyl;
 431     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 432   }
 433   // Don't assert holding the ttyLock
 434     assert(false, "DEBUG MESSAGE: %s", msg);
 435   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 436 }
 437 
 438 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 439   ttyLocker ttyl;
 440   FlagSetting fs(Debugging, true);
 441   tty->print_cr("eip = 0x%08x", eip);
 442 #ifndef PRODUCT
 443   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 444     tty->cr();
 445     findpc(eip);
 446     tty->cr();
 447   }
 448 #endif
 449 #define PRINT_REG(rax) \
 450   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 451   PRINT_REG(rax);
 452   PRINT_REG(rbx);
 453   PRINT_REG(rcx);
 454   PRINT_REG(rdx);
 455   PRINT_REG(rdi);
 456   PRINT_REG(rsi);
 457   PRINT_REG(rbp);
 458   PRINT_REG(rsp);
 459 #undef PRINT_REG
 460   // Print some words near top of staack.
 461   int* dump_sp = (int*) rsp;
 462   for (int col1 = 0; col1 < 8; col1++) {
 463     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 464     os::print_location(tty, *dump_sp++);
 465   }
 466   for (int row = 0; row < 16; row++) {
 467     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 468     for (int col = 0; col < 8; col++) {
 469       tty->print(" 0x%08x", *dump_sp++);
 470     }
 471     tty->cr();
 472   }
 473   // Print some instructions around pc:
 474   Disassembler::decode((address)eip-64, (address)eip);
 475   tty->print_cr("--------");
 476   Disassembler::decode((address)eip, (address)eip+32);
 477 }
 478 
 479 void MacroAssembler::stop(const char* msg) {
 480   ExternalAddress message((address)msg);
 481   // push address of message
 482   pushptr(message.addr());
 483   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 484   pusha();                                            // push registers
 485   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 486   hlt();
 487 }
 488 
 489 void MacroAssembler::warn(const char* msg) {
 490   push_CPU_state();
 491 
 492   ExternalAddress message((address) msg);
 493   // push address of message
 494   pushptr(message.addr());
 495 
 496   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 497   addl(rsp, wordSize);       // discard argument
 498   pop_CPU_state();
 499 }
 500 
 501 void MacroAssembler::print_state() {
 502   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 503   pusha();                                            // push registers
 504 
 505   push_CPU_state();
 506   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 507   pop_CPU_state();
 508 
 509   popa();
 510   addl(rsp, wordSize);
 511 }
 512 
 513 #else // _LP64
 514 
 515 // 64 bit versions
 516 
 517 Address MacroAssembler::as_Address(AddressLiteral adr) {
 518   // amd64 always does this as a pc-rel
 519   // we can be absolute or disp based on the instruction type
 520   // jmp/call are displacements others are absolute
 521   assert(!adr.is_lval(), "must be rval");
 522   assert(reachable(adr), "must be");
 523   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 524 
 525 }
 526 
 527 Address MacroAssembler::as_Address(ArrayAddress adr) {
 528   AddressLiteral base = adr.base();
 529   lea(rscratch1, base);
 530   Address index = adr.index();
 531   assert(index._disp == 0, "must not have disp"); // maybe it can?
 532   Address array(rscratch1, index._index, index._scale, index._disp);
 533   return array;
 534 }
 535 
 536 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 537   Label L, E;
 538 
 539 #ifdef _WIN64
 540   // Windows always allocates space for it's register args
 541   assert(num_args <= 4, "only register arguments supported");
 542   subq(rsp,  frame::arg_reg_save_area_bytes);
 543 #endif
 544 
 545   // Align stack if necessary
 546   testl(rsp, 15);
 547   jcc(Assembler::zero, L);
 548 
 549   subq(rsp, 8);
 550   {
 551     call(RuntimeAddress(entry_point));
 552   }
 553   addq(rsp, 8);
 554   jmp(E);
 555 
 556   bind(L);
 557   {
 558     call(RuntimeAddress(entry_point));
 559   }
 560 
 561   bind(E);
 562 
 563 #ifdef _WIN64
 564   // restore stack pointer
 565   addq(rsp, frame::arg_reg_save_area_bytes);
 566 #endif
 567 
 568 }
 569 
 570 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 571   assert(!src2.is_lval(), "should use cmpptr");
 572 
 573   if (reachable(src2)) {
 574     cmpq(src1, as_Address(src2));
 575   } else {
 576     lea(rscratch1, src2);
 577     Assembler::cmpq(src1, Address(rscratch1, 0));
 578   }
 579 }
 580 
 581 int MacroAssembler::corrected_idivq(Register reg) {
 582   // Full implementation of Java ldiv and lrem; checks for special
 583   // case as described in JVM spec., p.243 & p.271.  The function
 584   // returns the (pc) offset of the idivl instruction - may be needed
 585   // for implicit exceptions.
 586   //
 587   //         normal case                           special case
 588   //
 589   // input : rax: dividend                         min_long
 590   //         reg: divisor   (may not be eax/edx)   -1
 591   //
 592   // output: rax: quotient  (= rax idiv reg)       min_long
 593   //         rdx: remainder (= rax irem reg)       0
 594   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 595   static const int64_t min_long = 0x8000000000000000;
 596   Label normal_case, special_case;
 597 
 598   // check for special case
 599   cmp64(rax, ExternalAddress((address) &min_long));
 600   jcc(Assembler::notEqual, normal_case);
 601   xorl(rdx, rdx); // prepare rdx for possible special case (where
 602                   // remainder = 0)
 603   cmpq(reg, -1);
 604   jcc(Assembler::equal, special_case);
 605 
 606   // handle normal case
 607   bind(normal_case);
 608   cdqq();
 609   int idivq_offset = offset();
 610   idivq(reg);
 611 
 612   // normal and special case exit
 613   bind(special_case);
 614 
 615   return idivq_offset;
 616 }
 617 
 618 void MacroAssembler::decrementq(Register reg, int value) {
 619   if (value == min_jint) { subq(reg, value); return; }
 620   if (value <  0) { incrementq(reg, -value); return; }
 621   if (value == 0) {                        ; return; }
 622   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 623   /* else */      { subq(reg, value)       ; return; }
 624 }
 625 
 626 void MacroAssembler::decrementq(Address dst, int value) {
 627   if (value == min_jint) { subq(dst, value); return; }
 628   if (value <  0) { incrementq(dst, -value); return; }
 629   if (value == 0) {                        ; return; }
 630   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 631   /* else */      { subq(dst, value)       ; return; }
 632 }
 633 
 634 void MacroAssembler::incrementq(AddressLiteral dst) {
 635   if (reachable(dst)) {
 636     incrementq(as_Address(dst));
 637   } else {
 638     lea(rscratch1, dst);
 639     incrementq(Address(rscratch1, 0));
 640   }
 641 }
 642 
 643 void MacroAssembler::incrementq(Register reg, int value) {
 644   if (value == min_jint) { addq(reg, value); return; }
 645   if (value <  0) { decrementq(reg, -value); return; }
 646   if (value == 0) {                        ; return; }
 647   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 648   /* else */      { addq(reg, value)       ; return; }
 649 }
 650 
 651 void MacroAssembler::incrementq(Address dst, int value) {
 652   if (value == min_jint) { addq(dst, value); return; }
 653   if (value <  0) { decrementq(dst, -value); return; }
 654   if (value == 0) {                        ; return; }
 655   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 656   /* else */      { addq(dst, value)       ; return; }
 657 }
 658 
 659 // 32bit can do a case table jump in one instruction but we no longer allow the base
 660 // to be installed in the Address class
 661 void MacroAssembler::jump(ArrayAddress entry) {
 662   lea(rscratch1, entry.base());
 663   Address dispatch = entry.index();
 664   assert(dispatch._base == noreg, "must be");
 665   dispatch._base = rscratch1;
 666   jmp(dispatch);
 667 }
 668 
 669 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 670   ShouldNotReachHere(); // 64bit doesn't use two regs
 671   cmpq(x_lo, y_lo);
 672 }
 673 
 674 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 675     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 676 }
 677 
 678 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 679   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 680   movptr(dst, rscratch1);
 681 }
 682 
 683 void MacroAssembler::leave() {
 684   // %%% is this really better? Why not on 32bit too?
 685   emit_int8((unsigned char)0xC9); // LEAVE
 686 }
 687 
 688 void MacroAssembler::lneg(Register hi, Register lo) {
 689   ShouldNotReachHere(); // 64bit doesn't use two regs
 690   negq(lo);
 691 }
 692 
 693 void MacroAssembler::movoop(Register dst, jobject obj) {
 694   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 695 }
 696 
 697 void MacroAssembler::movoop(Address dst, jobject obj) {
 698   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 699   movq(dst, rscratch1);
 700 }
 701 
 702 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 703   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 704 }
 705 
 706 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 707   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 708   movq(dst, rscratch1);
 709 }
 710 
 711 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 712   if (src.is_lval()) {
 713     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 714   } else {
 715     if (reachable(src)) {
 716       movq(dst, as_Address(src));
 717     } else {
 718       lea(scratch, src);
 719       movq(dst, Address(scratch, 0));
 720     }
 721   }
 722 }
 723 
 724 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 725   movq(as_Address(dst), src);
 726 }
 727 
 728 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 729   movq(dst, as_Address(src));
 730 }
 731 
 732 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 733 void MacroAssembler::movptr(Address dst, intptr_t src) {
 734   mov64(rscratch1, src);
 735   movq(dst, rscratch1);
 736 }
 737 
 738 // These are mostly for initializing NULL
 739 void MacroAssembler::movptr(Address dst, int32_t src) {
 740   movslq(dst, src);
 741 }
 742 
 743 void MacroAssembler::movptr(Register dst, int32_t src) {
 744   mov64(dst, (intptr_t)src);
 745 }
 746 
 747 void MacroAssembler::pushoop(jobject obj) {
 748   movoop(rscratch1, obj);
 749   push(rscratch1);
 750 }
 751 
 752 void MacroAssembler::pushklass(Metadata* obj) {
 753   mov_metadata(rscratch1, obj);
 754   push(rscratch1);
 755 }
 756 
 757 void MacroAssembler::pushptr(AddressLiteral src) {
 758   lea(rscratch1, src);
 759   if (src.is_lval()) {
 760     push(rscratch1);
 761   } else {
 762     pushq(Address(rscratch1, 0));
 763   }
 764 }
 765 
 766 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 767   // we must set sp to zero to clear frame
 768   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 769   // must clear fp, so that compiled frames are not confused; it is
 770   // possible that we need it only for debugging
 771   if (clear_fp) {
 772     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 773   }
 774 
 775   // Always clear the pc because it could have been set by make_walkable()
 776   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 777   vzeroupper();
 778 }
 779 
 780 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 781                                          Register last_java_fp,
 782                                          address  last_java_pc) {
 783   vzeroupper();
 784   // determine last_java_sp register
 785   if (!last_java_sp->is_valid()) {
 786     last_java_sp = rsp;
 787   }
 788 
 789   // last_java_fp is optional
 790   if (last_java_fp->is_valid()) {
 791     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 792            last_java_fp);
 793   }
 794 
 795   // last_java_pc is optional
 796   if (last_java_pc != NULL) {
 797     Address java_pc(r15_thread,
 798                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 799     lea(rscratch1, InternalAddress(last_java_pc));
 800     movptr(java_pc, rscratch1);
 801   }
 802 
 803   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 804 }
 805 
 806 static void pass_arg0(MacroAssembler* masm, Register arg) {
 807   if (c_rarg0 != arg ) {
 808     masm->mov(c_rarg0, arg);
 809   }
 810 }
 811 
 812 static void pass_arg1(MacroAssembler* masm, Register arg) {
 813   if (c_rarg1 != arg ) {
 814     masm->mov(c_rarg1, arg);
 815   }
 816 }
 817 
 818 static void pass_arg2(MacroAssembler* masm, Register arg) {
 819   if (c_rarg2 != arg ) {
 820     masm->mov(c_rarg2, arg);
 821   }
 822 }
 823 
 824 static void pass_arg3(MacroAssembler* masm, Register arg) {
 825   if (c_rarg3 != arg ) {
 826     masm->mov(c_rarg3, arg);
 827   }
 828 }
 829 
 830 void MacroAssembler::stop(const char* msg) {
 831   address rip = pc();
 832   pusha(); // get regs on stack
 833   lea(c_rarg0, ExternalAddress((address) msg));
 834   lea(c_rarg1, InternalAddress(rip));
 835   movq(c_rarg2, rsp); // pass pointer to regs array
 836   andq(rsp, -16); // align stack as required by ABI
 837   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 838   hlt();
 839 }
 840 
 841 void MacroAssembler::warn(const char* msg) {
 842   push(rbp);
 843   movq(rbp, rsp);
 844   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 845   push_CPU_state();   // keeps alignment at 16 bytes
 846   lea(c_rarg0, ExternalAddress((address) msg));
 847   lea(rax, ExternalAddress(CAST_FROM_FN_PTR(address, warning)));
 848   call(rax);
 849   pop_CPU_state();
 850   mov(rsp, rbp);
 851   pop(rbp);
 852 }
 853 
 854 void MacroAssembler::print_state() {
 855   address rip = pc();
 856   pusha();            // get regs on stack
 857   push(rbp);
 858   movq(rbp, rsp);
 859   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 860   push_CPU_state();   // keeps alignment at 16 bytes
 861 
 862   lea(c_rarg0, InternalAddress(rip));
 863   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 864   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 865 
 866   pop_CPU_state();
 867   mov(rsp, rbp);
 868   pop(rbp);
 869   popa();
 870 }
 871 
 872 #ifndef PRODUCT
 873 extern "C" void findpc(intptr_t x);
 874 #endif
 875 
 876 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 877   // In order to get locks to work, we need to fake a in_VM state
 878   if (ShowMessageBoxOnError) {
 879     JavaThread* thread = JavaThread::current();
 880     JavaThreadState saved_state = thread->thread_state();
 881     thread->set_thread_state(_thread_in_vm);
 882 #ifndef PRODUCT
 883     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 884       ttyLocker ttyl;
 885       BytecodeCounter::print();
 886     }
 887 #endif
 888     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 889     // XXX correct this offset for amd64
 890     // This is the value of eip which points to where verify_oop will return.
 891     if (os::message_box(msg, "Execution stopped, print registers?")) {
 892       print_state64(pc, regs);
 893       BREAKPOINT;
 894       assert(false, "start up GDB");
 895     }
 896     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 897   } else {
 898     ttyLocker ttyl;
 899     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 900                     msg);
 901     assert(false, "DEBUG MESSAGE: %s", msg);
 902   }
 903 }
 904 
 905 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 906   ttyLocker ttyl;
 907   FlagSetting fs(Debugging, true);
 908   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 909 #ifndef PRODUCT
 910   tty->cr();
 911   findpc(pc);
 912   tty->cr();
 913 #endif
 914 #define PRINT_REG(rax, value) \
 915   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 916   PRINT_REG(rax, regs[15]);
 917   PRINT_REG(rbx, regs[12]);
 918   PRINT_REG(rcx, regs[14]);
 919   PRINT_REG(rdx, regs[13]);
 920   PRINT_REG(rdi, regs[8]);
 921   PRINT_REG(rsi, regs[9]);
 922   PRINT_REG(rbp, regs[10]);
 923   PRINT_REG(rsp, regs[11]);
 924   PRINT_REG(r8 , regs[7]);
 925   PRINT_REG(r9 , regs[6]);
 926   PRINT_REG(r10, regs[5]);
 927   PRINT_REG(r11, regs[4]);
 928   PRINT_REG(r12, regs[3]);
 929   PRINT_REG(r13, regs[2]);
 930   PRINT_REG(r14, regs[1]);
 931   PRINT_REG(r15, regs[0]);
 932 #undef PRINT_REG
 933   // Print some words near top of staack.
 934   int64_t* rsp = (int64_t*) regs[11];
 935   int64_t* dump_sp = rsp;
 936   for (int col1 = 0; col1 < 8; col1++) {
 937     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 938     os::print_location(tty, *dump_sp++);
 939   }
 940   for (int row = 0; row < 25; row++) {
 941     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 942     for (int col = 0; col < 4; col++) {
 943       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 944     }
 945     tty->cr();
 946   }
 947   // Print some instructions around pc:
 948   Disassembler::decode((address)pc-64, (address)pc);
 949   tty->print_cr("--------");
 950   Disassembler::decode((address)pc, (address)pc+32);
 951 }
 952 
 953 #endif // _LP64
 954 
 955 // Now versions that are common to 32/64 bit
 956 
 957 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 958   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 959 }
 960 
 961 void MacroAssembler::addptr(Register dst, Register src) {
 962   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 963 }
 964 
 965 void MacroAssembler::addptr(Address dst, Register src) {
 966   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 967 }
 968 
 969 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 970   if (reachable(src)) {
 971     Assembler::addsd(dst, as_Address(src));
 972   } else {
 973     lea(rscratch1, src);
 974     Assembler::addsd(dst, Address(rscratch1, 0));
 975   }
 976 }
 977 
 978 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 979   if (reachable(src)) {
 980     addss(dst, as_Address(src));
 981   } else {
 982     lea(rscratch1, src);
 983     addss(dst, Address(rscratch1, 0));
 984   }
 985 }
 986 
 987 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 988   if (reachable(src)) {
 989     Assembler::addpd(dst, as_Address(src));
 990   } else {
 991     lea(rscratch1, src);
 992     Assembler::addpd(dst, Address(rscratch1, 0));
 993   }
 994 }
 995 
 996 void MacroAssembler::align(int modulus) {
 997   align(modulus, offset());
 998 }
 999 
1000 void MacroAssembler::align(int modulus, int target) {
1001   if (target % modulus != 0) {
1002     nop(modulus - (target % modulus));
1003   }
1004 }
1005 
1006 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
1007   // Used in sign-masking with aligned address.
1008   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1009   if (reachable(src)) {
1010     Assembler::andpd(dst, as_Address(src));
1011   } else {
1012     lea(rscratch1, src);
1013     Assembler::andpd(dst, Address(rscratch1, 0));
1014   }
1015 }
1016 
1017 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1018   // Used in sign-masking with aligned address.
1019   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1020   if (reachable(src)) {
1021     Assembler::andps(dst, as_Address(src));
1022   } else {
1023     lea(rscratch1, src);
1024     Assembler::andps(dst, Address(rscratch1, 0));
1025   }
1026 }
1027 
1028 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1029   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1030 }
1031 
1032 void MacroAssembler::atomic_incl(Address counter_addr) {
1033   lock();
1034   incrementl(counter_addr);
1035 }
1036 
1037 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1038   if (reachable(counter_addr)) {
1039     atomic_incl(as_Address(counter_addr));
1040   } else {
1041     lea(scr, counter_addr);
1042     atomic_incl(Address(scr, 0));
1043   }
1044 }
1045 
1046 #ifdef _LP64
1047 void MacroAssembler::atomic_incq(Address counter_addr) {
1048   lock();
1049   incrementq(counter_addr);
1050 }
1051 
1052 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1053   if (reachable(counter_addr)) {
1054     atomic_incq(as_Address(counter_addr));
1055   } else {
1056     lea(scr, counter_addr);
1057     atomic_incq(Address(scr, 0));
1058   }
1059 }
1060 #endif
1061 
1062 // Writes to stack successive pages until offset reached to check for
1063 // stack overflow + shadow pages.  This clobbers tmp.
1064 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1065   movptr(tmp, rsp);
1066   // Bang stack for total size given plus shadow page size.
1067   // Bang one page at a time because large size can bang beyond yellow and
1068   // red zones.
1069   Label loop;
1070   bind(loop);
1071   movl(Address(tmp, (-os::vm_page_size())), size );
1072   subptr(tmp, os::vm_page_size());
1073   subl(size, os::vm_page_size());
1074   jcc(Assembler::greater, loop);
1075 
1076   // Bang down shadow pages too.
1077   // At this point, (tmp-0) is the last address touched, so don't
1078   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1079   // was post-decremented.)  Skip this address by starting at i=1, and
1080   // touch a few more pages below.  N.B.  It is important to touch all
1081   // the way down including all pages in the shadow zone.
1082   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1083     // this could be any sized move but this is can be a debugging crumb
1084     // so the bigger the better.
1085     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1086   }
1087 }
1088 
1089 void MacroAssembler::reserved_stack_check() {
1090     // testing if reserved zone needs to be enabled
1091     Label no_reserved_zone_enabling;
1092     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1093     NOT_LP64(get_thread(rsi);)
1094 
1095     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1096     jcc(Assembler::below, no_reserved_zone_enabling);
1097 
1098     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1099     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1100     should_not_reach_here();
1101 
1102     bind(no_reserved_zone_enabling);
1103 }
1104 
1105 int MacroAssembler::biased_locking_enter(Register lock_reg,
1106                                          Register obj_reg,
1107                                          Register swap_reg,
1108                                          Register tmp_reg,
1109                                          bool swap_reg_contains_mark,
1110                                          Label& done,
1111                                          Label* slow_case,
1112                                          BiasedLockingCounters* counters) {
1113   assert(UseBiasedLocking, "why call this otherwise?");
1114   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1115   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1116   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1117   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1118   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1119   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1120 
1121   if (PrintBiasedLockingStatistics && counters == NULL) {
1122     counters = BiasedLocking::counters();
1123   }
1124   // Biased locking
1125   // See whether the lock is currently biased toward our thread and
1126   // whether the epoch is still valid
1127   // Note that the runtime guarantees sufficient alignment of JavaThread
1128   // pointers to allow age to be placed into low bits
1129   // First check to see whether biasing is even enabled for this object
1130   Label cas_label;
1131   int null_check_offset = -1;
1132   if (!swap_reg_contains_mark) {
1133     null_check_offset = offset();
1134     movptr(swap_reg, mark_addr);
1135   }
1136   movptr(tmp_reg, swap_reg);
1137   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1138   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1139   jcc(Assembler::notEqual, cas_label);
1140   // The bias pattern is present in the object's header. Need to check
1141   // whether the bias owner and the epoch are both still current.
1142 #ifndef _LP64
1143   // Note that because there is no current thread register on x86_32 we
1144   // need to store off the mark word we read out of the object to
1145   // avoid reloading it and needing to recheck invariants below. This
1146   // store is unfortunate but it makes the overall code shorter and
1147   // simpler.
1148   movptr(saved_mark_addr, swap_reg);
1149 #endif
1150   if (swap_reg_contains_mark) {
1151     null_check_offset = offset();
1152   }
1153   load_prototype_header(tmp_reg, obj_reg);
1154 #ifdef _LP64
1155   orptr(tmp_reg, r15_thread);
1156   xorptr(tmp_reg, swap_reg);
1157   Register header_reg = tmp_reg;
1158 #else
1159   xorptr(tmp_reg, swap_reg);
1160   get_thread(swap_reg);
1161   xorptr(swap_reg, tmp_reg);
1162   Register header_reg = swap_reg;
1163 #endif
1164   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1165   if (counters != NULL) {
1166     cond_inc32(Assembler::zero,
1167                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1168   }
1169   jcc(Assembler::equal, done);
1170 
1171   Label try_revoke_bias;
1172   Label try_rebias;
1173 
1174   // At this point we know that the header has the bias pattern and
1175   // that we are not the bias owner in the current epoch. We need to
1176   // figure out more details about the state of the header in order to
1177   // know what operations can be legally performed on the object's
1178   // header.
1179 
1180   // If the low three bits in the xor result aren't clear, that means
1181   // the prototype header is no longer biased and we have to revoke
1182   // the bias on this object.
1183   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1184   jccb(Assembler::notZero, try_revoke_bias);
1185 
1186   // Biasing is still enabled for this data type. See whether the
1187   // epoch of the current bias is still valid, meaning that the epoch
1188   // bits of the mark word are equal to the epoch bits of the
1189   // prototype header. (Note that the prototype header's epoch bits
1190   // only change at a safepoint.) If not, attempt to rebias the object
1191   // toward the current thread. Note that we must be absolutely sure
1192   // that the current epoch is invalid in order to do this because
1193   // otherwise the manipulations it performs on the mark word are
1194   // illegal.
1195   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1196   jccb(Assembler::notZero, try_rebias);
1197 
1198   // The epoch of the current bias is still valid but we know nothing
1199   // about the owner; it might be set or it might be clear. Try to
1200   // acquire the bias of the object using an atomic operation. If this
1201   // fails we will go in to the runtime to revoke the object's bias.
1202   // Note that we first construct the presumed unbiased header so we
1203   // don't accidentally blow away another thread's valid bias.
1204   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1205   andptr(swap_reg,
1206          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1207 #ifdef _LP64
1208   movptr(tmp_reg, swap_reg);
1209   orptr(tmp_reg, r15_thread);
1210 #else
1211   get_thread(tmp_reg);
1212   orptr(tmp_reg, swap_reg);
1213 #endif
1214   lock();
1215   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1216   // If the biasing toward our thread failed, this means that
1217   // another thread succeeded in biasing it toward itself and we
1218   // need to revoke that bias. The revocation will occur in the
1219   // interpreter runtime in the slow case.
1220   if (counters != NULL) {
1221     cond_inc32(Assembler::zero,
1222                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1223   }
1224   if (slow_case != NULL) {
1225     jcc(Assembler::notZero, *slow_case);
1226   }
1227   jmp(done);
1228 
1229   bind(try_rebias);
1230   // At this point we know the epoch has expired, meaning that the
1231   // current "bias owner", if any, is actually invalid. Under these
1232   // circumstances _only_, we are allowed to use the current header's
1233   // value as the comparison value when doing the cas to acquire the
1234   // bias in the current epoch. In other words, we allow transfer of
1235   // the bias from one thread to another directly in this situation.
1236   //
1237   // FIXME: due to a lack of registers we currently blow away the age
1238   // bits in this situation. Should attempt to preserve them.
1239   load_prototype_header(tmp_reg, obj_reg);
1240 #ifdef _LP64
1241   orptr(tmp_reg, r15_thread);
1242 #else
1243   get_thread(swap_reg);
1244   orptr(tmp_reg, swap_reg);
1245   movptr(swap_reg, saved_mark_addr);
1246 #endif
1247   lock();
1248   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1249   // If the biasing toward our thread failed, then another thread
1250   // succeeded in biasing it toward itself and we need to revoke that
1251   // bias. The revocation will occur in the runtime in the slow case.
1252   if (counters != NULL) {
1253     cond_inc32(Assembler::zero,
1254                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1255   }
1256   if (slow_case != NULL) {
1257     jcc(Assembler::notZero, *slow_case);
1258   }
1259   jmp(done);
1260 
1261   bind(try_revoke_bias);
1262   // The prototype mark in the klass doesn't have the bias bit set any
1263   // more, indicating that objects of this data type are not supposed
1264   // to be biased any more. We are going to try to reset the mark of
1265   // this object to the prototype value and fall through to the
1266   // CAS-based locking scheme. Note that if our CAS fails, it means
1267   // that another thread raced us for the privilege of revoking the
1268   // bias of this particular object, so it's okay to continue in the
1269   // normal locking code.
1270   //
1271   // FIXME: due to a lack of registers we currently blow away the age
1272   // bits in this situation. Should attempt to preserve them.
1273   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1274   load_prototype_header(tmp_reg, obj_reg);
1275   lock();
1276   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1277   // Fall through to the normal CAS-based lock, because no matter what
1278   // the result of the above CAS, some thread must have succeeded in
1279   // removing the bias bit from the object's header.
1280   if (counters != NULL) {
1281     cond_inc32(Assembler::zero,
1282                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1283   }
1284 
1285   bind(cas_label);
1286 
1287   return null_check_offset;
1288 }
1289 
1290 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1291   assert(UseBiasedLocking, "why call this otherwise?");
1292 
1293   // Check for biased locking unlock case, which is a no-op
1294   // Note: we do not have to check the thread ID for two reasons.
1295   // First, the interpreter checks for IllegalMonitorStateException at
1296   // a higher level. Second, if the bias was revoked while we held the
1297   // lock, the object could not be rebiased toward another thread, so
1298   // the bias bit would be clear.
1299   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1300   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1301   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1302   jcc(Assembler::equal, done);
1303 }
1304 
1305 #ifdef COMPILER2
1306 
1307 #if INCLUDE_RTM_OPT
1308 
1309 // Update rtm_counters based on abort status
1310 // input: abort_status
1311 //        rtm_counters (RTMLockingCounters*)
1312 // flags are killed
1313 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1314 
1315   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1316   if (PrintPreciseRTMLockingStatistics) {
1317     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1318       Label check_abort;
1319       testl(abort_status, (1<<i));
1320       jccb(Assembler::equal, check_abort);
1321       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1322       bind(check_abort);
1323     }
1324   }
1325 }
1326 
1327 // Branch if (random & (count-1) != 0), count is 2^n
1328 // tmp, scr and flags are killed
1329 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1330   assert(tmp == rax, "");
1331   assert(scr == rdx, "");
1332   rdtsc(); // modifies EDX:EAX
1333   andptr(tmp, count-1);
1334   jccb(Assembler::notZero, brLabel);
1335 }
1336 
1337 // Perform abort ratio calculation, set no_rtm bit if high ratio
1338 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1339 // tmpReg, rtm_counters_Reg and flags are killed
1340 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1341                                                  Register rtm_counters_Reg,
1342                                                  RTMLockingCounters* rtm_counters,
1343                                                  Metadata* method_data) {
1344   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1345 
1346   if (RTMLockingCalculationDelay > 0) {
1347     // Delay calculation
1348     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1349     testptr(tmpReg, tmpReg);
1350     jccb(Assembler::equal, L_done);
1351   }
1352   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1353   //   Aborted transactions = abort_count * 100
1354   //   All transactions = total_count *  RTMTotalCountIncrRate
1355   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1356 
1357   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1358   cmpptr(tmpReg, RTMAbortThreshold);
1359   jccb(Assembler::below, L_check_always_rtm2);
1360   imulptr(tmpReg, tmpReg, 100);
1361 
1362   Register scrReg = rtm_counters_Reg;
1363   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1364   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1365   imulptr(scrReg, scrReg, RTMAbortRatio);
1366   cmpptr(tmpReg, scrReg);
1367   jccb(Assembler::below, L_check_always_rtm1);
1368   if (method_data != NULL) {
1369     // set rtm_state to "no rtm" in MDO
1370     mov_metadata(tmpReg, method_data);
1371     lock();
1372     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1373   }
1374   jmpb(L_done);
1375   bind(L_check_always_rtm1);
1376   // Reload RTMLockingCounters* address
1377   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1378   bind(L_check_always_rtm2);
1379   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1380   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1381   jccb(Assembler::below, L_done);
1382   if (method_data != NULL) {
1383     // set rtm_state to "always rtm" in MDO
1384     mov_metadata(tmpReg, method_data);
1385     lock();
1386     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1387   }
1388   bind(L_done);
1389 }
1390 
1391 // Update counters and perform abort ratio calculation
1392 // input:  abort_status_Reg
1393 // rtm_counters_Reg, flags are killed
1394 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1395                                    Register rtm_counters_Reg,
1396                                    RTMLockingCounters* rtm_counters,
1397                                    Metadata* method_data,
1398                                    bool profile_rtm) {
1399 
1400   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1401   // update rtm counters based on rax value at abort
1402   // reads abort_status_Reg, updates flags
1403   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1404   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1405   if (profile_rtm) {
1406     // Save abort status because abort_status_Reg is used by following code.
1407     if (RTMRetryCount > 0) {
1408       push(abort_status_Reg);
1409     }
1410     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1411     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1412     // restore abort status
1413     if (RTMRetryCount > 0) {
1414       pop(abort_status_Reg);
1415     }
1416   }
1417 }
1418 
1419 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1420 // inputs: retry_count_Reg
1421 //       : abort_status_Reg
1422 // output: retry_count_Reg decremented by 1
1423 // flags are killed
1424 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1425   Label doneRetry;
1426   assert(abort_status_Reg == rax, "");
1427   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1428   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1429   // if reason is in 0x6 and retry count != 0 then retry
1430   andptr(abort_status_Reg, 0x6);
1431   jccb(Assembler::zero, doneRetry);
1432   testl(retry_count_Reg, retry_count_Reg);
1433   jccb(Assembler::zero, doneRetry);
1434   pause();
1435   decrementl(retry_count_Reg);
1436   jmp(retryLabel);
1437   bind(doneRetry);
1438 }
1439 
1440 // Spin and retry if lock is busy,
1441 // inputs: box_Reg (monitor address)
1442 //       : retry_count_Reg
1443 // output: retry_count_Reg decremented by 1
1444 //       : clear z flag if retry count exceeded
1445 // tmp_Reg, scr_Reg, flags are killed
1446 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1447                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1448   Label SpinLoop, SpinExit, doneRetry;
1449   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1450 
1451   testl(retry_count_Reg, retry_count_Reg);
1452   jccb(Assembler::zero, doneRetry);
1453   decrementl(retry_count_Reg);
1454   movptr(scr_Reg, RTMSpinLoopCount);
1455 
1456   bind(SpinLoop);
1457   pause();
1458   decrementl(scr_Reg);
1459   jccb(Assembler::lessEqual, SpinExit);
1460   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1461   testptr(tmp_Reg, tmp_Reg);
1462   jccb(Assembler::notZero, SpinLoop);
1463 
1464   bind(SpinExit);
1465   jmp(retryLabel);
1466   bind(doneRetry);
1467   incrementl(retry_count_Reg); // clear z flag
1468 }
1469 
1470 // Use RTM for normal stack locks
1471 // Input: objReg (object to lock)
1472 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1473                                        Register retry_on_abort_count_Reg,
1474                                        RTMLockingCounters* stack_rtm_counters,
1475                                        Metadata* method_data, bool profile_rtm,
1476                                        Label& DONE_LABEL, Label& IsInflated) {
1477   assert(UseRTMForStackLocks, "why call this otherwise?");
1478   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1479   assert(tmpReg == rax, "");
1480   assert(scrReg == rdx, "");
1481   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1482 
1483   if (RTMRetryCount > 0) {
1484     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1485     bind(L_rtm_retry);
1486   }
1487   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1488   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1489   jcc(Assembler::notZero, IsInflated);
1490 
1491   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1492     Label L_noincrement;
1493     if (RTMTotalCountIncrRate > 1) {
1494       // tmpReg, scrReg and flags are killed
1495       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1496     }
1497     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1498     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1499     bind(L_noincrement);
1500   }
1501   xbegin(L_on_abort);
1502   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1503   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1504   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1505   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1506 
1507   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1508   if (UseRTMXendForLockBusy) {
1509     xend();
1510     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1511     jmp(L_decrement_retry);
1512   }
1513   else {
1514     xabort(0);
1515   }
1516   bind(L_on_abort);
1517   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1518     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1519   }
1520   bind(L_decrement_retry);
1521   if (RTMRetryCount > 0) {
1522     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1523     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1524   }
1525 }
1526 
1527 // Use RTM for inflating locks
1528 // inputs: objReg (object to lock)
1529 //         boxReg (on-stack box address (displaced header location) - KILLED)
1530 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1531 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1532                                           Register scrReg, Register retry_on_busy_count_Reg,
1533                                           Register retry_on_abort_count_Reg,
1534                                           RTMLockingCounters* rtm_counters,
1535                                           Metadata* method_data, bool profile_rtm,
1536                                           Label& DONE_LABEL) {
1537   assert(UseRTMLocking, "why call this otherwise?");
1538   assert(tmpReg == rax, "");
1539   assert(scrReg == rdx, "");
1540   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1541   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1542 
1543   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1544   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1545   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1546 
1547   if (RTMRetryCount > 0) {
1548     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1549     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1550     bind(L_rtm_retry);
1551   }
1552   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1553     Label L_noincrement;
1554     if (RTMTotalCountIncrRate > 1) {
1555       // tmpReg, scrReg and flags are killed
1556       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1557     }
1558     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1559     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1560     bind(L_noincrement);
1561   }
1562   xbegin(L_on_abort);
1563   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1564   movptr(tmpReg, Address(tmpReg, owner_offset));
1565   testptr(tmpReg, tmpReg);
1566   jcc(Assembler::zero, DONE_LABEL);
1567   if (UseRTMXendForLockBusy) {
1568     xend();
1569     jmp(L_decrement_retry);
1570   }
1571   else {
1572     xabort(0);
1573   }
1574   bind(L_on_abort);
1575   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1576   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1577     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1578   }
1579   if (RTMRetryCount > 0) {
1580     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1581     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1582   }
1583 
1584   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1585   testptr(tmpReg, tmpReg) ;
1586   jccb(Assembler::notZero, L_decrement_retry) ;
1587 
1588   // Appears unlocked - try to swing _owner from null to non-null.
1589   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1590 #ifdef _LP64
1591   Register threadReg = r15_thread;
1592 #else
1593   get_thread(scrReg);
1594   Register threadReg = scrReg;
1595 #endif
1596   lock();
1597   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1598 
1599   if (RTMRetryCount > 0) {
1600     // success done else retry
1601     jccb(Assembler::equal, DONE_LABEL) ;
1602     bind(L_decrement_retry);
1603     // Spin and retry if lock is busy.
1604     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1605   }
1606   else {
1607     bind(L_decrement_retry);
1608   }
1609 }
1610 
1611 #endif //  INCLUDE_RTM_OPT
1612 
1613 // Fast_Lock and Fast_Unlock used by C2
1614 
1615 // Because the transitions from emitted code to the runtime
1616 // monitorenter/exit helper stubs are so slow it's critical that
1617 // we inline both the stack-locking fast-path and the inflated fast path.
1618 //
1619 // See also: cmpFastLock and cmpFastUnlock.
1620 //
1621 // What follows is a specialized inline transliteration of the code
1622 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1623 // another option would be to emit TrySlowEnter and TrySlowExit methods
1624 // at startup-time.  These methods would accept arguments as
1625 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1626 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1627 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1628 // In practice, however, the # of lock sites is bounded and is usually small.
1629 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1630 // if the processor uses simple bimodal branch predictors keyed by EIP
1631 // Since the helper routines would be called from multiple synchronization
1632 // sites.
1633 //
1634 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1635 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1636 // to those specialized methods.  That'd give us a mostly platform-independent
1637 // implementation that the JITs could optimize and inline at their pleasure.
1638 // Done correctly, the only time we'd need to cross to native could would be
1639 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1640 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1641 // (b) explicit barriers or fence operations.
1642 //
1643 // TODO:
1644 //
1645 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1646 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1647 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1648 //    the lock operators would typically be faster than reifying Self.
1649 //
1650 // *  Ideally I'd define the primitives as:
1651 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1652 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1653 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1654 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1655 //    Furthermore the register assignments are overconstrained, possibly resulting in
1656 //    sub-optimal code near the synchronization site.
1657 //
1658 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1659 //    Alternately, use a better sp-proximity test.
1660 //
1661 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1662 //    Either one is sufficient to uniquely identify a thread.
1663 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1664 //
1665 // *  Intrinsify notify() and notifyAll() for the common cases where the
1666 //    object is locked by the calling thread but the waitlist is empty.
1667 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1668 //
1669 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1670 //    But beware of excessive branch density on AMD Opterons.
1671 //
1672 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1673 //    or failure of the fast-path.  If the fast-path fails then we pass
1674 //    control to the slow-path, typically in C.  In Fast_Lock and
1675 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1676 //    will emit a conditional branch immediately after the node.
1677 //    So we have branches to branches and lots of ICC.ZF games.
1678 //    Instead, it might be better to have C2 pass a "FailureLabel"
1679 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1680 //    will drop through the node.  ICC.ZF is undefined at exit.
1681 //    In the case of failure, the node will branch directly to the
1682 //    FailureLabel
1683 
1684 
1685 // obj: object to lock
1686 // box: on-stack box address (displaced header location) - KILLED
1687 // rax,: tmp -- KILLED
1688 // scr: tmp -- KILLED
1689 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1690                                Register scrReg, Register cx1Reg, Register cx2Reg,
1691                                BiasedLockingCounters* counters,
1692                                RTMLockingCounters* rtm_counters,
1693                                RTMLockingCounters* stack_rtm_counters,
1694                                Metadata* method_data,
1695                                bool use_rtm, bool profile_rtm) {
1696   // Ensure the register assignments are disjoint
1697   assert(tmpReg == rax, "");
1698 
1699   if (use_rtm) {
1700     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1701   } else {
1702     assert(cx1Reg == noreg, "");
1703     assert(cx2Reg == noreg, "");
1704     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1705   }
1706 
1707   if (counters != NULL) {
1708     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1709   }
1710 
1711   // Possible cases that we'll encounter in fast_lock
1712   // ------------------------------------------------
1713   // * Inflated
1714   //    -- unlocked
1715   //    -- Locked
1716   //       = by self
1717   //       = by other
1718   // * biased
1719   //    -- by Self
1720   //    -- by other
1721   // * neutral
1722   // * stack-locked
1723   //    -- by self
1724   //       = sp-proximity test hits
1725   //       = sp-proximity test generates false-negative
1726   //    -- by other
1727   //
1728 
1729   Label IsInflated, DONE_LABEL;
1730 
1731   // it's stack-locked, biased or neutral
1732   // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1733   // order to reduce the number of conditional branches in the most common cases.
1734   // Beware -- there's a subtle invariant that fetch of the markword
1735   // at [FETCH], below, will never observe a biased encoding (*101b).
1736   // If this invariant is not held we risk exclusion (safety) failure.
1737   if (UseBiasedLocking && !UseOptoBiasInlining) {
1738     biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1739   }
1740 
1741 #if INCLUDE_RTM_OPT
1742   if (UseRTMForStackLocks && use_rtm) {
1743     rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1744                       stack_rtm_counters, method_data, profile_rtm,
1745                       DONE_LABEL, IsInflated);
1746   }
1747 #endif // INCLUDE_RTM_OPT
1748 
1749   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1750   testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1751   jccb(Assembler::notZero, IsInflated);
1752 
1753   // Attempt stack-locking ...
1754   orptr (tmpReg, markOopDesc::unlocked_value);
1755   movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1756   lock();
1757   cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1758   if (counters != NULL) {
1759     cond_inc32(Assembler::equal,
1760                ExternalAddress((address)counters->fast_path_entry_count_addr()));
1761   }
1762   jcc(Assembler::equal, DONE_LABEL);           // Success
1763 
1764   // Recursive locking.
1765   // The object is stack-locked: markword contains stack pointer to BasicLock.
1766   // Locked by current thread if difference with current SP is less than one page.
1767   subptr(tmpReg, rsp);
1768   // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1769   andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1770   movptr(Address(boxReg, 0), tmpReg);
1771   if (counters != NULL) {
1772     cond_inc32(Assembler::equal,
1773                ExternalAddress((address)counters->fast_path_entry_count_addr()));
1774   }
1775   jmp(DONE_LABEL);
1776 
1777   bind(IsInflated);
1778   // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1779 
1780 #if INCLUDE_RTM_OPT
1781   // Use the same RTM locking code in 32- and 64-bit VM.
1782   if (use_rtm) {
1783     rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1784                          rtm_counters, method_data, profile_rtm, DONE_LABEL);
1785   } else {
1786 #endif // INCLUDE_RTM_OPT
1787 
1788 #ifndef _LP64
1789   // The object is inflated.
1790 
1791   // boxReg refers to the on-stack BasicLock in the current frame.
1792   // We'd like to write:
1793   //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1794   // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1795   // additional latency as we have another ST in the store buffer that must drain.
1796 
1797   // avoid ST-before-CAS
1798   // register juggle because we need tmpReg for cmpxchgptr below
1799   movptr(scrReg, boxReg);
1800   movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1801 
1802   // Optimistic form: consider XORL tmpReg,tmpReg
1803   movptr(tmpReg, NULL_WORD);
1804 
1805   // Appears unlocked - try to swing _owner from null to non-null.
1806   // Ideally, I'd manifest "Self" with get_thread and then attempt
1807   // to CAS the register containing Self into m->Owner.
1808   // But we don't have enough registers, so instead we can either try to CAS
1809   // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1810   // we later store "Self" into m->Owner.  Transiently storing a stack address
1811   // (rsp or the address of the box) into  m->owner is harmless.
1812   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1813   lock();
1814   cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1815   movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1816   // If we weren't able to swing _owner from NULL to the BasicLock
1817   // then take the slow path.
1818   jccb  (Assembler::notZero, DONE_LABEL);
1819   // update _owner from BasicLock to thread
1820   get_thread (scrReg);                    // beware: clobbers ICCs
1821   movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1822   xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1823 
1824   // If the CAS fails we can either retry or pass control to the slow-path.
1825   // We use the latter tactic.
1826   // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1827   // If the CAS was successful ...
1828   //   Self has acquired the lock
1829   //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1830   // Intentional fall-through into DONE_LABEL ...
1831 #else // _LP64
1832   // It's inflated
1833   movq(scrReg, tmpReg);
1834   xorq(tmpReg, tmpReg);
1835 
1836   lock();
1837   cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1838   // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1839   // Without cast to int32_t movptr will destroy r10 which is typically obj.
1840   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1841   // Intentional fall-through into DONE_LABEL ...
1842   // Propagate ICC.ZF from CAS above into DONE_LABEL.
1843 #endif // _LP64
1844 #if INCLUDE_RTM_OPT
1845   } // use_rtm()
1846 #endif
1847   // DONE_LABEL is a hot target - we'd really like to place it at the
1848   // start of cache line by padding with NOPs.
1849   // See the AMD and Intel software optimization manuals for the
1850   // most efficient "long" NOP encodings.
1851   // Unfortunately none of our alignment mechanisms suffice.
1852   bind(DONE_LABEL);
1853 
1854   // At DONE_LABEL the icc ZFlag is set as follows ...
1855   // Fast_Unlock uses the same protocol.
1856   // ZFlag == 1 -> Success
1857   // ZFlag == 0 -> Failure - force control through the slow-path
1858 }
1859 
1860 // obj: object to unlock
1861 // box: box address (displaced header location), killed.  Must be EAX.
1862 // tmp: killed, cannot be obj nor box.
1863 //
1864 // Some commentary on balanced locking:
1865 //
1866 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1867 // Methods that don't have provably balanced locking are forced to run in the
1868 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1869 // The interpreter provides two properties:
1870 // I1:  At return-time the interpreter automatically and quietly unlocks any
1871 //      objects acquired the current activation (frame).  Recall that the
1872 //      interpreter maintains an on-stack list of locks currently held by
1873 //      a frame.
1874 // I2:  If a method attempts to unlock an object that is not held by the
1875 //      the frame the interpreter throws IMSX.
1876 //
1877 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1878 // B() doesn't have provably balanced locking so it runs in the interpreter.
1879 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1880 // is still locked by A().
1881 //
1882 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1883 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1884 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1885 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1886 // Arguably given that the spec legislates the JNI case as undefined our implementation
1887 // could reasonably *avoid* checking owner in Fast_Unlock().
1888 // In the interest of performance we elide m->Owner==Self check in unlock.
1889 // A perfectly viable alternative is to elide the owner check except when
1890 // Xcheck:jni is enabled.
1891 
1892 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1893   assert(boxReg == rax, "");
1894   assert_different_registers(objReg, boxReg, tmpReg);
1895 
1896   Label DONE_LABEL, Stacked, CheckSucc;
1897 
1898   // Critically, the biased locking test must have precedence over
1899   // and appear before the (box->dhw == 0) recursive stack-lock test.
1900   if (UseBiasedLocking && !UseOptoBiasInlining) {
1901     biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1902   }
1903 
1904 #if INCLUDE_RTM_OPT
1905   if (UseRTMForStackLocks && use_rtm) {
1906     assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1907     Label L_regular_unlock;
1908     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
1909     andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1910     cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1911     jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1912     xend();                                       // otherwise end...
1913     jmp(DONE_LABEL);                              // ... and we're done
1914     bind(L_regular_unlock);
1915   }
1916 #endif
1917 
1918   cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
1919   jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
1920   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
1921   testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
1922   jccb  (Assembler::zero, Stacked);
1923 
1924   // It's inflated.
1925 #if INCLUDE_RTM_OPT
1926   if (use_rtm) {
1927     Label L_regular_inflated_unlock;
1928     int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1929     movptr(boxReg, Address(tmpReg, owner_offset));
1930     testptr(boxReg, boxReg);
1931     jccb(Assembler::notZero, L_regular_inflated_unlock);
1932     xend();
1933     jmpb(DONE_LABEL);
1934     bind(L_regular_inflated_unlock);
1935   }
1936 #endif
1937 
1938   // Despite our balanced locking property we still check that m->_owner == Self
1939   // as java routines or native JNI code called by this thread might
1940   // have released the lock.
1941   // Refer to the comments in synchronizer.cpp for how we might encode extra
1942   // state in _succ so we can avoid fetching EntryList|cxq.
1943   //
1944   // I'd like to add more cases in fast_lock() and fast_unlock() --
1945   // such as recursive enter and exit -- but we have to be wary of
1946   // I$ bloat, T$ effects and BP$ effects.
1947   //
1948   // If there's no contention try a 1-0 exit.  That is, exit without
1949   // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
1950   // we detect and recover from the race that the 1-0 exit admits.
1951   //
1952   // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
1953   // before it STs null into _owner, releasing the lock.  Updates
1954   // to data protected by the critical section must be visible before
1955   // we drop the lock (and thus before any other thread could acquire
1956   // the lock and observe the fields protected by the lock).
1957   // IA32's memory-model is SPO, so STs are ordered with respect to
1958   // each other and there's no need for an explicit barrier (fence).
1959   // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
1960 #ifndef _LP64
1961   get_thread (boxReg);
1962 
1963   // Note that we could employ various encoding schemes to reduce
1964   // the number of loads below (currently 4) to just 2 or 3.
1965   // Refer to the comments in synchronizer.cpp.
1966   // In practice the chain of fetches doesn't seem to impact performance, however.
1967   xorptr(boxReg, boxReg);
1968   orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
1969   jccb  (Assembler::notZero, DONE_LABEL);
1970   movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
1971   orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
1972   jccb  (Assembler::notZero, CheckSucc);
1973   movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
1974   jmpb  (DONE_LABEL);
1975 
1976   bind (Stacked);
1977   // It's not inflated and it's not recursively stack-locked and it's not biased.
1978   // It must be stack-locked.
1979   // Try to reset the header to displaced header.
1980   // The "box" value on the stack is stable, so we can reload
1981   // and be assured we observe the same value as above.
1982   movptr(tmpReg, Address(boxReg, 0));
1983   lock();
1984   cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
1985   // Intention fall-thru into DONE_LABEL
1986 
1987   // DONE_LABEL is a hot target - we'd really like to place it at the
1988   // start of cache line by padding with NOPs.
1989   // See the AMD and Intel software optimization manuals for the
1990   // most efficient "long" NOP encodings.
1991   // Unfortunately none of our alignment mechanisms suffice.
1992   bind (CheckSucc);
1993 #else // _LP64
1994   // It's inflated
1995   xorptr(boxReg, boxReg);
1996   orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
1997   jccb  (Assembler::notZero, DONE_LABEL);
1998   movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
1999   orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2000   jccb  (Assembler::notZero, CheckSucc);
2001   movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2002   jmpb  (DONE_LABEL);
2003 
2004   // Try to avoid passing control into the slow_path ...
2005   Label LSuccess, LGoSlowPath ;
2006   bind  (CheckSucc);
2007 
2008   // The following optional optimization can be elided if necessary
2009   // Effectively: if (succ == null) goto SlowPath
2010   // The code reduces the window for a race, however,
2011   // and thus benefits performance.
2012   cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2013   jccb  (Assembler::zero, LGoSlowPath);
2014 
2015   xorptr(boxReg, boxReg);
2016   movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2017 
2018   // Memory barrier/fence
2019   // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2020   // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2021   // This is faster on Nehalem and AMD Shanghai/Barcelona.
2022   // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2023   // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2024   // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2025   lock(); addl(Address(rsp, 0), 0);
2026 
2027   cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2028   jccb  (Assembler::notZero, LSuccess);
2029 
2030   // Rare inopportune interleaving - race.
2031   // The successor vanished in the small window above.
2032   // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2033   // We need to ensure progress and succession.
2034   // Try to reacquire the lock.
2035   // If that fails then the new owner is responsible for succession and this
2036   // thread needs to take no further action and can exit via the fast path (success).
2037   // If the re-acquire succeeds then pass control into the slow path.
2038   // As implemented, this latter mode is horrible because we generated more
2039   // coherence traffic on the lock *and* artifically extended the critical section
2040   // length while by virtue of passing control into the slow path.
2041 
2042   // box is really RAX -- the following CMPXCHG depends on that binding
2043   // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2044   lock();
2045   cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2046   // There's no successor so we tried to regrab the lock.
2047   // If that didn't work, then another thread grabbed the
2048   // lock so we're done (and exit was a success).
2049   jccb  (Assembler::notEqual, LSuccess);
2050   // Intentional fall-through into slow-path
2051 
2052   bind  (LGoSlowPath);
2053   orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2054   jmpb  (DONE_LABEL);
2055 
2056   bind  (LSuccess);
2057   testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2058   jmpb  (DONE_LABEL);
2059 
2060   bind  (Stacked);
2061   movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2062   lock();
2063   cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2064 
2065 #endif
2066   bind(DONE_LABEL);
2067 }
2068 #endif // COMPILER2
2069 
2070 void MacroAssembler::c2bool(Register x) {
2071   // implements x == 0 ? 0 : 1
2072   // note: must only look at least-significant byte of x
2073   //       since C-style booleans are stored in one byte
2074   //       only! (was bug)
2075   andl(x, 0xFF);
2076   setb(Assembler::notZero, x);
2077 }
2078 
2079 // Wouldn't need if AddressLiteral version had new name
2080 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2081   Assembler::call(L, rtype);
2082 }
2083 
2084 void MacroAssembler::call(Register entry) {
2085   Assembler::call(entry);
2086 }
2087 
2088 void MacroAssembler::call(AddressLiteral entry) {
2089   if (reachable(entry)) {
2090     Assembler::call_literal(entry.target(), entry.rspec());
2091   } else {
2092     lea(rscratch1, entry);
2093     Assembler::call(rscratch1);
2094   }
2095 }
2096 
2097 void MacroAssembler::ic_call(address entry, jint method_index) {
2098   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2099   movptr(rax, (intptr_t)Universe::non_oop_word());
2100   call(AddressLiteral(entry, rh));
2101 }
2102 
2103 // Implementation of call_VM versions
2104 
2105 void MacroAssembler::call_VM(Register oop_result,
2106                              address entry_point,
2107                              bool check_exceptions) {
2108   Label C, E;
2109   call(C, relocInfo::none);
2110   jmp(E);
2111 
2112   bind(C);
2113   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2114   ret(0);
2115 
2116   bind(E);
2117 }
2118 
2119 void MacroAssembler::call_VM(Register oop_result,
2120                              address entry_point,
2121                              Register arg_1,
2122                              bool check_exceptions) {
2123   Label C, E;
2124   call(C, relocInfo::none);
2125   jmp(E);
2126 
2127   bind(C);
2128   pass_arg1(this, arg_1);
2129   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2130   ret(0);
2131 
2132   bind(E);
2133 }
2134 
2135 void MacroAssembler::call_VM(Register oop_result,
2136                              address entry_point,
2137                              Register arg_1,
2138                              Register arg_2,
2139                              bool check_exceptions) {
2140   Label C, E;
2141   call(C, relocInfo::none);
2142   jmp(E);
2143 
2144   bind(C);
2145 
2146   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2147 
2148   pass_arg2(this, arg_2);
2149   pass_arg1(this, arg_1);
2150   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2151   ret(0);
2152 
2153   bind(E);
2154 }
2155 
2156 void MacroAssembler::call_VM(Register oop_result,
2157                              address entry_point,
2158                              Register arg_1,
2159                              Register arg_2,
2160                              Register arg_3,
2161                              bool check_exceptions) {
2162   Label C, E;
2163   call(C, relocInfo::none);
2164   jmp(E);
2165 
2166   bind(C);
2167 
2168   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2169   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2170   pass_arg3(this, arg_3);
2171 
2172   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2173   pass_arg2(this, arg_2);
2174 
2175   pass_arg1(this, arg_1);
2176   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2177   ret(0);
2178 
2179   bind(E);
2180 }
2181 
2182 void MacroAssembler::call_VM(Register oop_result,
2183                              Register last_java_sp,
2184                              address entry_point,
2185                              int number_of_arguments,
2186                              bool check_exceptions) {
2187   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2188   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2189 }
2190 
2191 void MacroAssembler::call_VM(Register oop_result,
2192                              Register last_java_sp,
2193                              address entry_point,
2194                              Register arg_1,
2195                              bool check_exceptions) {
2196   pass_arg1(this, arg_1);
2197   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2198 }
2199 
2200 void MacroAssembler::call_VM(Register oop_result,
2201                              Register last_java_sp,
2202                              address entry_point,
2203                              Register arg_1,
2204                              Register arg_2,
2205                              bool check_exceptions) {
2206 
2207   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2208   pass_arg2(this, arg_2);
2209   pass_arg1(this, arg_1);
2210   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2211 }
2212 
2213 void MacroAssembler::call_VM(Register oop_result,
2214                              Register last_java_sp,
2215                              address entry_point,
2216                              Register arg_1,
2217                              Register arg_2,
2218                              Register arg_3,
2219                              bool check_exceptions) {
2220   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2221   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2222   pass_arg3(this, arg_3);
2223   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2224   pass_arg2(this, arg_2);
2225   pass_arg1(this, arg_1);
2226   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2227 }
2228 
2229 void MacroAssembler::super_call_VM(Register oop_result,
2230                                    Register last_java_sp,
2231                                    address entry_point,
2232                                    int number_of_arguments,
2233                                    bool check_exceptions) {
2234   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2235   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2236 }
2237 
2238 void MacroAssembler::super_call_VM(Register oop_result,
2239                                    Register last_java_sp,
2240                                    address entry_point,
2241                                    Register arg_1,
2242                                    bool check_exceptions) {
2243   pass_arg1(this, arg_1);
2244   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2245 }
2246 
2247 void MacroAssembler::super_call_VM(Register oop_result,
2248                                    Register last_java_sp,
2249                                    address entry_point,
2250                                    Register arg_1,
2251                                    Register arg_2,
2252                                    bool check_exceptions) {
2253 
2254   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2255   pass_arg2(this, arg_2);
2256   pass_arg1(this, arg_1);
2257   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2258 }
2259 
2260 void MacroAssembler::super_call_VM(Register oop_result,
2261                                    Register last_java_sp,
2262                                    address entry_point,
2263                                    Register arg_1,
2264                                    Register arg_2,
2265                                    Register arg_3,
2266                                    bool check_exceptions) {
2267   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2268   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2269   pass_arg3(this, arg_3);
2270   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2271   pass_arg2(this, arg_2);
2272   pass_arg1(this, arg_1);
2273   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2274 }
2275 
2276 void MacroAssembler::call_VM_base(Register oop_result,
2277                                   Register java_thread,
2278                                   Register last_java_sp,
2279                                   address  entry_point,
2280                                   int      number_of_arguments,
2281                                   bool     check_exceptions) {
2282   // determine java_thread register
2283   if (!java_thread->is_valid()) {
2284 #ifdef _LP64
2285     java_thread = r15_thread;
2286 #else
2287     java_thread = rdi;
2288     get_thread(java_thread);
2289 #endif // LP64
2290   }
2291   // determine last_java_sp register
2292   if (!last_java_sp->is_valid()) {
2293     last_java_sp = rsp;
2294   }
2295   // debugging support
2296   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2297   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2298 #ifdef ASSERT
2299   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2300   // r12 is the heapbase.
2301   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2302 #endif // ASSERT
2303 
2304   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2305   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2306 
2307   // push java thread (becomes first argument of C function)
2308 
2309   NOT_LP64(push(java_thread); number_of_arguments++);
2310   LP64_ONLY(mov(c_rarg0, r15_thread));
2311 
2312   // set last Java frame before call
2313   assert(last_java_sp != rbp, "can't use ebp/rbp");
2314 
2315   // Only interpreter should have to set fp
2316   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2317 
2318   // do the call, remove parameters
2319   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2320 
2321   // restore the thread (cannot use the pushed argument since arguments
2322   // may be overwritten by C code generated by an optimizing compiler);
2323   // however can use the register value directly if it is callee saved.
2324   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2325     // rdi & rsi (also r15) are callee saved -> nothing to do
2326 #ifdef ASSERT
2327     guarantee(java_thread != rax, "change this code");
2328     push(rax);
2329     { Label L;
2330       get_thread(rax);
2331       cmpptr(java_thread, rax);
2332       jcc(Assembler::equal, L);
2333       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2334       bind(L);
2335     }
2336     pop(rax);
2337 #endif
2338   } else {
2339     get_thread(java_thread);
2340   }
2341   // reset last Java frame
2342   // Only interpreter should have to clear fp
2343   reset_last_Java_frame(java_thread, true);
2344 
2345    // C++ interp handles this in the interpreter
2346   check_and_handle_popframe(java_thread);
2347   check_and_handle_earlyret(java_thread);
2348 
2349   if (check_exceptions) {
2350     // check for pending exceptions (java_thread is set upon return)
2351     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2352 #ifndef _LP64
2353     jump_cc(Assembler::notEqual,
2354             RuntimeAddress(StubRoutines::forward_exception_entry()));
2355 #else
2356     // This used to conditionally jump to forward_exception however it is
2357     // possible if we relocate that the branch will not reach. So we must jump
2358     // around so we can always reach
2359 
2360     Label ok;
2361     jcc(Assembler::equal, ok);
2362     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2363     bind(ok);
2364 #endif // LP64
2365   }
2366 
2367   // get oop result if there is one and reset the value in the thread
2368   if (oop_result->is_valid()) {
2369     get_vm_result(oop_result, java_thread);
2370   }
2371 }
2372 
2373 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2374 
2375   // Calculate the value for last_Java_sp
2376   // somewhat subtle. call_VM does an intermediate call
2377   // which places a return address on the stack just under the
2378   // stack pointer as the user finsihed with it. This allows
2379   // use to retrieve last_Java_pc from last_Java_sp[-1].
2380   // On 32bit we then have to push additional args on the stack to accomplish
2381   // the actual requested call. On 64bit call_VM only can use register args
2382   // so the only extra space is the return address that call_VM created.
2383   // This hopefully explains the calculations here.
2384 
2385 #ifdef _LP64
2386   // We've pushed one address, correct last_Java_sp
2387   lea(rax, Address(rsp, wordSize));
2388 #else
2389   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2390 #endif // LP64
2391 
2392   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2393 
2394 }
2395 
2396 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2397 void MacroAssembler::call_VM_leaf0(address entry_point) {
2398   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2399 }
2400 
2401 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2402   call_VM_leaf_base(entry_point, number_of_arguments);
2403 }
2404 
2405 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2406   pass_arg0(this, arg_0);
2407   call_VM_leaf(entry_point, 1);
2408 }
2409 
2410 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2411 
2412   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2413   pass_arg1(this, arg_1);
2414   pass_arg0(this, arg_0);
2415   call_VM_leaf(entry_point, 2);
2416 }
2417 
2418 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2419   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2420   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2421   pass_arg2(this, arg_2);
2422   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2423   pass_arg1(this, arg_1);
2424   pass_arg0(this, arg_0);
2425   call_VM_leaf(entry_point, 3);
2426 }
2427 
2428 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2429   pass_arg0(this, arg_0);
2430   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2431 }
2432 
2433 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2434 
2435   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2436   pass_arg1(this, arg_1);
2437   pass_arg0(this, arg_0);
2438   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2439 }
2440 
2441 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2442   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2443   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2444   pass_arg2(this, arg_2);
2445   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2446   pass_arg1(this, arg_1);
2447   pass_arg0(this, arg_0);
2448   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2449 }
2450 
2451 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2452   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2453   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2454   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2455   pass_arg3(this, arg_3);
2456   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2457   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2458   pass_arg2(this, arg_2);
2459   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2460   pass_arg1(this, arg_1);
2461   pass_arg0(this, arg_0);
2462   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2463 }
2464 
2465 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2466   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2467   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2468   verify_oop(oop_result, "broken oop in call_VM_base");
2469 }
2470 
2471 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2472   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2473   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2474 }
2475 
2476 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2477 }
2478 
2479 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2480 }
2481 
2482 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2483   if (reachable(src1)) {
2484     cmpl(as_Address(src1), imm);
2485   } else {
2486     lea(rscratch1, src1);
2487     cmpl(Address(rscratch1, 0), imm);
2488   }
2489 }
2490 
2491 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2492   assert(!src2.is_lval(), "use cmpptr");
2493   if (reachable(src2)) {
2494     cmpl(src1, as_Address(src2));
2495   } else {
2496     lea(rscratch1, src2);
2497     cmpl(src1, Address(rscratch1, 0));
2498   }
2499 }
2500 
2501 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2502   Assembler::cmpl(src1, imm);
2503 }
2504 
2505 void MacroAssembler::cmp32(Register src1, Address src2) {
2506   Assembler::cmpl(src1, src2);
2507 }
2508 
2509 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2510   ucomisd(opr1, opr2);
2511 
2512   Label L;
2513   if (unordered_is_less) {
2514     movl(dst, -1);
2515     jcc(Assembler::parity, L);
2516     jcc(Assembler::below , L);
2517     movl(dst, 0);
2518     jcc(Assembler::equal , L);
2519     increment(dst);
2520   } else { // unordered is greater
2521     movl(dst, 1);
2522     jcc(Assembler::parity, L);
2523     jcc(Assembler::above , L);
2524     movl(dst, 0);
2525     jcc(Assembler::equal , L);
2526     decrementl(dst);
2527   }
2528   bind(L);
2529 }
2530 
2531 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2532   ucomiss(opr1, opr2);
2533 
2534   Label L;
2535   if (unordered_is_less) {
2536     movl(dst, -1);
2537     jcc(Assembler::parity, L);
2538     jcc(Assembler::below , L);
2539     movl(dst, 0);
2540     jcc(Assembler::equal , L);
2541     increment(dst);
2542   } else { // unordered is greater
2543     movl(dst, 1);
2544     jcc(Assembler::parity, L);
2545     jcc(Assembler::above , L);
2546     movl(dst, 0);
2547     jcc(Assembler::equal , L);
2548     decrementl(dst);
2549   }
2550   bind(L);
2551 }
2552 
2553 
2554 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2555   if (reachable(src1)) {
2556     cmpb(as_Address(src1), imm);
2557   } else {
2558     lea(rscratch1, src1);
2559     cmpb(Address(rscratch1, 0), imm);
2560   }
2561 }
2562 
2563 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2564 #ifdef _LP64
2565   if (src2.is_lval()) {
2566     movptr(rscratch1, src2);
2567     Assembler::cmpq(src1, rscratch1);
2568   } else if (reachable(src2)) {
2569     cmpq(src1, as_Address(src2));
2570   } else {
2571     lea(rscratch1, src2);
2572     Assembler::cmpq(src1, Address(rscratch1, 0));
2573   }
2574 #else
2575   if (src2.is_lval()) {
2576     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2577   } else {
2578     cmpl(src1, as_Address(src2));
2579   }
2580 #endif // _LP64
2581 }
2582 
2583 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2584   assert(src2.is_lval(), "not a mem-mem compare");
2585 #ifdef _LP64
2586   // moves src2's literal address
2587   movptr(rscratch1, src2);
2588   Assembler::cmpq(src1, rscratch1);
2589 #else
2590   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2591 #endif // _LP64
2592 }
2593 
2594 void MacroAssembler::cmpoop(Register src1, Register src2) {
2595   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
2596   bs->obj_equals(this, src1, src2);
2597 }
2598 
2599 void MacroAssembler::cmpoop(Register src1, Address src2) {
2600   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
2601   bs->obj_equals(this, src1, src2);
2602 }
2603 
2604 #ifdef _LP64
2605 void MacroAssembler::cmpoop(Register src1, jobject src2) {
2606   movoop(rscratch1, src2);
2607   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
2608   bs->obj_equals(this, src1, rscratch1);
2609 }
2610 #endif
2611 
2612 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2613   if (reachable(adr)) {
2614     lock();
2615     cmpxchgptr(reg, as_Address(adr));
2616   } else {
2617     lea(rscratch1, adr);
2618     lock();
2619     cmpxchgptr(reg, Address(rscratch1, 0));
2620   }
2621 }
2622 
2623 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2624   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2625 }
2626 
2627 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2628   if (reachable(src)) {
2629     Assembler::comisd(dst, as_Address(src));
2630   } else {
2631     lea(rscratch1, src);
2632     Assembler::comisd(dst, Address(rscratch1, 0));
2633   }
2634 }
2635 
2636 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2637   if (reachable(src)) {
2638     Assembler::comiss(dst, as_Address(src));
2639   } else {
2640     lea(rscratch1, src);
2641     Assembler::comiss(dst, Address(rscratch1, 0));
2642   }
2643 }
2644 
2645 
2646 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2647   Condition negated_cond = negate_condition(cond);
2648   Label L;
2649   jcc(negated_cond, L);
2650   pushf(); // Preserve flags
2651   atomic_incl(counter_addr);
2652   popf();
2653   bind(L);
2654 }
2655 
2656 int MacroAssembler::corrected_idivl(Register reg) {
2657   // Full implementation of Java idiv and irem; checks for
2658   // special case as described in JVM spec., p.243 & p.271.
2659   // The function returns the (pc) offset of the idivl
2660   // instruction - may be needed for implicit exceptions.
2661   //
2662   //         normal case                           special case
2663   //
2664   // input : rax,: dividend                         min_int
2665   //         reg: divisor   (may not be rax,/rdx)   -1
2666   //
2667   // output: rax,: quotient  (= rax, idiv reg)       min_int
2668   //         rdx: remainder (= rax, irem reg)       0
2669   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2670   const int min_int = 0x80000000;
2671   Label normal_case, special_case;
2672 
2673   // check for special case
2674   cmpl(rax, min_int);
2675   jcc(Assembler::notEqual, normal_case);
2676   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2677   cmpl(reg, -1);
2678   jcc(Assembler::equal, special_case);
2679 
2680   // handle normal case
2681   bind(normal_case);
2682   cdql();
2683   int idivl_offset = offset();
2684   idivl(reg);
2685 
2686   // normal and special case exit
2687   bind(special_case);
2688 
2689   return idivl_offset;
2690 }
2691 
2692 
2693 
2694 void MacroAssembler::decrementl(Register reg, int value) {
2695   if (value == min_jint) {subl(reg, value) ; return; }
2696   if (value <  0) { incrementl(reg, -value); return; }
2697   if (value == 0) {                        ; return; }
2698   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2699   /* else */      { subl(reg, value)       ; return; }
2700 }
2701 
2702 void MacroAssembler::decrementl(Address dst, int value) {
2703   if (value == min_jint) {subl(dst, value) ; return; }
2704   if (value <  0) { incrementl(dst, -value); return; }
2705   if (value == 0) {                        ; return; }
2706   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2707   /* else */      { subl(dst, value)       ; return; }
2708 }
2709 
2710 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2711   assert (shift_value > 0, "illegal shift value");
2712   Label _is_positive;
2713   testl (reg, reg);
2714   jcc (Assembler::positive, _is_positive);
2715   int offset = (1 << shift_value) - 1 ;
2716 
2717   if (offset == 1) {
2718     incrementl(reg);
2719   } else {
2720     addl(reg, offset);
2721   }
2722 
2723   bind (_is_positive);
2724   sarl(reg, shift_value);
2725 }
2726 
2727 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2728   if (reachable(src)) {
2729     Assembler::divsd(dst, as_Address(src));
2730   } else {
2731     lea(rscratch1, src);
2732     Assembler::divsd(dst, Address(rscratch1, 0));
2733   }
2734 }
2735 
2736 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2737   if (reachable(src)) {
2738     Assembler::divss(dst, as_Address(src));
2739   } else {
2740     lea(rscratch1, src);
2741     Assembler::divss(dst, Address(rscratch1, 0));
2742   }
2743 }
2744 
2745 // !defined(COMPILER2) is because of stupid core builds
2746 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2747 void MacroAssembler::empty_FPU_stack() {
2748   if (VM_Version::supports_mmx()) {
2749     emms();
2750   } else {
2751     for (int i = 8; i-- > 0; ) ffree(i);
2752   }
2753 }
2754 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2755 
2756 
2757 void MacroAssembler::enter() {
2758   push(rbp);
2759   mov(rbp, rsp);
2760 }
2761 
2762 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2763 void MacroAssembler::fat_nop() {
2764   if (UseAddressNop) {
2765     addr_nop_5();
2766   } else {
2767     emit_int8(0x26); // es:
2768     emit_int8(0x2e); // cs:
2769     emit_int8(0x64); // fs:
2770     emit_int8(0x65); // gs:
2771     emit_int8((unsigned char)0x90);
2772   }
2773 }
2774 
2775 void MacroAssembler::fcmp(Register tmp) {
2776   fcmp(tmp, 1, true, true);
2777 }
2778 
2779 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2780   assert(!pop_right || pop_left, "usage error");
2781   if (VM_Version::supports_cmov()) {
2782     assert(tmp == noreg, "unneeded temp");
2783     if (pop_left) {
2784       fucomip(index);
2785     } else {
2786       fucomi(index);
2787     }
2788     if (pop_right) {
2789       fpop();
2790     }
2791   } else {
2792     assert(tmp != noreg, "need temp");
2793     if (pop_left) {
2794       if (pop_right) {
2795         fcompp();
2796       } else {
2797         fcomp(index);
2798       }
2799     } else {
2800       fcom(index);
2801     }
2802     // convert FPU condition into eflags condition via rax,
2803     save_rax(tmp);
2804     fwait(); fnstsw_ax();
2805     sahf();
2806     restore_rax(tmp);
2807   }
2808   // condition codes set as follows:
2809   //
2810   // CF (corresponds to C0) if x < y
2811   // PF (corresponds to C2) if unordered
2812   // ZF (corresponds to C3) if x = y
2813 }
2814 
2815 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
2816   fcmp2int(dst, unordered_is_less, 1, true, true);
2817 }
2818 
2819 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
2820   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
2821   Label L;
2822   if (unordered_is_less) {
2823     movl(dst, -1);
2824     jcc(Assembler::parity, L);
2825     jcc(Assembler::below , L);
2826     movl(dst, 0);
2827     jcc(Assembler::equal , L);
2828     increment(dst);
2829   } else { // unordered is greater
2830     movl(dst, 1);
2831     jcc(Assembler::parity, L);
2832     jcc(Assembler::above , L);
2833     movl(dst, 0);
2834     jcc(Assembler::equal , L);
2835     decrementl(dst);
2836   }
2837   bind(L);
2838 }
2839 
2840 void MacroAssembler::fld_d(AddressLiteral src) {
2841   fld_d(as_Address(src));
2842 }
2843 
2844 void MacroAssembler::fld_s(AddressLiteral src) {
2845   fld_s(as_Address(src));
2846 }
2847 
2848 void MacroAssembler::fld_x(AddressLiteral src) {
2849   Assembler::fld_x(as_Address(src));
2850 }
2851 
2852 void MacroAssembler::fldcw(AddressLiteral src) {
2853   Assembler::fldcw(as_Address(src));
2854 }
2855 
2856 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
2857   if (reachable(src)) {
2858     Assembler::mulpd(dst, as_Address(src));
2859   } else {
2860     lea(rscratch1, src);
2861     Assembler::mulpd(dst, Address(rscratch1, 0));
2862   }
2863 }
2864 
2865 void MacroAssembler::increase_precision() {
2866   subptr(rsp, BytesPerWord);
2867   fnstcw(Address(rsp, 0));
2868   movl(rax, Address(rsp, 0));
2869   orl(rax, 0x300);
2870   push(rax);
2871   fldcw(Address(rsp, 0));
2872   pop(rax);
2873 }
2874 
2875 void MacroAssembler::restore_precision() {
2876   fldcw(Address(rsp, 0));
2877   addptr(rsp, BytesPerWord);
2878 }
2879 
2880 void MacroAssembler::fpop() {
2881   ffree();
2882   fincstp();
2883 }
2884 
2885 void MacroAssembler::load_float(Address src) {
2886   if (UseSSE >= 1) {
2887     movflt(xmm0, src);
2888   } else {
2889     LP64_ONLY(ShouldNotReachHere());
2890     NOT_LP64(fld_s(src));
2891   }
2892 }
2893 
2894 void MacroAssembler::store_float(Address dst) {
2895   if (UseSSE >= 1) {
2896     movflt(dst, xmm0);
2897   } else {
2898     LP64_ONLY(ShouldNotReachHere());
2899     NOT_LP64(fstp_s(dst));
2900   }
2901 }
2902 
2903 void MacroAssembler::load_double(Address src) {
2904   if (UseSSE >= 2) {
2905     movdbl(xmm0, src);
2906   } else {
2907     LP64_ONLY(ShouldNotReachHere());
2908     NOT_LP64(fld_d(src));
2909   }
2910 }
2911 
2912 void MacroAssembler::store_double(Address dst) {
2913   if (UseSSE >= 2) {
2914     movdbl(dst, xmm0);
2915   } else {
2916     LP64_ONLY(ShouldNotReachHere());
2917     NOT_LP64(fstp_d(dst));
2918   }
2919 }
2920 
2921 void MacroAssembler::fremr(Register tmp) {
2922   save_rax(tmp);
2923   { Label L;
2924     bind(L);
2925     fprem();
2926     fwait(); fnstsw_ax();
2927 #ifdef _LP64
2928     testl(rax, 0x400);
2929     jcc(Assembler::notEqual, L);
2930 #else
2931     sahf();
2932     jcc(Assembler::parity, L);
2933 #endif // _LP64
2934   }
2935   restore_rax(tmp);
2936   // Result is in ST0.
2937   // Note: fxch & fpop to get rid of ST1
2938   // (otherwise FPU stack could overflow eventually)
2939   fxch(1);
2940   fpop();
2941 }
2942 
2943 // dst = c = a * b + c
2944 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
2945   Assembler::vfmadd231sd(c, a, b);
2946   if (dst != c) {
2947     movdbl(dst, c);
2948   }
2949 }
2950 
2951 // dst = c = a * b + c
2952 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
2953   Assembler::vfmadd231ss(c, a, b);
2954   if (dst != c) {
2955     movflt(dst, c);
2956   }
2957 }
2958 
2959 // dst = c = a * b + c
2960 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
2961   Assembler::vfmadd231pd(c, a, b, vector_len);
2962   if (dst != c) {
2963     vmovdqu(dst, c);
2964   }
2965 }
2966 
2967 // dst = c = a * b + c
2968 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
2969   Assembler::vfmadd231ps(c, a, b, vector_len);
2970   if (dst != c) {
2971     vmovdqu(dst, c);
2972   }
2973 }
2974 
2975 // dst = c = a * b + c
2976 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
2977   Assembler::vfmadd231pd(c, a, b, vector_len);
2978   if (dst != c) {
2979     vmovdqu(dst, c);
2980   }
2981 }
2982 
2983 // dst = c = a * b + c
2984 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
2985   Assembler::vfmadd231ps(c, a, b, vector_len);
2986   if (dst != c) {
2987     vmovdqu(dst, c);
2988   }
2989 }
2990 
2991 void MacroAssembler::incrementl(AddressLiteral dst) {
2992   if (reachable(dst)) {
2993     incrementl(as_Address(dst));
2994   } else {
2995     lea(rscratch1, dst);
2996     incrementl(Address(rscratch1, 0));
2997   }
2998 }
2999 
3000 void MacroAssembler::incrementl(ArrayAddress dst) {
3001   incrementl(as_Address(dst));
3002 }
3003 
3004 void MacroAssembler::incrementl(Register reg, int value) {
3005   if (value == min_jint) {addl(reg, value) ; return; }
3006   if (value <  0) { decrementl(reg, -value); return; }
3007   if (value == 0) {                        ; return; }
3008   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3009   /* else */      { addl(reg, value)       ; return; }
3010 }
3011 
3012 void MacroAssembler::incrementl(Address dst, int value) {
3013   if (value == min_jint) {addl(dst, value) ; return; }
3014   if (value <  0) { decrementl(dst, -value); return; }
3015   if (value == 0) {                        ; return; }
3016   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3017   /* else */      { addl(dst, value)       ; return; }
3018 }
3019 
3020 void MacroAssembler::jump(AddressLiteral dst) {
3021   if (reachable(dst)) {
3022     jmp_literal(dst.target(), dst.rspec());
3023   } else {
3024     lea(rscratch1, dst);
3025     jmp(rscratch1);
3026   }
3027 }
3028 
3029 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3030   if (reachable(dst)) {
3031     InstructionMark im(this);
3032     relocate(dst.reloc());
3033     const int short_size = 2;
3034     const int long_size = 6;
3035     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3036     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3037       // 0111 tttn #8-bit disp
3038       emit_int8(0x70 | cc);
3039       emit_int8((offs - short_size) & 0xFF);
3040     } else {
3041       // 0000 1111 1000 tttn #32-bit disp
3042       emit_int8(0x0F);
3043       emit_int8((unsigned char)(0x80 | cc));
3044       emit_int32(offs - long_size);
3045     }
3046   } else {
3047 #ifdef ASSERT
3048     warning("reversing conditional branch");
3049 #endif /* ASSERT */
3050     Label skip;
3051     jccb(reverse[cc], skip);
3052     lea(rscratch1, dst);
3053     Assembler::jmp(rscratch1);
3054     bind(skip);
3055   }
3056 }
3057 
3058 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3059   if (reachable(src)) {
3060     Assembler::ldmxcsr(as_Address(src));
3061   } else {
3062     lea(rscratch1, src);
3063     Assembler::ldmxcsr(Address(rscratch1, 0));
3064   }
3065 }
3066 
3067 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3068   int off;
3069   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3070     off = offset();
3071     movsbl(dst, src); // movsxb
3072   } else {
3073     off = load_unsigned_byte(dst, src);
3074     shll(dst, 24);
3075     sarl(dst, 24);
3076   }
3077   return off;
3078 }
3079 
3080 // Note: load_signed_short used to be called load_signed_word.
3081 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3082 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3083 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3084 int MacroAssembler::load_signed_short(Register dst, Address src) {
3085   int off;
3086   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3087     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3088     // version but this is what 64bit has always done. This seems to imply
3089     // that users are only using 32bits worth.
3090     off = offset();
3091     movswl(dst, src); // movsxw
3092   } else {
3093     off = load_unsigned_short(dst, src);
3094     shll(dst, 16);
3095     sarl(dst, 16);
3096   }
3097   return off;
3098 }
3099 
3100 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3101   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3102   // and "3.9 Partial Register Penalties", p. 22).
3103   int off;
3104   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3105     off = offset();
3106     movzbl(dst, src); // movzxb
3107   } else {
3108     xorl(dst, dst);
3109     off = offset();
3110     movb(dst, src);
3111   }
3112   return off;
3113 }
3114 
3115 // Note: load_unsigned_short used to be called load_unsigned_word.
3116 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3117   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3118   // and "3.9 Partial Register Penalties", p. 22).
3119   int off;
3120   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3121     off = offset();
3122     movzwl(dst, src); // movzxw
3123   } else {
3124     xorl(dst, dst);
3125     off = offset();
3126     movw(dst, src);
3127   }
3128   return off;
3129 }
3130 
3131 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3132   switch (size_in_bytes) {
3133 #ifndef _LP64
3134   case  8:
3135     assert(dst2 != noreg, "second dest register required");
3136     movl(dst,  src);
3137     movl(dst2, src.plus_disp(BytesPerInt));
3138     break;
3139 #else
3140   case  8:  movq(dst, src); break;
3141 #endif
3142   case  4:  movl(dst, src); break;
3143   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3144   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3145   default:  ShouldNotReachHere();
3146   }
3147 }
3148 
3149 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3150   switch (size_in_bytes) {
3151 #ifndef _LP64
3152   case  8:
3153     assert(src2 != noreg, "second source register required");
3154     movl(dst,                        src);
3155     movl(dst.plus_disp(BytesPerInt), src2);
3156     break;
3157 #else
3158   case  8:  movq(dst, src); break;
3159 #endif
3160   case  4:  movl(dst, src); break;
3161   case  2:  movw(dst, src); break;
3162   case  1:  movb(dst, src); break;
3163   default:  ShouldNotReachHere();
3164   }
3165 }
3166 
3167 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3168   if (reachable(dst)) {
3169     movl(as_Address(dst), src);
3170   } else {
3171     lea(rscratch1, dst);
3172     movl(Address(rscratch1, 0), src);
3173   }
3174 }
3175 
3176 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3177   if (reachable(src)) {
3178     movl(dst, as_Address(src));
3179   } else {
3180     lea(rscratch1, src);
3181     movl(dst, Address(rscratch1, 0));
3182   }
3183 }
3184 
3185 // C++ bool manipulation
3186 
3187 void MacroAssembler::movbool(Register dst, Address src) {
3188   if(sizeof(bool) == 1)
3189     movb(dst, src);
3190   else if(sizeof(bool) == 2)
3191     movw(dst, src);
3192   else if(sizeof(bool) == 4)
3193     movl(dst, src);
3194   else
3195     // unsupported
3196     ShouldNotReachHere();
3197 }
3198 
3199 void MacroAssembler::movbool(Address dst, bool boolconst) {
3200   if(sizeof(bool) == 1)
3201     movb(dst, (int) boolconst);
3202   else if(sizeof(bool) == 2)
3203     movw(dst, (int) boolconst);
3204   else if(sizeof(bool) == 4)
3205     movl(dst, (int) boolconst);
3206   else
3207     // unsupported
3208     ShouldNotReachHere();
3209 }
3210 
3211 void MacroAssembler::movbool(Address dst, Register src) {
3212   if(sizeof(bool) == 1)
3213     movb(dst, src);
3214   else if(sizeof(bool) == 2)
3215     movw(dst, src);
3216   else if(sizeof(bool) == 4)
3217     movl(dst, src);
3218   else
3219     // unsupported
3220     ShouldNotReachHere();
3221 }
3222 
3223 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3224   movb(as_Address(dst), src);
3225 }
3226 
3227 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3228   if (reachable(src)) {
3229     movdl(dst, as_Address(src));
3230   } else {
3231     lea(rscratch1, src);
3232     movdl(dst, Address(rscratch1, 0));
3233   }
3234 }
3235 
3236 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3237   if (reachable(src)) {
3238     movq(dst, as_Address(src));
3239   } else {
3240     lea(rscratch1, src);
3241     movq(dst, Address(rscratch1, 0));
3242   }
3243 }
3244 
3245 #ifdef COMPILER2
3246 void MacroAssembler::setvectmask(Register dst, Register src) {
3247   guarantee(PostLoopMultiversioning, "must be");
3248   Assembler::movl(dst, 1);
3249   Assembler::shlxl(dst, dst, src);
3250   Assembler::decl(dst);
3251   Assembler::kmovdl(k1, dst);
3252   Assembler::movl(dst, src);
3253 }
3254 
3255 void MacroAssembler::restorevectmask() {
3256   guarantee(PostLoopMultiversioning, "must be");
3257   Assembler::knotwl(k1, k0);
3258 }
3259 #endif // COMPILER2
3260 
3261 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3262   if (reachable(src)) {
3263     if (UseXmmLoadAndClearUpper) {
3264       movsd (dst, as_Address(src));
3265     } else {
3266       movlpd(dst, as_Address(src));
3267     }
3268   } else {
3269     lea(rscratch1, src);
3270     if (UseXmmLoadAndClearUpper) {
3271       movsd (dst, Address(rscratch1, 0));
3272     } else {
3273       movlpd(dst, Address(rscratch1, 0));
3274     }
3275   }
3276 }
3277 
3278 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3279   if (reachable(src)) {
3280     movss(dst, as_Address(src));
3281   } else {
3282     lea(rscratch1, src);
3283     movss(dst, Address(rscratch1, 0));
3284   }
3285 }
3286 
3287 void MacroAssembler::movptr(Register dst, Register src) {
3288   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3289 }
3290 
3291 void MacroAssembler::movptr(Register dst, Address src) {
3292   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3293 }
3294 
3295 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3296 void MacroAssembler::movptr(Register dst, intptr_t src) {
3297   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3298 }
3299 
3300 void MacroAssembler::movptr(Address dst, Register src) {
3301   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3302 }
3303 
3304 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3305     assert(((src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3306     Assembler::movdqu(dst, src);
3307 }
3308 
3309 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3310     assert(((dst->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3311     Assembler::movdqu(dst, src);
3312 }
3313 
3314 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3315     assert(((dst->encoding() < 16  && src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3316     Assembler::movdqu(dst, src);
3317 }
3318 
3319 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3320   if (reachable(src)) {
3321     movdqu(dst, as_Address(src));
3322   } else {
3323     lea(scratchReg, src);
3324     movdqu(dst, Address(scratchReg, 0));
3325   }
3326 }
3327 
3328 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3329     assert(((src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3330     Assembler::vmovdqu(dst, src);
3331 }
3332 
3333 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3334     assert(((dst->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3335     Assembler::vmovdqu(dst, src);
3336 }
3337 
3338 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3339     assert(((dst->encoding() < 16  && src->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3340     Assembler::vmovdqu(dst, src);
3341 }
3342 
3343 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3344   if (reachable(src)) {
3345     vmovdqu(dst, as_Address(src));
3346   }
3347   else {
3348     lea(rscratch1, src);
3349     vmovdqu(dst, Address(rscratch1, 0));
3350   }
3351 }
3352 
3353 void MacroAssembler::evmovdquq(XMMRegister dst, AddressLiteral src, int vector_len, Register rscratch) {
3354   if (reachable(src)) {
3355     Assembler::evmovdquq(dst, as_Address(src), vector_len);
3356   } else {
3357     lea(rscratch, src);
3358     Assembler::evmovdquq(dst, Address(rscratch, 0), vector_len);
3359   }
3360 }
3361 
3362 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3363   if (reachable(src)) {
3364     Assembler::movdqa(dst, as_Address(src));
3365   } else {
3366     lea(rscratch1, src);
3367     Assembler::movdqa(dst, Address(rscratch1, 0));
3368   }
3369 }
3370 
3371 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3372   if (reachable(src)) {
3373     Assembler::movsd(dst, as_Address(src));
3374   } else {
3375     lea(rscratch1, src);
3376     Assembler::movsd(dst, Address(rscratch1, 0));
3377   }
3378 }
3379 
3380 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3381   if (reachable(src)) {
3382     Assembler::movss(dst, as_Address(src));
3383   } else {
3384     lea(rscratch1, src);
3385     Assembler::movss(dst, Address(rscratch1, 0));
3386   }
3387 }
3388 
3389 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3390   if (reachable(src)) {
3391     Assembler::mulsd(dst, as_Address(src));
3392   } else {
3393     lea(rscratch1, src);
3394     Assembler::mulsd(dst, Address(rscratch1, 0));
3395   }
3396 }
3397 
3398 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3399   if (reachable(src)) {
3400     Assembler::mulss(dst, as_Address(src));
3401   } else {
3402     lea(rscratch1, src);
3403     Assembler::mulss(dst, Address(rscratch1, 0));
3404   }
3405 }
3406 
3407 void MacroAssembler::null_check(Register reg, int offset) {
3408   if (needs_explicit_null_check(offset)) {
3409     // provoke OS NULL exception if reg = NULL by
3410     // accessing M[reg] w/o changing any (non-CC) registers
3411     // NOTE: cmpl is plenty here to provoke a segv
3412     cmpptr(rax, Address(reg, 0));
3413     // Note: should probably use testl(rax, Address(reg, 0));
3414     //       may be shorter code (however, this version of
3415     //       testl needs to be implemented first)
3416   } else {
3417     // nothing to do, (later) access of M[reg + offset]
3418     // will provoke OS NULL exception if reg = NULL
3419   }
3420 }
3421 
3422 void MacroAssembler::os_breakpoint() {
3423   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3424   // (e.g., MSVC can't call ps() otherwise)
3425   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3426 }
3427 
3428 void MacroAssembler::unimplemented(const char* what) {
3429   const char* buf = NULL;
3430   {
3431     ResourceMark rm;
3432     stringStream ss;
3433     ss.print("unimplemented: %s", what);
3434     buf = code_string(ss.as_string());
3435   }
3436   stop(buf);
3437 }
3438 
3439 #ifdef _LP64
3440 #define XSTATE_BV 0x200
3441 #endif
3442 
3443 void MacroAssembler::pop_CPU_state() {
3444   pop_FPU_state();
3445   pop_IU_state();
3446 }
3447 
3448 void MacroAssembler::pop_FPU_state() {
3449 #ifndef _LP64
3450   frstor(Address(rsp, 0));
3451 #else
3452   fxrstor(Address(rsp, 0));
3453 #endif
3454   addptr(rsp, FPUStateSizeInWords * wordSize);
3455 }
3456 
3457 void MacroAssembler::pop_IU_state() {
3458   popa();
3459   LP64_ONLY(addq(rsp, 8));
3460   popf();
3461 }
3462 
3463 // Save Integer and Float state
3464 // Warning: Stack must be 16 byte aligned (64bit)
3465 void MacroAssembler::push_CPU_state() {
3466   push_IU_state();
3467   push_FPU_state();
3468 }
3469 
3470 void MacroAssembler::push_FPU_state() {
3471   subptr(rsp, FPUStateSizeInWords * wordSize);
3472 #ifndef _LP64
3473   fnsave(Address(rsp, 0));
3474   fwait();
3475 #else
3476   fxsave(Address(rsp, 0));
3477 #endif // LP64
3478 }
3479 
3480 void MacroAssembler::push_IU_state() {
3481   // Push flags first because pusha kills them
3482   pushf();
3483   // Make sure rsp stays 16-byte aligned
3484   LP64_ONLY(subq(rsp, 8));
3485   pusha();
3486 }
3487 
3488 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3489   if (!java_thread->is_valid()) {
3490     java_thread = rdi;
3491     get_thread(java_thread);
3492   }
3493   // we must set sp to zero to clear frame
3494   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3495   if (clear_fp) {
3496     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3497   }
3498 
3499   // Always clear the pc because it could have been set by make_walkable()
3500   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3501 
3502   vzeroupper();
3503 }
3504 
3505 void MacroAssembler::restore_rax(Register tmp) {
3506   if (tmp == noreg) pop(rax);
3507   else if (tmp != rax) mov(rax, tmp);
3508 }
3509 
3510 void MacroAssembler::round_to(Register reg, int modulus) {
3511   addptr(reg, modulus - 1);
3512   andptr(reg, -modulus);
3513 }
3514 
3515 void MacroAssembler::save_rax(Register tmp) {
3516   if (tmp == noreg) push(rax);
3517   else if (tmp != rax) mov(tmp, rax);
3518 }
3519 
3520 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, Register temp_reg) {
3521   if (SafepointMechanism::uses_thread_local_poll()) {
3522 #ifdef _LP64
3523     assert(thread_reg == r15_thread, "should be");
3524 #else
3525     if (thread_reg == noreg) {
3526       thread_reg = temp_reg;
3527       get_thread(thread_reg);
3528     }
3529 #endif
3530     testb(Address(thread_reg, Thread::polling_page_offset()), SafepointMechanism::poll_bit());
3531     jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
3532   } else {
3533     cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3534         SafepointSynchronize::_not_synchronized);
3535     jcc(Assembler::notEqual, slow_path);
3536   }
3537 }
3538 
3539 // Calls to C land
3540 //
3541 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3542 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3543 // has to be reset to 0. This is required to allow proper stack traversal.
3544 void MacroAssembler::set_last_Java_frame(Register java_thread,
3545                                          Register last_java_sp,
3546                                          Register last_java_fp,
3547                                          address  last_java_pc) {
3548   vzeroupper();
3549   // determine java_thread register
3550   if (!java_thread->is_valid()) {
3551     java_thread = rdi;
3552     get_thread(java_thread);
3553   }
3554   // determine last_java_sp register
3555   if (!last_java_sp->is_valid()) {
3556     last_java_sp = rsp;
3557   }
3558 
3559   // last_java_fp is optional
3560 
3561   if (last_java_fp->is_valid()) {
3562     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3563   }
3564 
3565   // last_java_pc is optional
3566 
3567   if (last_java_pc != NULL) {
3568     lea(Address(java_thread,
3569                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3570         InternalAddress(last_java_pc));
3571 
3572   }
3573   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3574 }
3575 
3576 void MacroAssembler::shlptr(Register dst, int imm8) {
3577   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3578 }
3579 
3580 void MacroAssembler::shrptr(Register dst, int imm8) {
3581   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3582 }
3583 
3584 void MacroAssembler::sign_extend_byte(Register reg) {
3585   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3586     movsbl(reg, reg); // movsxb
3587   } else {
3588     shll(reg, 24);
3589     sarl(reg, 24);
3590   }
3591 }
3592 
3593 void MacroAssembler::sign_extend_short(Register reg) {
3594   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3595     movswl(reg, reg); // movsxw
3596   } else {
3597     shll(reg, 16);
3598     sarl(reg, 16);
3599   }
3600 }
3601 
3602 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3603   assert(reachable(src), "Address should be reachable");
3604   testl(dst, as_Address(src));
3605 }
3606 
3607 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3608   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3609   Assembler::pcmpeqb(dst, src);
3610 }
3611 
3612 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3613   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3614   Assembler::pcmpeqw(dst, src);
3615 }
3616 
3617 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3618   assert((dst->encoding() < 16),"XMM register should be 0-15");
3619   Assembler::pcmpestri(dst, src, imm8);
3620 }
3621 
3622 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3623   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
3624   Assembler::pcmpestri(dst, src, imm8);
3625 }
3626 
3627 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3628   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3629   Assembler::pmovzxbw(dst, src);
3630 }
3631 
3632 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
3633   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3634   Assembler::pmovzxbw(dst, src);
3635 }
3636 
3637 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
3638   assert((src->encoding() < 16),"XMM register should be 0-15");
3639   Assembler::pmovmskb(dst, src);
3640 }
3641 
3642 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
3643   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
3644   Assembler::ptest(dst, src);
3645 }
3646 
3647 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
3648   if (reachable(src)) {
3649     Assembler::sqrtsd(dst, as_Address(src));
3650   } else {
3651     lea(rscratch1, src);
3652     Assembler::sqrtsd(dst, Address(rscratch1, 0));
3653   }
3654 }
3655 
3656 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
3657   if (reachable(src)) {
3658     Assembler::sqrtss(dst, as_Address(src));
3659   } else {
3660     lea(rscratch1, src);
3661     Assembler::sqrtss(dst, Address(rscratch1, 0));
3662   }
3663 }
3664 
3665 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
3666   if (reachable(src)) {
3667     Assembler::subsd(dst, as_Address(src));
3668   } else {
3669     lea(rscratch1, src);
3670     Assembler::subsd(dst, Address(rscratch1, 0));
3671   }
3672 }
3673 
3674 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
3675   if (reachable(src)) {
3676     Assembler::subss(dst, as_Address(src));
3677   } else {
3678     lea(rscratch1, src);
3679     Assembler::subss(dst, Address(rscratch1, 0));
3680   }
3681 }
3682 
3683 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
3684   if (reachable(src)) {
3685     Assembler::ucomisd(dst, as_Address(src));
3686   } else {
3687     lea(rscratch1, src);
3688     Assembler::ucomisd(dst, Address(rscratch1, 0));
3689   }
3690 }
3691 
3692 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
3693   if (reachable(src)) {
3694     Assembler::ucomiss(dst, as_Address(src));
3695   } else {
3696     lea(rscratch1, src);
3697     Assembler::ucomiss(dst, Address(rscratch1, 0));
3698   }
3699 }
3700 
3701 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
3702   // Used in sign-bit flipping with aligned address.
3703   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
3704   if (reachable(src)) {
3705     Assembler::xorpd(dst, as_Address(src));
3706   } else {
3707     lea(rscratch1, src);
3708     Assembler::xorpd(dst, Address(rscratch1, 0));
3709   }
3710 }
3711 
3712 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
3713   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
3714     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
3715   }
3716   else {
3717     Assembler::xorpd(dst, src);
3718   }
3719 }
3720 
3721 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
3722   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
3723     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
3724   } else {
3725     Assembler::xorps(dst, src);
3726   }
3727 }
3728 
3729 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
3730   // Used in sign-bit flipping with aligned address.
3731   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
3732   if (reachable(src)) {
3733     Assembler::xorps(dst, as_Address(src));
3734   } else {
3735     lea(rscratch1, src);
3736     Assembler::xorps(dst, Address(rscratch1, 0));
3737   }
3738 }
3739 
3740 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
3741   // Used in sign-bit flipping with aligned address.
3742   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
3743   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
3744   if (reachable(src)) {
3745     Assembler::pshufb(dst, as_Address(src));
3746   } else {
3747     lea(rscratch1, src);
3748     Assembler::pshufb(dst, Address(rscratch1, 0));
3749   }
3750 }
3751 
3752 // AVX 3-operands instructions
3753 
3754 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3755   if (reachable(src)) {
3756     vaddsd(dst, nds, as_Address(src));
3757   } else {
3758     lea(rscratch1, src);
3759     vaddsd(dst, nds, Address(rscratch1, 0));
3760   }
3761 }
3762 
3763 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3764   if (reachable(src)) {
3765     vaddss(dst, nds, as_Address(src));
3766   } else {
3767     lea(rscratch1, src);
3768     vaddss(dst, nds, Address(rscratch1, 0));
3769   }
3770 }
3771 
3772 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
3773   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
3774   vandps(dst, nds, negate_field, vector_len);
3775 }
3776 
3777 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
3778   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
3779   vandpd(dst, nds, negate_field, vector_len);
3780 }
3781 
3782 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3783   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3784   Assembler::vpaddb(dst, nds, src, vector_len);
3785 }
3786 
3787 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3788   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3789   Assembler::vpaddb(dst, nds, src, vector_len);
3790 }
3791 
3792 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3793   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3794   Assembler::vpaddw(dst, nds, src, vector_len);
3795 }
3796 
3797 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3798   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3799   Assembler::vpaddw(dst, nds, src, vector_len);
3800 }
3801 
3802 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
3803   if (reachable(src)) {
3804     Assembler::vpand(dst, nds, as_Address(src), vector_len);
3805   } else {
3806     lea(rscratch1, src);
3807     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
3808   }
3809 }
3810 
3811 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src, int vector_len) {
3812   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3813   Assembler::vpbroadcastw(dst, src, vector_len);
3814 }
3815 
3816 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3817   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3818   Assembler::vpcmpeqb(dst, nds, src, vector_len);
3819 }
3820 
3821 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3822   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3823   Assembler::vpcmpeqw(dst, nds, src, vector_len);
3824 }
3825 
3826 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
3827   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3828   Assembler::vpmovzxbw(dst, src, vector_len);
3829 }
3830 
3831 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
3832   assert((src->encoding() < 16),"XMM register should be 0-15");
3833   Assembler::vpmovmskb(dst, src);
3834 }
3835 
3836 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3837   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3838   Assembler::vpmullw(dst, nds, src, vector_len);
3839 }
3840 
3841 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3842   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3843   Assembler::vpmullw(dst, nds, src, vector_len);
3844 }
3845 
3846 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3847   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3848   Assembler::vpsubb(dst, nds, src, vector_len);
3849 }
3850 
3851 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3852   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3853   Assembler::vpsubb(dst, nds, src, vector_len);
3854 }
3855 
3856 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3857   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3858   Assembler::vpsubw(dst, nds, src, vector_len);
3859 }
3860 
3861 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3862   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3863   Assembler::vpsubw(dst, nds, src, vector_len);
3864 }
3865 
3866 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3867   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3868   Assembler::vpsraw(dst, nds, shift, vector_len);
3869 }
3870 
3871 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3872   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3873   Assembler::vpsraw(dst, nds, shift, vector_len);
3874 }
3875 
















3876 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3877   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3878   Assembler::vpsrlw(dst, nds, shift, vector_len);
3879 }
3880 
3881 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3882   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3883   Assembler::vpsrlw(dst, nds, shift, vector_len);
3884 }
3885 
3886 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3887   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3888   Assembler::vpsllw(dst, nds, shift, vector_len);
3889 }
3890 
3891 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3892   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3893   Assembler::vpsllw(dst, nds, shift, vector_len);
3894 }
3895 
3896 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
3897   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
3898   Assembler::vptest(dst, src);
3899 }
3900 
3901 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
3902   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3903   Assembler::punpcklbw(dst, src);
3904 }
3905 
3906 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
3907   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3908   Assembler::pshufd(dst, src, mode);
3909 }
3910 
3911 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
3912   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3913   Assembler::pshuflw(dst, src, mode);
3914 }
3915 
3916 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
3917   if (reachable(src)) {
3918     vandpd(dst, nds, as_Address(src), vector_len);
3919   } else {
3920     lea(rscratch1, src);
3921     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
3922   }
3923 }
3924 
3925 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
3926   if (reachable(src)) {
3927     vandps(dst, nds, as_Address(src), vector_len);
3928   } else {
3929     lea(rscratch1, src);
3930     vandps(dst, nds, Address(rscratch1, 0), vector_len);
3931   }
3932 }
3933 
3934 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3935   if (reachable(src)) {
3936     vdivsd(dst, nds, as_Address(src));
3937   } else {
3938     lea(rscratch1, src);
3939     vdivsd(dst, nds, Address(rscratch1, 0));
3940   }
3941 }
3942 
3943 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3944   if (reachable(src)) {
3945     vdivss(dst, nds, as_Address(src));
3946   } else {
3947     lea(rscratch1, src);
3948     vdivss(dst, nds, Address(rscratch1, 0));
3949   }
3950 }
3951 
3952 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3953   if (reachable(src)) {
3954     vmulsd(dst, nds, as_Address(src));
3955   } else {
3956     lea(rscratch1, src);
3957     vmulsd(dst, nds, Address(rscratch1, 0));
3958   }
3959 }
3960 
3961 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3962   if (reachable(src)) {
3963     vmulss(dst, nds, as_Address(src));
3964   } else {
3965     lea(rscratch1, src);
3966     vmulss(dst, nds, Address(rscratch1, 0));
3967   }
3968 }
3969 
3970 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3971   if (reachable(src)) {
3972     vsubsd(dst, nds, as_Address(src));
3973   } else {
3974     lea(rscratch1, src);
3975     vsubsd(dst, nds, Address(rscratch1, 0));
3976   }
3977 }
3978 
3979 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3980   if (reachable(src)) {
3981     vsubss(dst, nds, as_Address(src));
3982   } else {
3983     lea(rscratch1, src);
3984     vsubss(dst, nds, Address(rscratch1, 0));
3985   }
3986 }
3987 
3988 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3989   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
3990   vxorps(dst, nds, src, Assembler::AVX_128bit);
3991 }
3992 
3993 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3994   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
3995   vxorpd(dst, nds, src, Assembler::AVX_128bit);
3996 }
3997 
3998 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
3999   if (reachable(src)) {
4000     vxorpd(dst, nds, as_Address(src), vector_len);
4001   } else {
4002     lea(rscratch1, src);
4003     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
4004   }
4005 }
4006 
4007 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4008   if (reachable(src)) {
4009     vxorps(dst, nds, as_Address(src), vector_len);
4010   } else {
4011     lea(rscratch1, src);
4012     vxorps(dst, nds, Address(rscratch1, 0), vector_len);














4013   }
4014 }
4015 
4016 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
4017   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
4018   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
4019   // The inverted mask is sign-extended
4020   andptr(possibly_jweak, inverted_jweak_mask);
4021 }
4022 
4023 void MacroAssembler::resolve_jobject(Register value,
4024                                      Register thread,
4025                                      Register tmp) {
4026   assert_different_registers(value, thread, tmp);
4027   Label done, not_weak;
4028   testptr(value, value);
4029   jcc(Assembler::zero, done);                // Use NULL as-is.
4030   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
4031   jcc(Assembler::zero, not_weak);
4032   // Resolve jweak.
4033   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
4034                  value, Address(value, -JNIHandles::weak_tag_value), tmp, thread);
4035   verify_oop(value);
4036   jmp(done);
4037   bind(not_weak);
4038   // Resolve (untagged) jobject.
4039   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, 0), tmp, thread);
4040   verify_oop(value);
4041   bind(done);
4042 }
4043 
4044 void MacroAssembler::subptr(Register dst, int32_t imm32) {
4045   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
4046 }
4047 
4048 // Force generation of a 4 byte immediate value even if it fits into 8bit
4049 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
4050   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
4051 }
4052 
4053 void MacroAssembler::subptr(Register dst, Register src) {
4054   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
4055 }
4056 
4057 // C++ bool manipulation
4058 void MacroAssembler::testbool(Register dst) {
4059   if(sizeof(bool) == 1)
4060     testb(dst, 0xff);
4061   else if(sizeof(bool) == 2) {
4062     // testw implementation needed for two byte bools
4063     ShouldNotReachHere();
4064   } else if(sizeof(bool) == 4)
4065     testl(dst, dst);
4066   else
4067     // unsupported
4068     ShouldNotReachHere();
4069 }
4070 
4071 void MacroAssembler::testptr(Register dst, Register src) {
4072   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
4073 }
4074 
4075 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
4076 void MacroAssembler::tlab_allocate(Register thread, Register obj,
4077                                    Register var_size_in_bytes,
4078                                    int con_size_in_bytes,
4079                                    Register t1,
4080                                    Register t2,
4081                                    Label& slow_case) {
4082   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
4083   bs->tlab_allocate(this, thread, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
4084 }
4085 
4086 // Defines obj, preserves var_size_in_bytes
4087 void MacroAssembler::eden_allocate(Register thread, Register obj,
4088                                    Register var_size_in_bytes,
4089                                    int con_size_in_bytes,
4090                                    Register t1,
4091                                    Label& slow_case) {
4092   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
4093   bs->eden_allocate(this, thread, obj, var_size_in_bytes, con_size_in_bytes, t1, slow_case);
4094 }
4095 
4096 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
4097 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
4098   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
4099   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
4100   Label done;
4101 
4102   testptr(length_in_bytes, length_in_bytes);
4103   jcc(Assembler::zero, done);
4104 
4105   // initialize topmost word, divide index by 2, check if odd and test if zero
4106   // note: for the remaining code to work, index must be a multiple of BytesPerWord
4107 #ifdef ASSERT
4108   {
4109     Label L;
4110     testptr(length_in_bytes, BytesPerWord - 1);
4111     jcc(Assembler::zero, L);
4112     stop("length must be a multiple of BytesPerWord");
4113     bind(L);
4114   }
4115 #endif
4116   Register index = length_in_bytes;
4117   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
4118   if (UseIncDec) {
4119     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
4120   } else {
4121     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
4122     shrptr(index, 1);
4123   }
4124 #ifndef _LP64
4125   // index could have not been a multiple of 8 (i.e., bit 2 was set)
4126   {
4127     Label even;
4128     // note: if index was a multiple of 8, then it cannot
4129     //       be 0 now otherwise it must have been 0 before
4130     //       => if it is even, we don't need to check for 0 again
4131     jcc(Assembler::carryClear, even);
4132     // clear topmost word (no jump would be needed if conditional assignment worked here)
4133     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
4134     // index could be 0 now, must check again
4135     jcc(Assembler::zero, done);
4136     bind(even);
4137   }
4138 #endif // !_LP64
4139   // initialize remaining object fields: index is a multiple of 2 now
4140   {
4141     Label loop;
4142     bind(loop);
4143     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
4144     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
4145     decrement(index);
4146     jcc(Assembler::notZero, loop);
4147   }
4148 
4149   bind(done);
4150 }
4151 
4152 // Look up the method for a megamorphic invokeinterface call.
4153 // The target method is determined by <intf_klass, itable_index>.
4154 // The receiver klass is in recv_klass.
4155 // On success, the result will be in method_result, and execution falls through.
4156 // On failure, execution transfers to the given label.
4157 void MacroAssembler::lookup_interface_method(Register recv_klass,
4158                                              Register intf_klass,
4159                                              RegisterOrConstant itable_index,
4160                                              Register method_result,
4161                                              Register scan_temp,
4162                                              Label& L_no_such_interface,
4163                                              bool return_method) {
4164   assert_different_registers(recv_klass, intf_klass, scan_temp);
4165   assert_different_registers(method_result, intf_klass, scan_temp);
4166   assert(recv_klass != method_result || !return_method,
4167          "recv_klass can be destroyed when method isn't needed");
4168 
4169   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
4170          "caller must use same register for non-constant itable index as for method");
4171 
4172   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
4173   int vtable_base = in_bytes(Klass::vtable_start_offset());
4174   int itentry_off = itableMethodEntry::method_offset_in_bytes();
4175   int scan_step   = itableOffsetEntry::size() * wordSize;
4176   int vte_size    = vtableEntry::size_in_bytes();
4177   Address::ScaleFactor times_vte_scale = Address::times_ptr;
4178   assert(vte_size == wordSize, "else adjust times_vte_scale");
4179 
4180   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
4181 
4182   // %%% Could store the aligned, prescaled offset in the klassoop.
4183   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
4184 
4185   if (return_method) {
4186     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
4187     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
4188     lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
4189   }
4190 
4191   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
4192   //   if (scan->interface() == intf) {
4193   //     result = (klass + scan->offset() + itable_index);
4194   //   }
4195   // }
4196   Label search, found_method;
4197 
4198   for (int peel = 1; peel >= 0; peel--) {
4199     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
4200     cmpptr(intf_klass, method_result);
4201 
4202     if (peel) {
4203       jccb(Assembler::equal, found_method);
4204     } else {
4205       jccb(Assembler::notEqual, search);
4206       // (invert the test to fall through to found_method...)
4207     }
4208 
4209     if (!peel)  break;
4210 
4211     bind(search);
4212 
4213     // Check that the previous entry is non-null.  A null entry means that
4214     // the receiver class doesn't implement the interface, and wasn't the
4215     // same as when the caller was compiled.
4216     testptr(method_result, method_result);
4217     jcc(Assembler::zero, L_no_such_interface);
4218     addptr(scan_temp, scan_step);
4219   }
4220 
4221   bind(found_method);
4222 
4223   if (return_method) {
4224     // Got a hit.
4225     movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
4226     movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
4227   }
4228 }
4229 
4230 
4231 // virtual method calling
4232 void MacroAssembler::lookup_virtual_method(Register recv_klass,
4233                                            RegisterOrConstant vtable_index,
4234                                            Register method_result) {
4235   const int base = in_bytes(Klass::vtable_start_offset());
4236   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
4237   Address vtable_entry_addr(recv_klass,
4238                             vtable_index, Address::times_ptr,
4239                             base + vtableEntry::method_offset_in_bytes());
4240   movptr(method_result, vtable_entry_addr);
4241 }
4242 
4243 
4244 void MacroAssembler::check_klass_subtype(Register sub_klass,
4245                            Register super_klass,
4246                            Register temp_reg,
4247                            Label& L_success) {
4248   Label L_failure;
4249   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
4250   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
4251   bind(L_failure);
4252 }
4253 
4254 
4255 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
4256                                                    Register super_klass,
4257                                                    Register temp_reg,
4258                                                    Label* L_success,
4259                                                    Label* L_failure,
4260                                                    Label* L_slow_path,
4261                                         RegisterOrConstant super_check_offset) {
4262   assert_different_registers(sub_klass, super_klass, temp_reg);
4263   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
4264   if (super_check_offset.is_register()) {
4265     assert_different_registers(sub_klass, super_klass,
4266                                super_check_offset.as_register());
4267   } else if (must_load_sco) {
4268     assert(temp_reg != noreg, "supply either a temp or a register offset");
4269   }
4270 
4271   Label L_fallthrough;
4272   int label_nulls = 0;
4273   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
4274   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
4275   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
4276   assert(label_nulls <= 1, "at most one NULL in the batch");
4277 
4278   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
4279   int sco_offset = in_bytes(Klass::super_check_offset_offset());
4280   Address super_check_offset_addr(super_klass, sco_offset);
4281 
4282   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
4283   // range of a jccb.  If this routine grows larger, reconsider at
4284   // least some of these.
4285 #define local_jcc(assembler_cond, label)                                \
4286   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
4287   else                             jcc( assembler_cond, label) /*omit semi*/
4288 
4289   // Hacked jmp, which may only be used just before L_fallthrough.
4290 #define final_jmp(label)                                                \
4291   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
4292   else                            jmp(label)                /*omit semi*/
4293 
4294   // If the pointers are equal, we are done (e.g., String[] elements).
4295   // This self-check enables sharing of secondary supertype arrays among
4296   // non-primary types such as array-of-interface.  Otherwise, each such
4297   // type would need its own customized SSA.
4298   // We move this check to the front of the fast path because many
4299   // type checks are in fact trivially successful in this manner,
4300   // so we get a nicely predicted branch right at the start of the check.
4301   cmpptr(sub_klass, super_klass);
4302   local_jcc(Assembler::equal, *L_success);
4303 
4304   // Check the supertype display:
4305   if (must_load_sco) {
4306     // Positive movl does right thing on LP64.
4307     movl(temp_reg, super_check_offset_addr);
4308     super_check_offset = RegisterOrConstant(temp_reg);
4309   }
4310   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
4311   cmpptr(super_klass, super_check_addr); // load displayed supertype
4312 
4313   // This check has worked decisively for primary supers.
4314   // Secondary supers are sought in the super_cache ('super_cache_addr').
4315   // (Secondary supers are interfaces and very deeply nested subtypes.)
4316   // This works in the same check above because of a tricky aliasing
4317   // between the super_cache and the primary super display elements.
4318   // (The 'super_check_addr' can address either, as the case requires.)
4319   // Note that the cache is updated below if it does not help us find
4320   // what we need immediately.
4321   // So if it was a primary super, we can just fail immediately.
4322   // Otherwise, it's the slow path for us (no success at this point).
4323 
4324   if (super_check_offset.is_register()) {
4325     local_jcc(Assembler::equal, *L_success);
4326     cmpl(super_check_offset.as_register(), sc_offset);
4327     if (L_failure == &L_fallthrough) {
4328       local_jcc(Assembler::equal, *L_slow_path);
4329     } else {
4330       local_jcc(Assembler::notEqual, *L_failure);
4331       final_jmp(*L_slow_path);
4332     }
4333   } else if (super_check_offset.as_constant() == sc_offset) {
4334     // Need a slow path; fast failure is impossible.
4335     if (L_slow_path == &L_fallthrough) {
4336       local_jcc(Assembler::equal, *L_success);
4337     } else {
4338       local_jcc(Assembler::notEqual, *L_slow_path);
4339       final_jmp(*L_success);
4340     }
4341   } else {
4342     // No slow path; it's a fast decision.
4343     if (L_failure == &L_fallthrough) {
4344       local_jcc(Assembler::equal, *L_success);
4345     } else {
4346       local_jcc(Assembler::notEqual, *L_failure);
4347       final_jmp(*L_success);
4348     }
4349   }
4350 
4351   bind(L_fallthrough);
4352 
4353 #undef local_jcc
4354 #undef final_jmp
4355 }
4356 
4357 
4358 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
4359                                                    Register super_klass,
4360                                                    Register temp_reg,
4361                                                    Register temp2_reg,
4362                                                    Label* L_success,
4363                                                    Label* L_failure,
4364                                                    bool set_cond_codes) {
4365   assert_different_registers(sub_klass, super_klass, temp_reg);
4366   if (temp2_reg != noreg)
4367     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
4368 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
4369 
4370   Label L_fallthrough;
4371   int label_nulls = 0;
4372   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
4373   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
4374   assert(label_nulls <= 1, "at most one NULL in the batch");
4375 
4376   // a couple of useful fields in sub_klass:
4377   int ss_offset = in_bytes(Klass::secondary_supers_offset());
4378   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
4379   Address secondary_supers_addr(sub_klass, ss_offset);
4380   Address super_cache_addr(     sub_klass, sc_offset);
4381 
4382   // Do a linear scan of the secondary super-klass chain.
4383   // This code is rarely used, so simplicity is a virtue here.
4384   // The repne_scan instruction uses fixed registers, which we must spill.
4385   // Don't worry too much about pre-existing connections with the input regs.
4386 
4387   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
4388   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
4389 
4390   // Get super_klass value into rax (even if it was in rdi or rcx).
4391   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
4392   if (super_klass != rax || UseCompressedOops) {
4393     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
4394     mov(rax, super_klass);
4395   }
4396   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
4397   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
4398 
4399 #ifndef PRODUCT
4400   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
4401   ExternalAddress pst_counter_addr((address) pst_counter);
4402   NOT_LP64(  incrementl(pst_counter_addr) );
4403   LP64_ONLY( lea(rcx, pst_counter_addr) );
4404   LP64_ONLY( incrementl(Address(rcx, 0)) );
4405 #endif //PRODUCT
4406 
4407   // We will consult the secondary-super array.
4408   movptr(rdi, secondary_supers_addr);
4409   // Load the array length.  (Positive movl does right thing on LP64.)
4410   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
4411   // Skip to start of data.
4412   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
4413 
4414   // Scan RCX words at [RDI] for an occurrence of RAX.
4415   // Set NZ/Z based on last compare.
4416   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
4417   // not change flags (only scas instruction which is repeated sets flags).
4418   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
4419 
4420     testptr(rax,rax); // Set Z = 0
4421     repne_scan();
4422 
4423   // Unspill the temp. registers:
4424   if (pushed_rdi)  pop(rdi);
4425   if (pushed_rcx)  pop(rcx);
4426   if (pushed_rax)  pop(rax);
4427 
4428   if (set_cond_codes) {
4429     // Special hack for the AD files:  rdi is guaranteed non-zero.
4430     assert(!pushed_rdi, "rdi must be left non-NULL");
4431     // Also, the condition codes are properly set Z/NZ on succeed/failure.
4432   }
4433 
4434   if (L_failure == &L_fallthrough)
4435         jccb(Assembler::notEqual, *L_failure);
4436   else  jcc(Assembler::notEqual, *L_failure);
4437 
4438   // Success.  Cache the super we found and proceed in triumph.
4439   movptr(super_cache_addr, super_klass);
4440 
4441   if (L_success != &L_fallthrough) {
4442     jmp(*L_success);
4443   }
4444 
4445 #undef IS_A_TEMP
4446 
4447   bind(L_fallthrough);
4448 }
4449 
4450 
4451 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
4452   if (VM_Version::supports_cmov()) {
4453     cmovl(cc, dst, src);
4454   } else {
4455     Label L;
4456     jccb(negate_condition(cc), L);
4457     movl(dst, src);
4458     bind(L);
4459   }
4460 }
4461 
4462 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
4463   if (VM_Version::supports_cmov()) {
4464     cmovl(cc, dst, src);
4465   } else {
4466     Label L;
4467     jccb(negate_condition(cc), L);
4468     movl(dst, src);
4469     bind(L);
4470   }
4471 }
4472 
4473 void MacroAssembler::verify_oop(Register reg, const char* s) {
4474   if (!VerifyOops) return;
4475 
4476   // Pass register number to verify_oop_subroutine
4477   const char* b = NULL;
4478   {
4479     ResourceMark rm;
4480     stringStream ss;
4481     ss.print("verify_oop: %s: %s", reg->name(), s);
4482     b = code_string(ss.as_string());
4483   }
4484   BLOCK_COMMENT("verify_oop {");
4485 #ifdef _LP64
4486   push(rscratch1);                    // save r10, trashed by movptr()
4487 #endif
4488   push(rax);                          // save rax,
4489   push(reg);                          // pass register argument
4490   ExternalAddress buffer((address) b);
4491   // avoid using pushptr, as it modifies scratch registers
4492   // and our contract is not to modify anything
4493   movptr(rax, buffer.addr());
4494   push(rax);
4495   // call indirectly to solve generation ordering problem
4496   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
4497   call(rax);
4498   // Caller pops the arguments (oop, message) and restores rax, r10
4499   BLOCK_COMMENT("} verify_oop");
4500 }
4501 
4502 
4503 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
4504                                                       Register tmp,
4505                                                       int offset) {
4506   intptr_t value = *delayed_value_addr;
4507   if (value != 0)
4508     return RegisterOrConstant(value + offset);
4509 
4510   // load indirectly to solve generation ordering problem
4511   movptr(tmp, ExternalAddress((address) delayed_value_addr));
4512 
4513 #ifdef ASSERT
4514   { Label L;
4515     testptr(tmp, tmp);
4516     if (WizardMode) {
4517       const char* buf = NULL;
4518       {
4519         ResourceMark rm;
4520         stringStream ss;
4521         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
4522         buf = code_string(ss.as_string());
4523       }
4524       jcc(Assembler::notZero, L);
4525       STOP(buf);
4526     } else {
4527       jccb(Assembler::notZero, L);
4528       hlt();
4529     }
4530     bind(L);
4531   }
4532 #endif
4533 
4534   if (offset != 0)
4535     addptr(tmp, offset);
4536 
4537   return RegisterOrConstant(tmp);
4538 }
4539 
4540 
4541 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
4542                                          int extra_slot_offset) {
4543   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
4544   int stackElementSize = Interpreter::stackElementSize;
4545   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
4546 #ifdef ASSERT
4547   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
4548   assert(offset1 - offset == stackElementSize, "correct arithmetic");
4549 #endif
4550   Register             scale_reg    = noreg;
4551   Address::ScaleFactor scale_factor = Address::no_scale;
4552   if (arg_slot.is_constant()) {
4553     offset += arg_slot.as_constant() * stackElementSize;
4554   } else {
4555     scale_reg    = arg_slot.as_register();
4556     scale_factor = Address::times(stackElementSize);
4557   }
4558   offset += wordSize;           // return PC is on stack
4559   return Address(rsp, scale_reg, scale_factor, offset);
4560 }
4561 
4562 
4563 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
4564   if (!VerifyOops) return;
4565 
4566   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
4567   // Pass register number to verify_oop_subroutine
4568   const char* b = NULL;
4569   {
4570     ResourceMark rm;
4571     stringStream ss;
4572     ss.print("verify_oop_addr: %s", s);
4573     b = code_string(ss.as_string());
4574   }
4575 #ifdef _LP64
4576   push(rscratch1);                    // save r10, trashed by movptr()
4577 #endif
4578   push(rax);                          // save rax,
4579   // addr may contain rsp so we will have to adjust it based on the push
4580   // we just did (and on 64 bit we do two pushes)
4581   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
4582   // stores rax into addr which is backwards of what was intended.
4583   if (addr.uses(rsp)) {
4584     lea(rax, addr);
4585     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
4586   } else {
4587     pushptr(addr);
4588   }
4589 
4590   ExternalAddress buffer((address) b);
4591   // pass msg argument
4592   // avoid using pushptr, as it modifies scratch registers
4593   // and our contract is not to modify anything
4594   movptr(rax, buffer.addr());
4595   push(rax);
4596 
4597   // call indirectly to solve generation ordering problem
4598   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
4599   call(rax);
4600   // Caller pops the arguments (addr, message) and restores rax, r10.
4601 }
4602 
4603 void MacroAssembler::verify_tlab() {
4604 #ifdef ASSERT
4605   if (UseTLAB && VerifyOops) {
4606     Label next, ok;
4607     Register t1 = rsi;
4608     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
4609 
4610     push(t1);
4611     NOT_LP64(push(thread_reg));
4612     NOT_LP64(get_thread(thread_reg));
4613 
4614     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
4615     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
4616     jcc(Assembler::aboveEqual, next);
4617     STOP("assert(top >= start)");
4618     should_not_reach_here();
4619 
4620     bind(next);
4621     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
4622     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
4623     jcc(Assembler::aboveEqual, ok);
4624     STOP("assert(top <= end)");
4625     should_not_reach_here();
4626 
4627     bind(ok);
4628     NOT_LP64(pop(thread_reg));
4629     pop(t1);
4630   }
4631 #endif
4632 }
4633 
4634 class ControlWord {
4635  public:
4636   int32_t _value;
4637 
4638   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
4639   int  precision_control() const       { return  (_value >>  8) & 3      ; }
4640   bool precision() const               { return ((_value >>  5) & 1) != 0; }
4641   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
4642   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
4643   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
4644   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
4645   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
4646 
4647   void print() const {
4648     // rounding control
4649     const char* rc;
4650     switch (rounding_control()) {
4651       case 0: rc = "round near"; break;
4652       case 1: rc = "round down"; break;
4653       case 2: rc = "round up  "; break;
4654       case 3: rc = "chop      "; break;
4655     };
4656     // precision control
4657     const char* pc;
4658     switch (precision_control()) {
4659       case 0: pc = "24 bits "; break;
4660       case 1: pc = "reserved"; break;
4661       case 2: pc = "53 bits "; break;
4662       case 3: pc = "64 bits "; break;
4663     };
4664     // flags
4665     char f[9];
4666     f[0] = ' ';
4667     f[1] = ' ';
4668     f[2] = (precision   ()) ? 'P' : 'p';
4669     f[3] = (underflow   ()) ? 'U' : 'u';
4670     f[4] = (overflow    ()) ? 'O' : 'o';
4671     f[5] = (zero_divide ()) ? 'Z' : 'z';
4672     f[6] = (denormalized()) ? 'D' : 'd';
4673     f[7] = (invalid     ()) ? 'I' : 'i';
4674     f[8] = '\x0';
4675     // output
4676     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
4677   }
4678 
4679 };
4680 
4681 class StatusWord {
4682  public:
4683   int32_t _value;
4684 
4685   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
4686   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
4687   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
4688   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
4689   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
4690   int  top() const                     { return  (_value >> 11) & 7      ; }
4691   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
4692   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
4693   bool precision() const               { return ((_value >>  5) & 1) != 0; }
4694   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
4695   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
4696   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
4697   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
4698   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
4699 
4700   void print() const {
4701     // condition codes
4702     char c[5];
4703     c[0] = (C3()) ? '3' : '-';
4704     c[1] = (C2()) ? '2' : '-';
4705     c[2] = (C1()) ? '1' : '-';
4706     c[3] = (C0()) ? '0' : '-';
4707     c[4] = '\x0';
4708     // flags
4709     char f[9];
4710     f[0] = (error_status()) ? 'E' : '-';
4711     f[1] = (stack_fault ()) ? 'S' : '-';
4712     f[2] = (precision   ()) ? 'P' : '-';
4713     f[3] = (underflow   ()) ? 'U' : '-';
4714     f[4] = (overflow    ()) ? 'O' : '-';
4715     f[5] = (zero_divide ()) ? 'Z' : '-';
4716     f[6] = (denormalized()) ? 'D' : '-';
4717     f[7] = (invalid     ()) ? 'I' : '-';
4718     f[8] = '\x0';
4719     // output
4720     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
4721   }
4722 
4723 };
4724 
4725 class TagWord {
4726  public:
4727   int32_t _value;
4728 
4729   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
4730 
4731   void print() const {
4732     printf("%04x", _value & 0xFFFF);
4733   }
4734 
4735 };
4736 
4737 class FPU_Register {
4738  public:
4739   int32_t _m0;
4740   int32_t _m1;
4741   int16_t _ex;
4742 
4743   bool is_indefinite() const           {
4744     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
4745   }
4746 
4747   void print() const {
4748     char  sign = (_ex < 0) ? '-' : '+';
4749     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
4750     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
4751   };
4752 
4753 };
4754 
4755 class FPU_State {
4756  public:
4757   enum {
4758     register_size       = 10,
4759     number_of_registers =  8,
4760     register_mask       =  7
4761   };
4762 
4763   ControlWord  _control_word;
4764   StatusWord   _status_word;
4765   TagWord      _tag_word;
4766   int32_t      _error_offset;
4767   int32_t      _error_selector;
4768   int32_t      _data_offset;
4769   int32_t      _data_selector;
4770   int8_t       _register[register_size * number_of_registers];
4771 
4772   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
4773   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
4774 
4775   const char* tag_as_string(int tag) const {
4776     switch (tag) {
4777       case 0: return "valid";
4778       case 1: return "zero";
4779       case 2: return "special";
4780       case 3: return "empty";
4781     }
4782     ShouldNotReachHere();
4783     return NULL;
4784   }
4785 
4786   void print() const {
4787     // print computation registers
4788     { int t = _status_word.top();
4789       for (int i = 0; i < number_of_registers; i++) {
4790         int j = (i - t) & register_mask;
4791         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
4792         st(j)->print();
4793         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
4794       }
4795     }
4796     printf("\n");
4797     // print control registers
4798     printf("ctrl = "); _control_word.print(); printf("\n");
4799     printf("stat = "); _status_word .print(); printf("\n");
4800     printf("tags = "); _tag_word    .print(); printf("\n");
4801   }
4802 
4803 };
4804 
4805 class Flag_Register {
4806  public:
4807   int32_t _value;
4808 
4809   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
4810   bool direction() const               { return ((_value >> 10) & 1) != 0; }
4811   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
4812   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
4813   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
4814   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
4815   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
4816 
4817   void print() const {
4818     // flags
4819     char f[8];
4820     f[0] = (overflow       ()) ? 'O' : '-';
4821     f[1] = (direction      ()) ? 'D' : '-';
4822     f[2] = (sign           ()) ? 'S' : '-';
4823     f[3] = (zero           ()) ? 'Z' : '-';
4824     f[4] = (auxiliary_carry()) ? 'A' : '-';
4825     f[5] = (parity         ()) ? 'P' : '-';
4826     f[6] = (carry          ()) ? 'C' : '-';
4827     f[7] = '\x0';
4828     // output
4829     printf("%08x  flags = %s", _value, f);
4830   }
4831 
4832 };
4833 
4834 class IU_Register {
4835  public:
4836   int32_t _value;
4837 
4838   void print() const {
4839     printf("%08x  %11d", _value, _value);
4840   }
4841 
4842 };
4843 
4844 class IU_State {
4845  public:
4846   Flag_Register _eflags;
4847   IU_Register   _rdi;
4848   IU_Register   _rsi;
4849   IU_Register   _rbp;
4850   IU_Register   _rsp;
4851   IU_Register   _rbx;
4852   IU_Register   _rdx;
4853   IU_Register   _rcx;
4854   IU_Register   _rax;
4855 
4856   void print() const {
4857     // computation registers
4858     printf("rax,  = "); _rax.print(); printf("\n");
4859     printf("rbx,  = "); _rbx.print(); printf("\n");
4860     printf("rcx  = "); _rcx.print(); printf("\n");
4861     printf("rdx  = "); _rdx.print(); printf("\n");
4862     printf("rdi  = "); _rdi.print(); printf("\n");
4863     printf("rsi  = "); _rsi.print(); printf("\n");
4864     printf("rbp,  = "); _rbp.print(); printf("\n");
4865     printf("rsp  = "); _rsp.print(); printf("\n");
4866     printf("\n");
4867     // control registers
4868     printf("flgs = "); _eflags.print(); printf("\n");
4869   }
4870 };
4871 
4872 
4873 class CPU_State {
4874  public:
4875   FPU_State _fpu_state;
4876   IU_State  _iu_state;
4877 
4878   void print() const {
4879     printf("--------------------------------------------------\n");
4880     _iu_state .print();
4881     printf("\n");
4882     _fpu_state.print();
4883     printf("--------------------------------------------------\n");
4884   }
4885 
4886 };
4887 
4888 
4889 static void _print_CPU_state(CPU_State* state) {
4890   state->print();
4891 };
4892 
4893 
4894 void MacroAssembler::print_CPU_state() {
4895   push_CPU_state();
4896   push(rsp);                // pass CPU state
4897   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
4898   addptr(rsp, wordSize);       // discard argument
4899   pop_CPU_state();
4900 }
4901 
4902 
4903 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
4904   static int counter = 0;
4905   FPU_State* fs = &state->_fpu_state;
4906   counter++;
4907   // For leaf calls, only verify that the top few elements remain empty.
4908   // We only need 1 empty at the top for C2 code.
4909   if( stack_depth < 0 ) {
4910     if( fs->tag_for_st(7) != 3 ) {
4911       printf("FPR7 not empty\n");
4912       state->print();
4913       assert(false, "error");
4914       return false;
4915     }
4916     return true;                // All other stack states do not matter
4917   }
4918 
4919   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
4920          "bad FPU control word");
4921 
4922   // compute stack depth
4923   int i = 0;
4924   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
4925   int d = i;
4926   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
4927   // verify findings
4928   if (i != FPU_State::number_of_registers) {
4929     // stack not contiguous
4930     printf("%s: stack not contiguous at ST%d\n", s, i);
4931     state->print();
4932     assert(false, "error");
4933     return false;
4934   }
4935   // check if computed stack depth corresponds to expected stack depth
4936   if (stack_depth < 0) {
4937     // expected stack depth is -stack_depth or less
4938     if (d > -stack_depth) {
4939       // too many elements on the stack
4940       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
4941       state->print();
4942       assert(false, "error");
4943       return false;
4944     }
4945   } else {
4946     // expected stack depth is stack_depth
4947     if (d != stack_depth) {
4948       // wrong stack depth
4949       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
4950       state->print();
4951       assert(false, "error");
4952       return false;
4953     }
4954   }
4955   // everything is cool
4956   return true;
4957 }
4958 
4959 
4960 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
4961   if (!VerifyFPU) return;
4962   push_CPU_state();
4963   push(rsp);                // pass CPU state
4964   ExternalAddress msg((address) s);
4965   // pass message string s
4966   pushptr(msg.addr());
4967   push(stack_depth);        // pass stack depth
4968   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
4969   addptr(rsp, 3 * wordSize);   // discard arguments
4970   // check for error
4971   { Label L;
4972     testl(rax, rax);
4973     jcc(Assembler::notZero, L);
4974     int3();                  // break if error condition
4975     bind(L);
4976   }
4977   pop_CPU_state();
4978 }
4979 
4980 void MacroAssembler::restore_cpu_control_state_after_jni() {
4981   // Either restore the MXCSR register after returning from the JNI Call
4982   // or verify that it wasn't changed (with -Xcheck:jni flag).
4983   if (VM_Version::supports_sse()) {
4984     if (RestoreMXCSROnJNICalls) {
4985       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
4986     } else if (CheckJNICalls) {
4987       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
4988     }
4989   }
4990   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
4991   vzeroupper();
4992   // Reset k1 to 0xffff.
4993 
4994 #ifdef COMPILER2
4995   if (PostLoopMultiversioning && VM_Version::supports_evex()) {
4996     push(rcx);
4997     movl(rcx, 0xffff);
4998     kmovwl(k1, rcx);
4999     pop(rcx);
5000   }
5001 #endif // COMPILER2
5002 
5003 #ifndef _LP64
5004   // Either restore the x87 floating pointer control word after returning
5005   // from the JNI call or verify that it wasn't changed.
5006   if (CheckJNICalls) {
5007     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
5008   }
5009 #endif // _LP64
5010 }
5011 
5012 // ((OopHandle)result).resolve();
5013 void MacroAssembler::resolve_oop_handle(Register result, Register tmp) {
5014   assert_different_registers(result, tmp);
5015 
5016   // Only 64 bit platforms support GCs that require a tmp register
5017   // Only IN_HEAP loads require a thread_tmp register
5018   // OopHandle::resolve is an indirection like jobject.
5019   access_load_at(T_OBJECT, IN_NATIVE,
5020                  result, Address(result, 0), tmp, /*tmp_thread*/noreg);
5021 }
5022 
5023 void MacroAssembler::load_mirror(Register mirror, Register method, Register tmp) {
5024   // get mirror
5025   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
5026   movptr(mirror, Address(method, Method::const_offset()));
5027   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
5028   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
5029   movptr(mirror, Address(mirror, mirror_offset));
5030   resolve_oop_handle(mirror, tmp);
5031 }
5032 
5033 void MacroAssembler::load_klass(Register dst, Register src) {
5034 #ifdef _LP64
5035   if (UseCompressedClassPointers) {
5036     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5037     decode_klass_not_null(dst);
5038   } else
5039 #endif
5040     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5041 }
5042 
5043 void MacroAssembler::load_prototype_header(Register dst, Register src) {
5044   load_klass(dst, src);
5045   movptr(dst, Address(dst, Klass::prototype_header_offset()));
5046 }
5047 
5048 void MacroAssembler::store_klass(Register dst, Register src) {
5049 #ifdef _LP64
5050   if (UseCompressedClassPointers) {
5051     encode_klass_not_null(src);
5052     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
5053   } else
5054 #endif
5055     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
5056 }
5057 
5058 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators, Register dst, Address src,
5059                                     Register tmp1, Register thread_tmp) {
5060   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5061   decorators = AccessInternal::decorator_fixup(decorators);
5062   bool as_raw = (decorators & AS_RAW) != 0;
5063   if (as_raw) {
5064     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
5065   } else {
5066     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
5067   }
5068 }
5069 
5070 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators, Address dst, Register src,
5071                                      Register tmp1, Register tmp2) {
5072   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5073   decorators = AccessInternal::decorator_fixup(decorators);
5074   bool as_raw = (decorators & AS_RAW) != 0;
5075   if (as_raw) {
5076     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, tmp2);
5077   } else {
5078     bs->store_at(this, decorators, type, dst, src, tmp1, tmp2);
5079   }
5080 }
5081 
5082 void MacroAssembler::resolve(DecoratorSet decorators, Register obj) {
5083   // Use stronger ACCESS_WRITE|ACCESS_READ by default.
5084   if ((decorators & (ACCESS_READ | ACCESS_WRITE)) == 0) {
5085     decorators |= ACCESS_READ | ACCESS_WRITE;
5086   }
5087   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5088   return bs->resolve(this, decorators, obj);
5089 }
5090 
5091 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
5092                                    Register thread_tmp, DecoratorSet decorators) {
5093   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
5094 }
5095 
5096 // Doesn't do verfication, generates fixed size code
5097 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
5098                                             Register thread_tmp, DecoratorSet decorators) {
5099   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
5100 }
5101 
5102 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
5103                                     Register tmp2, DecoratorSet decorators) {
5104   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
5105 }
5106 
5107 // Used for storing NULLs.
5108 void MacroAssembler::store_heap_oop_null(Address dst) {
5109   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg);
5110 }
5111 
5112 #ifdef _LP64
5113 void MacroAssembler::store_klass_gap(Register dst, Register src) {
5114   if (UseCompressedClassPointers) {
5115     // Store to klass gap in destination
5116     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
5117   }
5118 }
5119 
5120 #ifdef ASSERT
5121 void MacroAssembler::verify_heapbase(const char* msg) {
5122   assert (UseCompressedOops, "should be compressed");
5123   assert (Universe::heap() != NULL, "java heap should be initialized");
5124   if (CheckCompressedOops) {
5125     Label ok;
5126     push(rscratch1); // cmpptr trashes rscratch1
5127     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
5128     jcc(Assembler::equal, ok);
5129     STOP(msg);
5130     bind(ok);
5131     pop(rscratch1);
5132   }
5133 }
5134 #endif
5135 
5136 // Algorithm must match oop.inline.hpp encode_heap_oop.
5137 void MacroAssembler::encode_heap_oop(Register r) {
5138 #ifdef ASSERT
5139   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
5140 #endif
5141   verify_oop(r, "broken oop in encode_heap_oop");
5142   if (Universe::narrow_oop_base() == NULL) {
5143     if (Universe::narrow_oop_shift() != 0) {
5144       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5145       shrq(r, LogMinObjAlignmentInBytes);
5146     }
5147     return;
5148   }
5149   testq(r, r);
5150   cmovq(Assembler::equal, r, r12_heapbase);
5151   subq(r, r12_heapbase);
5152   shrq(r, LogMinObjAlignmentInBytes);
5153 }
5154 
5155 void MacroAssembler::encode_heap_oop_not_null(Register r) {
5156 #ifdef ASSERT
5157   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
5158   if (CheckCompressedOops) {
5159     Label ok;
5160     testq(r, r);
5161     jcc(Assembler::notEqual, ok);
5162     STOP("null oop passed to encode_heap_oop_not_null");
5163     bind(ok);
5164   }
5165 #endif
5166   verify_oop(r, "broken oop in encode_heap_oop_not_null");
5167   if (Universe::narrow_oop_base() != NULL) {
5168     subq(r, r12_heapbase);
5169   }
5170   if (Universe::narrow_oop_shift() != 0) {
5171     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5172     shrq(r, LogMinObjAlignmentInBytes);
5173   }
5174 }
5175 
5176 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
5177 #ifdef ASSERT
5178   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
5179   if (CheckCompressedOops) {
5180     Label ok;
5181     testq(src, src);
5182     jcc(Assembler::notEqual, ok);
5183     STOP("null oop passed to encode_heap_oop_not_null2");
5184     bind(ok);
5185   }
5186 #endif
5187   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
5188   if (dst != src) {
5189     movq(dst, src);
5190   }
5191   if (Universe::narrow_oop_base() != NULL) {
5192     subq(dst, r12_heapbase);
5193   }
5194   if (Universe::narrow_oop_shift() != 0) {
5195     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5196     shrq(dst, LogMinObjAlignmentInBytes);
5197   }
5198 }
5199 
5200 void  MacroAssembler::decode_heap_oop(Register r) {
5201 #ifdef ASSERT
5202   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
5203 #endif
5204   if (Universe::narrow_oop_base() == NULL) {
5205     if (Universe::narrow_oop_shift() != 0) {
5206       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5207       shlq(r, LogMinObjAlignmentInBytes);
5208     }
5209   } else {
5210     Label done;
5211     shlq(r, LogMinObjAlignmentInBytes);
5212     jccb(Assembler::equal, done);
5213     addq(r, r12_heapbase);
5214     bind(done);
5215   }
5216   verify_oop(r, "broken oop in decode_heap_oop");
5217 }
5218 
5219 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
5220   // Note: it will change flags
5221   assert (UseCompressedOops, "should only be used for compressed headers");
5222   assert (Universe::heap() != NULL, "java heap should be initialized");
5223   // Cannot assert, unverified entry point counts instructions (see .ad file)
5224   // vtableStubs also counts instructions in pd_code_size_limit.
5225   // Also do not verify_oop as this is called by verify_oop.
5226   if (Universe::narrow_oop_shift() != 0) {
5227     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5228     shlq(r, LogMinObjAlignmentInBytes);
5229     if (Universe::narrow_oop_base() != NULL) {
5230       addq(r, r12_heapbase);
5231     }
5232   } else {
5233     assert (Universe::narrow_oop_base() == NULL, "sanity");
5234   }
5235 }
5236 
5237 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
5238   // Note: it will change flags
5239   assert (UseCompressedOops, "should only be used for compressed headers");
5240   assert (Universe::heap() != NULL, "java heap should be initialized");
5241   // Cannot assert, unverified entry point counts instructions (see .ad file)
5242   // vtableStubs also counts instructions in pd_code_size_limit.
5243   // Also do not verify_oop as this is called by verify_oop.
5244   if (Universe::narrow_oop_shift() != 0) {
5245     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5246     if (LogMinObjAlignmentInBytes == Address::times_8) {
5247       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
5248     } else {
5249       if (dst != src) {
5250         movq(dst, src);
5251       }
5252       shlq(dst, LogMinObjAlignmentInBytes);
5253       if (Universe::narrow_oop_base() != NULL) {
5254         addq(dst, r12_heapbase);
5255       }
5256     }
5257   } else {
5258     assert (Universe::narrow_oop_base() == NULL, "sanity");
5259     if (dst != src) {
5260       movq(dst, src);
5261     }
5262   }
5263 }
5264 
5265 void MacroAssembler::encode_klass_not_null(Register r) {
5266   if (Universe::narrow_klass_base() != NULL) {
5267     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
5268     assert(r != r12_heapbase, "Encoding a klass in r12");
5269     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
5270     subq(r, r12_heapbase);
5271   }
5272   if (Universe::narrow_klass_shift() != 0) {
5273     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
5274     shrq(r, LogKlassAlignmentInBytes);
5275   }
5276   if (Universe::narrow_klass_base() != NULL) {
5277     reinit_heapbase();
5278   }
5279 }
5280 
5281 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
5282   if (dst == src) {
5283     encode_klass_not_null(src);
5284   } else {
5285     if (Universe::narrow_klass_base() != NULL) {
5286       mov64(dst, (int64_t)Universe::narrow_klass_base());
5287       negq(dst);
5288       addq(dst, src);
5289     } else {
5290       movptr(dst, src);
5291     }
5292     if (Universe::narrow_klass_shift() != 0) {
5293       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
5294       shrq(dst, LogKlassAlignmentInBytes);
5295     }
5296   }
5297 }
5298 
5299 // Function instr_size_for_decode_klass_not_null() counts the instructions
5300 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
5301 // when (Universe::heap() != NULL).  Hence, if the instructions they
5302 // generate change, then this method needs to be updated.
5303 int MacroAssembler::instr_size_for_decode_klass_not_null() {
5304   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
5305   if (Universe::narrow_klass_base() != NULL) {
5306     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
5307     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
5308   } else {
5309     // longest load decode klass function, mov64, leaq
5310     return 16;
5311   }
5312 }
5313 
5314 // !!! If the instructions that get generated here change then function
5315 // instr_size_for_decode_klass_not_null() needs to get updated.
5316 void  MacroAssembler::decode_klass_not_null(Register r) {
5317   // Note: it will change flags
5318   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5319   assert(r != r12_heapbase, "Decoding a klass in r12");
5320   // Cannot assert, unverified entry point counts instructions (see .ad file)
5321   // vtableStubs also counts instructions in pd_code_size_limit.
5322   // Also do not verify_oop as this is called by verify_oop.
5323   if (Universe::narrow_klass_shift() != 0) {
5324     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
5325     shlq(r, LogKlassAlignmentInBytes);
5326   }
5327   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
5328   if (Universe::narrow_klass_base() != NULL) {
5329     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
5330     addq(r, r12_heapbase);
5331     reinit_heapbase();
5332   }
5333 }
5334 
5335 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
5336   // Note: it will change flags
5337   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5338   if (dst == src) {
5339     decode_klass_not_null(dst);
5340   } else {
5341     // Cannot assert, unverified entry point counts instructions (see .ad file)
5342     // vtableStubs also counts instructions in pd_code_size_limit.
5343     // Also do not verify_oop as this is called by verify_oop.
5344     mov64(dst, (int64_t)Universe::narrow_klass_base());
5345     if (Universe::narrow_klass_shift() != 0) {
5346       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
5347       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
5348       leaq(dst, Address(dst, src, Address::times_8, 0));
5349     } else {
5350       addq(dst, src);
5351     }
5352   }
5353 }
5354 
5355 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
5356   assert (UseCompressedOops, "should only be used for compressed headers");
5357   assert (Universe::heap() != NULL, "java heap should be initialized");
5358   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5359   int oop_index = oop_recorder()->find_index(obj);
5360   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5361   mov_narrow_oop(dst, oop_index, rspec);
5362 }
5363 
5364 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
5365   assert (UseCompressedOops, "should only be used for compressed headers");
5366   assert (Universe::heap() != NULL, "java heap should be initialized");
5367   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5368   int oop_index = oop_recorder()->find_index(obj);
5369   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5370   mov_narrow_oop(dst, oop_index, rspec);
5371 }
5372 
5373 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
5374   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5375   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5376   int klass_index = oop_recorder()->find_index(k);
5377   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5378   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
5379 }
5380 
5381 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
5382   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5383   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5384   int klass_index = oop_recorder()->find_index(k);
5385   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5386   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
5387 }
5388 
5389 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
5390   assert (UseCompressedOops, "should only be used for compressed headers");
5391   assert (Universe::heap() != NULL, "java heap should be initialized");
5392   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5393   int oop_index = oop_recorder()->find_index(obj);
5394   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5395   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
5396 }
5397 
5398 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
5399   assert (UseCompressedOops, "should only be used for compressed headers");
5400   assert (Universe::heap() != NULL, "java heap should be initialized");
5401   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5402   int oop_index = oop_recorder()->find_index(obj);
5403   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5404   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
5405 }
5406 
5407 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
5408   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5409   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5410   int klass_index = oop_recorder()->find_index(k);
5411   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5412   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
5413 }
5414 
5415 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
5416   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5417   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5418   int klass_index = oop_recorder()->find_index(k);
5419   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5420   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
5421 }
5422 
5423 void MacroAssembler::reinit_heapbase() {
5424   if (UseCompressedOops || UseCompressedClassPointers) {
5425     if (Universe::heap() != NULL) {
5426       if (Universe::narrow_oop_base() == NULL) {
5427         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
5428       } else {
5429         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
5430       }
5431     } else {
5432       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
5433     }
5434   }
5435 }
5436 
5437 #endif // _LP64
5438 
5439 // C2 compiled method's prolog code.
5440 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b, bool is_stub) {
5441 
5442   // WARNING: Initial instruction MUST be 5 bytes or longer so that
5443   // NativeJump::patch_verified_entry will be able to patch out the entry
5444   // code safely. The push to verify stack depth is ok at 5 bytes,
5445   // the frame allocation can be either 3 or 6 bytes. So if we don't do
5446   // stack bang then we must use the 6 byte frame allocation even if
5447   // we have no frame. :-(
5448   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
5449 
5450   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
5451   // Remove word for return addr
5452   framesize -= wordSize;
5453   stack_bang_size -= wordSize;
5454 
5455   // Calls to C2R adapters often do not accept exceptional returns.
5456   // We require that their callers must bang for them.  But be careful, because
5457   // some VM calls (such as call site linkage) can use several kilobytes of
5458   // stack.  But the stack safety zone should account for that.
5459   // See bugs 4446381, 4468289, 4497237.
5460   if (stack_bang_size > 0) {
5461     generate_stack_overflow_check(stack_bang_size);
5462 
5463     // We always push rbp, so that on return to interpreter rbp, will be
5464     // restored correctly and we can correct the stack.
5465     push(rbp);
5466     // Save caller's stack pointer into RBP if the frame pointer is preserved.
5467     if (PreserveFramePointer) {
5468       mov(rbp, rsp);
5469     }
5470     // Remove word for ebp
5471     framesize -= wordSize;
5472 
5473     // Create frame
5474     if (framesize) {
5475       subptr(rsp, framesize);
5476     }
5477   } else {
5478     // Create frame (force generation of a 4 byte immediate value)
5479     subptr_imm32(rsp, framesize);
5480 
5481     // Save RBP register now.
5482     framesize -= wordSize;
5483     movptr(Address(rsp, framesize), rbp);
5484     // Save caller's stack pointer into RBP if the frame pointer is preserved.
5485     if (PreserveFramePointer) {
5486       movptr(rbp, rsp);
5487       if (framesize > 0) {
5488         addptr(rbp, framesize);
5489       }
5490     }
5491   }
5492 
5493   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
5494     framesize -= wordSize;
5495     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
5496   }
5497 
5498 #ifndef _LP64
5499   // If method sets FPU control word do it now
5500   if (fp_mode_24b) {
5501     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
5502   }
5503   if (UseSSE >= 2 && VerifyFPU) {
5504     verify_FPU(0, "FPU stack must be clean on entry");
5505   }
5506 #endif
5507 
5508 #ifdef ASSERT
5509   if (VerifyStackAtCalls) {
5510     Label L;
5511     push(rax);
5512     mov(rax, rsp);
5513     andptr(rax, StackAlignmentInBytes-1);
5514     cmpptr(rax, StackAlignmentInBytes-wordSize);
5515     pop(rax);
5516     jcc(Assembler::equal, L);
5517     STOP("Stack is not properly aligned!");
5518     bind(L);
5519   }
5520 #endif
5521 
5522   if (!is_stub) {
5523     BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5524     bs->nmethod_entry_barrier(this);
5525   }
5526 }
5527 
5528 // clear memory of size 'cnt' qwords, starting at 'base' using XMM/YMM registers
5529 void MacroAssembler::xmm_clear_mem(Register base, Register cnt, XMMRegister xtmp) {
5530   // cnt - number of qwords (8-byte words).
5531   // base - start address, qword aligned.
5532   Label L_zero_64_bytes, L_loop, L_sloop, L_tail, L_end;
5533   if (UseAVX >= 2) {
5534     vpxor(xtmp, xtmp, xtmp, AVX_256bit);
5535   } else {
5536     pxor(xtmp, xtmp);
5537   }
5538   jmp(L_zero_64_bytes);
5539 
5540   BIND(L_loop);
5541   if (UseAVX >= 2) {
5542     vmovdqu(Address(base,  0), xtmp);
5543     vmovdqu(Address(base, 32), xtmp);
5544   } else {
5545     movdqu(Address(base,  0), xtmp);
5546     movdqu(Address(base, 16), xtmp);
5547     movdqu(Address(base, 32), xtmp);
5548     movdqu(Address(base, 48), xtmp);
5549   }
5550   addptr(base, 64);
5551 
5552   BIND(L_zero_64_bytes);
5553   subptr(cnt, 8);
5554   jccb(Assembler::greaterEqual, L_loop);
5555   addptr(cnt, 4);
5556   jccb(Assembler::less, L_tail);
5557   // Copy trailing 32 bytes
5558   if (UseAVX >= 2) {
5559     vmovdqu(Address(base, 0), xtmp);
5560   } else {
5561     movdqu(Address(base,  0), xtmp);
5562     movdqu(Address(base, 16), xtmp);
5563   }
5564   addptr(base, 32);
5565   subptr(cnt, 4);
5566 
5567   BIND(L_tail);
5568   addptr(cnt, 4);
5569   jccb(Assembler::lessEqual, L_end);
5570   decrement(cnt);
5571 
5572   BIND(L_sloop);
5573   movq(Address(base, 0), xtmp);
5574   addptr(base, 8);
5575   decrement(cnt);
5576   jccb(Assembler::greaterEqual, L_sloop);
5577   BIND(L_end);
5578 }
5579 
5580 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, XMMRegister xtmp, bool is_large) {
5581   // cnt - number of qwords (8-byte words).
5582   // base - start address, qword aligned.
5583   // is_large - if optimizers know cnt is larger than InitArrayShortSize
5584   assert(base==rdi, "base register must be edi for rep stos");
5585   assert(tmp==rax,   "tmp register must be eax for rep stos");
5586   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
5587   assert(InitArrayShortSize % BytesPerLong == 0,
5588     "InitArrayShortSize should be the multiple of BytesPerLong");
5589 
5590   Label DONE;
5591 
5592   if (!is_large || !UseXMMForObjInit) {
5593     xorptr(tmp, tmp);
5594   }
5595 
5596   if (!is_large) {
5597     Label LOOP, LONG;
5598     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
5599     jccb(Assembler::greater, LONG);
5600 
5601     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
5602 
5603     decrement(cnt);
5604     jccb(Assembler::negative, DONE); // Zero length
5605 
5606     // Use individual pointer-sized stores for small counts:
5607     BIND(LOOP);
5608     movptr(Address(base, cnt, Address::times_ptr), tmp);
5609     decrement(cnt);
5610     jccb(Assembler::greaterEqual, LOOP);
5611     jmpb(DONE);
5612 
5613     BIND(LONG);
5614   }
5615 
5616   // Use longer rep-prefixed ops for non-small counts:
5617   if (UseFastStosb) {
5618     shlptr(cnt, 3); // convert to number of bytes
5619     rep_stosb();
5620   } else if (UseXMMForObjInit) {
5621     movptr(tmp, base);
5622     xmm_clear_mem(tmp, cnt, xtmp);
5623   } else {
5624     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
5625     rep_stos();
5626   }
5627 
5628   BIND(DONE);
5629 }
5630 
5631 #ifdef COMPILER2
5632 
5633 // IndexOf for constant substrings with size >= 8 chars
5634 // which don't need to be loaded through stack.
5635 void MacroAssembler::string_indexofC8(Register str1, Register str2,
5636                                       Register cnt1, Register cnt2,
5637                                       int int_cnt2,  Register result,
5638                                       XMMRegister vec, Register tmp,
5639                                       int ae) {
5640   ShortBranchVerifier sbv(this);
5641   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
5642   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
5643 
5644   // This method uses the pcmpestri instruction with bound registers
5645   //   inputs:
5646   //     xmm - substring
5647   //     rax - substring length (elements count)
5648   //     mem - scanned string
5649   //     rdx - string length (elements count)
5650   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
5651   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
5652   //   outputs:
5653   //     rcx - matched index in string
5654   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
5655   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
5656   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
5657   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
5658   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
5659 
5660   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
5661         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
5662         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
5663 
5664   // Note, inline_string_indexOf() generates checks:
5665   // if (substr.count > string.count) return -1;
5666   // if (substr.count == 0) return 0;
5667   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
5668 
5669   // Load substring.
5670   if (ae == StrIntrinsicNode::UL) {
5671     pmovzxbw(vec, Address(str2, 0));
5672   } else {
5673     movdqu(vec, Address(str2, 0));
5674   }
5675   movl(cnt2, int_cnt2);
5676   movptr(result, str1); // string addr
5677 
5678   if (int_cnt2 > stride) {
5679     jmpb(SCAN_TO_SUBSTR);
5680 
5681     // Reload substr for rescan, this code
5682     // is executed only for large substrings (> 8 chars)
5683     bind(RELOAD_SUBSTR);
5684     if (ae == StrIntrinsicNode::UL) {
5685       pmovzxbw(vec, Address(str2, 0));
5686     } else {
5687       movdqu(vec, Address(str2, 0));
5688     }
5689     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
5690 
5691     bind(RELOAD_STR);
5692     // We came here after the beginning of the substring was
5693     // matched but the rest of it was not so we need to search
5694     // again. Start from the next element after the previous match.
5695 
5696     // cnt2 is number of substring reminding elements and
5697     // cnt1 is number of string reminding elements when cmp failed.
5698     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
5699     subl(cnt1, cnt2);
5700     addl(cnt1, int_cnt2);
5701     movl(cnt2, int_cnt2); // Now restore cnt2
5702 
5703     decrementl(cnt1);     // Shift to next element
5704     cmpl(cnt1, cnt2);
5705     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
5706 
5707     addptr(result, (1<<scale1));
5708 
5709   } // (int_cnt2 > 8)
5710 
5711   // Scan string for start of substr in 16-byte vectors
5712   bind(SCAN_TO_SUBSTR);
5713   pcmpestri(vec, Address(result, 0), mode);
5714   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
5715   subl(cnt1, stride);
5716   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
5717   cmpl(cnt1, cnt2);
5718   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
5719   addptr(result, 16);
5720   jmpb(SCAN_TO_SUBSTR);
5721 
5722   // Found a potential substr
5723   bind(FOUND_CANDIDATE);
5724   // Matched whole vector if first element matched (tmp(rcx) == 0).
5725   if (int_cnt2 == stride) {
5726     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
5727   } else { // int_cnt2 > 8
5728     jccb(Assembler::overflow, FOUND_SUBSTR);
5729   }
5730   // After pcmpestri tmp(rcx) contains matched element index
5731   // Compute start addr of substr
5732   lea(result, Address(result, tmp, scale1));
5733 
5734   // Make sure string is still long enough
5735   subl(cnt1, tmp);
5736   cmpl(cnt1, cnt2);
5737   if (int_cnt2 == stride) {
5738     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
5739   } else { // int_cnt2 > 8
5740     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
5741   }
5742   // Left less then substring.
5743 
5744   bind(RET_NOT_FOUND);
5745   movl(result, -1);
5746   jmp(EXIT);
5747 
5748   if (int_cnt2 > stride) {
5749     // This code is optimized for the case when whole substring
5750     // is matched if its head is matched.
5751     bind(MATCH_SUBSTR_HEAD);
5752     pcmpestri(vec, Address(result, 0), mode);
5753     // Reload only string if does not match
5754     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
5755 
5756     Label CONT_SCAN_SUBSTR;
5757     // Compare the rest of substring (> 8 chars).
5758     bind(FOUND_SUBSTR);
5759     // First 8 chars are already matched.
5760     negptr(cnt2);
5761     addptr(cnt2, stride);
5762 
5763     bind(SCAN_SUBSTR);
5764     subl(cnt1, stride);
5765     cmpl(cnt2, -stride); // Do not read beyond substring
5766     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
5767     // Back-up strings to avoid reading beyond substring:
5768     // cnt1 = cnt1 - cnt2 + 8
5769     addl(cnt1, cnt2); // cnt2 is negative
5770     addl(cnt1, stride);
5771     movl(cnt2, stride); negptr(cnt2);
5772     bind(CONT_SCAN_SUBSTR);
5773     if (int_cnt2 < (int)G) {
5774       int tail_off1 = int_cnt2<<scale1;
5775       int tail_off2 = int_cnt2<<scale2;
5776       if (ae == StrIntrinsicNode::UL) {
5777         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
5778       } else {
5779         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
5780       }
5781       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
5782     } else {
5783       // calculate index in register to avoid integer overflow (int_cnt2*2)
5784       movl(tmp, int_cnt2);
5785       addptr(tmp, cnt2);
5786       if (ae == StrIntrinsicNode::UL) {
5787         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
5788       } else {
5789         movdqu(vec, Address(str2, tmp, scale2, 0));
5790       }
5791       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
5792     }
5793     // Need to reload strings pointers if not matched whole vector
5794     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
5795     addptr(cnt2, stride);
5796     jcc(Assembler::negative, SCAN_SUBSTR);
5797     // Fall through if found full substring
5798 
5799   } // (int_cnt2 > 8)
5800 
5801   bind(RET_FOUND);
5802   // Found result if we matched full small substring.
5803   // Compute substr offset
5804   subptr(result, str1);
5805   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
5806     shrl(result, 1); // index
5807   }
5808   bind(EXIT);
5809 
5810 } // string_indexofC8
5811 
5812 // Small strings are loaded through stack if they cross page boundary.
5813 void MacroAssembler::string_indexof(Register str1, Register str2,
5814                                     Register cnt1, Register cnt2,
5815                                     int int_cnt2,  Register result,
5816                                     XMMRegister vec, Register tmp,
5817                                     int ae) {
5818   ShortBranchVerifier sbv(this);
5819   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
5820   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
5821 
5822   //
5823   // int_cnt2 is length of small (< 8 chars) constant substring
5824   // or (-1) for non constant substring in which case its length
5825   // is in cnt2 register.
5826   //
5827   // Note, inline_string_indexOf() generates checks:
5828   // if (substr.count > string.count) return -1;
5829   // if (substr.count == 0) return 0;
5830   //
5831   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
5832   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
5833   // This method uses the pcmpestri instruction with bound registers
5834   //   inputs:
5835   //     xmm - substring
5836   //     rax - substring length (elements count)
5837   //     mem - scanned string
5838   //     rdx - string length (elements count)
5839   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
5840   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
5841   //   outputs:
5842   //     rcx - matched index in string
5843   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
5844   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
5845   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
5846   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
5847 
5848   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
5849         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
5850         FOUND_CANDIDATE;
5851 
5852   { //========================================================
5853     // We don't know where these strings are located
5854     // and we can't read beyond them. Load them through stack.
5855     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
5856 
5857     movptr(tmp, rsp); // save old SP
5858 
5859     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
5860       if (int_cnt2 == (1>>scale2)) { // One byte
5861         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
5862         load_unsigned_byte(result, Address(str2, 0));
5863         movdl(vec, result); // move 32 bits
5864       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
5865         // Not enough header space in 32-bit VM: 12+3 = 15.
5866         movl(result, Address(str2, -1));
5867         shrl(result, 8);
5868         movdl(vec, result); // move 32 bits
5869       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
5870         load_unsigned_short(result, Address(str2, 0));
5871         movdl(vec, result); // move 32 bits
5872       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
5873         movdl(vec, Address(str2, 0)); // move 32 bits
5874       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
5875         movq(vec, Address(str2, 0));  // move 64 bits
5876       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
5877         // Array header size is 12 bytes in 32-bit VM
5878         // + 6 bytes for 3 chars == 18 bytes,
5879         // enough space to load vec and shift.
5880         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
5881         if (ae == StrIntrinsicNode::UL) {
5882           int tail_off = int_cnt2-8;
5883           pmovzxbw(vec, Address(str2, tail_off));
5884           psrldq(vec, -2*tail_off);
5885         }
5886         else {
5887           int tail_off = int_cnt2*(1<<scale2);
5888           movdqu(vec, Address(str2, tail_off-16));
5889           psrldq(vec, 16-tail_off);
5890         }
5891       }
5892     } else { // not constant substring
5893       cmpl(cnt2, stride);
5894       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
5895 
5896       // We can read beyond string if srt+16 does not cross page boundary
5897       // since heaps are aligned and mapped by pages.
5898       assert(os::vm_page_size() < (int)G, "default page should be small");
5899       movl(result, str2); // We need only low 32 bits
5900       andl(result, (os::vm_page_size()-1));
5901       cmpl(result, (os::vm_page_size()-16));
5902       jccb(Assembler::belowEqual, CHECK_STR);
5903 
5904       // Move small strings to stack to allow load 16 bytes into vec.
5905       subptr(rsp, 16);
5906       int stk_offset = wordSize-(1<<scale2);
5907       push(cnt2);
5908 
5909       bind(COPY_SUBSTR);
5910       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
5911         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
5912         movb(Address(rsp, cnt2, scale2, stk_offset), result);
5913       } else if (ae == StrIntrinsicNode::UU) {
5914         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
5915         movw(Address(rsp, cnt2, scale2, stk_offset), result);
5916       }
5917       decrement(cnt2);
5918       jccb(Assembler::notZero, COPY_SUBSTR);
5919 
5920       pop(cnt2);
5921       movptr(str2, rsp);  // New substring address
5922     } // non constant
5923 
5924     bind(CHECK_STR);
5925     cmpl(cnt1, stride);
5926     jccb(Assembler::aboveEqual, BIG_STRINGS);
5927 
5928     // Check cross page boundary.
5929     movl(result, str1); // We need only low 32 bits
5930     andl(result, (os::vm_page_size()-1));
5931     cmpl(result, (os::vm_page_size()-16));
5932     jccb(Assembler::belowEqual, BIG_STRINGS);
5933 
5934     subptr(rsp, 16);
5935     int stk_offset = -(1<<scale1);
5936     if (int_cnt2 < 0) { // not constant
5937       push(cnt2);
5938       stk_offset += wordSize;
5939     }
5940     movl(cnt2, cnt1);
5941 
5942     bind(COPY_STR);
5943     if (ae == StrIntrinsicNode::LL) {
5944       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
5945       movb(Address(rsp, cnt2, scale1, stk_offset), result);
5946     } else {
5947       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
5948       movw(Address(rsp, cnt2, scale1, stk_offset), result);
5949     }
5950     decrement(cnt2);
5951     jccb(Assembler::notZero, COPY_STR);
5952 
5953     if (int_cnt2 < 0) { // not constant
5954       pop(cnt2);
5955     }
5956     movptr(str1, rsp);  // New string address
5957 
5958     bind(BIG_STRINGS);
5959     // Load substring.
5960     if (int_cnt2 < 0) { // -1
5961       if (ae == StrIntrinsicNode::UL) {
5962         pmovzxbw(vec, Address(str2, 0));
5963       } else {
5964         movdqu(vec, Address(str2, 0));
5965       }
5966       push(cnt2);       // substr count
5967       push(str2);       // substr addr
5968       push(str1);       // string addr
5969     } else {
5970       // Small (< 8 chars) constant substrings are loaded already.
5971       movl(cnt2, int_cnt2);
5972     }
5973     push(tmp);  // original SP
5974 
5975   } // Finished loading
5976 
5977   //========================================================
5978   // Start search
5979   //
5980 
5981   movptr(result, str1); // string addr
5982 
5983   if (int_cnt2  < 0) {  // Only for non constant substring
5984     jmpb(SCAN_TO_SUBSTR);
5985 
5986     // SP saved at sp+0
5987     // String saved at sp+1*wordSize
5988     // Substr saved at sp+2*wordSize
5989     // Substr count saved at sp+3*wordSize
5990 
5991     // Reload substr for rescan, this code
5992     // is executed only for large substrings (> 8 chars)
5993     bind(RELOAD_SUBSTR);
5994     movptr(str2, Address(rsp, 2*wordSize));
5995     movl(cnt2, Address(rsp, 3*wordSize));
5996     if (ae == StrIntrinsicNode::UL) {
5997       pmovzxbw(vec, Address(str2, 0));
5998     } else {
5999       movdqu(vec, Address(str2, 0));
6000     }
6001     // We came here after the beginning of the substring was
6002     // matched but the rest of it was not so we need to search
6003     // again. Start from the next element after the previous match.
6004     subptr(str1, result); // Restore counter
6005     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
6006       shrl(str1, 1);
6007     }
6008     addl(cnt1, str1);
6009     decrementl(cnt1);   // Shift to next element
6010     cmpl(cnt1, cnt2);
6011     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6012 
6013     addptr(result, (1<<scale1));
6014   } // non constant
6015 
6016   // Scan string for start of substr in 16-byte vectors
6017   bind(SCAN_TO_SUBSTR);
6018   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6019   pcmpestri(vec, Address(result, 0), mode);
6020   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6021   subl(cnt1, stride);
6022   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6023   cmpl(cnt1, cnt2);
6024   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6025   addptr(result, 16);
6026 
6027   bind(ADJUST_STR);
6028   cmpl(cnt1, stride); // Do not read beyond string
6029   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6030   // Back-up string to avoid reading beyond string.
6031   lea(result, Address(result, cnt1, scale1, -16));
6032   movl(cnt1, stride);
6033   jmpb(SCAN_TO_SUBSTR);
6034 
6035   // Found a potential substr
6036   bind(FOUND_CANDIDATE);
6037   // After pcmpestri tmp(rcx) contains matched element index
6038 
6039   // Make sure string is still long enough
6040   subl(cnt1, tmp);
6041   cmpl(cnt1, cnt2);
6042   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
6043   // Left less then substring.
6044 
6045   bind(RET_NOT_FOUND);
6046   movl(result, -1);
6047   jmp(CLEANUP);
6048 
6049   bind(FOUND_SUBSTR);
6050   // Compute start addr of substr
6051   lea(result, Address(result, tmp, scale1));
6052   if (int_cnt2 > 0) { // Constant substring
6053     // Repeat search for small substring (< 8 chars)
6054     // from new point without reloading substring.
6055     // Have to check that we don't read beyond string.
6056     cmpl(tmp, stride-int_cnt2);
6057     jccb(Assembler::greater, ADJUST_STR);
6058     // Fall through if matched whole substring.
6059   } else { // non constant
6060     assert(int_cnt2 == -1, "should be != 0");
6061 
6062     addl(tmp, cnt2);
6063     // Found result if we matched whole substring.
6064     cmpl(tmp, stride);
6065     jcc(Assembler::lessEqual, RET_FOUND);
6066 
6067     // Repeat search for small substring (<= 8 chars)
6068     // from new point 'str1' without reloading substring.
6069     cmpl(cnt2, stride);
6070     // Have to check that we don't read beyond string.
6071     jccb(Assembler::lessEqual, ADJUST_STR);
6072 
6073     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
6074     // Compare the rest of substring (> 8 chars).
6075     movptr(str1, result);
6076 
6077     cmpl(tmp, cnt2);
6078     // First 8 chars are already matched.
6079     jccb(Assembler::equal, CHECK_NEXT);
6080 
6081     bind(SCAN_SUBSTR);
6082     pcmpestri(vec, Address(str1, 0), mode);
6083     // Need to reload strings pointers if not matched whole vector
6084     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
6085 
6086     bind(CHECK_NEXT);
6087     subl(cnt2, stride);
6088     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
6089     addptr(str1, 16);
6090     if (ae == StrIntrinsicNode::UL) {
6091       addptr(str2, 8);
6092     } else {
6093       addptr(str2, 16);
6094     }
6095     subl(cnt1, stride);
6096     cmpl(cnt2, stride); // Do not read beyond substring
6097     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
6098     // Back-up strings to avoid reading beyond substring.
6099 
6100     if (ae == StrIntrinsicNode::UL) {
6101       lea(str2, Address(str2, cnt2, scale2, -8));
6102       lea(str1, Address(str1, cnt2, scale1, -16));
6103     } else {
6104       lea(str2, Address(str2, cnt2, scale2, -16));
6105       lea(str1, Address(str1, cnt2, scale1, -16));
6106     }
6107     subl(cnt1, cnt2);
6108     movl(cnt2, stride);
6109     addl(cnt1, stride);
6110     bind(CONT_SCAN_SUBSTR);
6111     if (ae == StrIntrinsicNode::UL) {
6112       pmovzxbw(vec, Address(str2, 0));
6113     } else {
6114       movdqu(vec, Address(str2, 0));
6115     }
6116     jmp(SCAN_SUBSTR);
6117 
6118     bind(RET_FOUND_LONG);
6119     movptr(str1, Address(rsp, wordSize));
6120   } // non constant
6121 
6122   bind(RET_FOUND);
6123   // Compute substr offset
6124   subptr(result, str1);
6125   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
6126     shrl(result, 1); // index
6127   }
6128   bind(CLEANUP);
6129   pop(rsp); // restore SP
6130 
6131 } // string_indexof
6132 
6133 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
6134                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
6135   ShortBranchVerifier sbv(this);
6136   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6137 
6138   int stride = 8;
6139 
6140   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
6141         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
6142         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
6143         FOUND_SEQ_CHAR, DONE_LABEL;
6144 
6145   movptr(result, str1);
6146   if (UseAVX >= 2) {
6147     cmpl(cnt1, stride);
6148     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
6149     cmpl(cnt1, 2*stride);
6150     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
6151     movdl(vec1, ch);
6152     vpbroadcastw(vec1, vec1, Assembler::AVX_256bit);
6153     vpxor(vec2, vec2);
6154     movl(tmp, cnt1);
6155     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
6156     andl(cnt1,0x0000000F);  //tail count (in chars)
6157 
6158     bind(SCAN_TO_16_CHAR_LOOP);
6159     vmovdqu(vec3, Address(result, 0));
6160     vpcmpeqw(vec3, vec3, vec1, 1);
6161     vptest(vec2, vec3);
6162     jcc(Assembler::carryClear, FOUND_CHAR);
6163     addptr(result, 32);
6164     subl(tmp, 2*stride);
6165     jcc(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
6166     jmp(SCAN_TO_8_CHAR);
6167     bind(SCAN_TO_8_CHAR_INIT);
6168     movdl(vec1, ch);
6169     pshuflw(vec1, vec1, 0x00);
6170     pshufd(vec1, vec1, 0);
6171     pxor(vec2, vec2);
6172   }
6173   bind(SCAN_TO_8_CHAR);
6174   cmpl(cnt1, stride);
6175   if (UseAVX >= 2) {
6176     jcc(Assembler::less, SCAN_TO_CHAR);
6177   } else {
6178     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
6179     movdl(vec1, ch);
6180     pshuflw(vec1, vec1, 0x00);
6181     pshufd(vec1, vec1, 0);
6182     pxor(vec2, vec2);
6183   }
6184   movl(tmp, cnt1);
6185   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
6186   andl(cnt1,0x00000007);  //tail count (in chars)
6187 
6188   bind(SCAN_TO_8_CHAR_LOOP);
6189   movdqu(vec3, Address(result, 0));
6190   pcmpeqw(vec3, vec1);
6191   ptest(vec2, vec3);
6192   jcc(Assembler::carryClear, FOUND_CHAR);
6193   addptr(result, 16);
6194   subl(tmp, stride);
6195   jcc(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
6196   bind(SCAN_TO_CHAR);
6197   testl(cnt1, cnt1);
6198   jcc(Assembler::zero, RET_NOT_FOUND);
6199   bind(SCAN_TO_CHAR_LOOP);
6200   load_unsigned_short(tmp, Address(result, 0));
6201   cmpl(ch, tmp);
6202   jccb(Assembler::equal, FOUND_SEQ_CHAR);
6203   addptr(result, 2);
6204   subl(cnt1, 1);
6205   jccb(Assembler::zero, RET_NOT_FOUND);
6206   jmp(SCAN_TO_CHAR_LOOP);
6207 
6208   bind(RET_NOT_FOUND);
6209   movl(result, -1);
6210   jmpb(DONE_LABEL);
6211 
6212   bind(FOUND_CHAR);
6213   if (UseAVX >= 2) {
6214     vpmovmskb(tmp, vec3);
6215   } else {
6216     pmovmskb(tmp, vec3);
6217   }
6218   bsfl(ch, tmp);
6219   addl(result, ch);
6220 
6221   bind(FOUND_SEQ_CHAR);
6222   subptr(result, str1);
6223   shrl(result, 1);
6224 
6225   bind(DONE_LABEL);
6226 } // string_indexof_char
6227 
6228 // helper function for string_compare
6229 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
6230                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
6231                                         Address::ScaleFactor scale2, Register index, int ae) {
6232   if (ae == StrIntrinsicNode::LL) {
6233     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
6234     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
6235   } else if (ae == StrIntrinsicNode::UU) {
6236     load_unsigned_short(elem1, Address(str1, index, scale, 0));
6237     load_unsigned_short(elem2, Address(str2, index, scale, 0));
6238   } else {
6239     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
6240     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
6241   }
6242 }
6243 
6244 // Compare strings, used for char[] and byte[].
6245 void MacroAssembler::string_compare(Register str1, Register str2,
6246                                     Register cnt1, Register cnt2, Register result,
6247                                     XMMRegister vec1, int ae) {
6248   ShortBranchVerifier sbv(this);
6249   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
6250   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
6251   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
6252   int stride2x2 = 0x40;
6253   Address::ScaleFactor scale = Address::no_scale;
6254   Address::ScaleFactor scale1 = Address::no_scale;
6255   Address::ScaleFactor scale2 = Address::no_scale;
6256 
6257   if (ae != StrIntrinsicNode::LL) {
6258     stride2x2 = 0x20;
6259   }
6260 
6261   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
6262     shrl(cnt2, 1);
6263   }
6264   // Compute the minimum of the string lengths and the
6265   // difference of the string lengths (stack).
6266   // Do the conditional move stuff
6267   movl(result, cnt1);
6268   subl(cnt1, cnt2);
6269   push(cnt1);
6270   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
6271 
6272   // Is the minimum length zero?
6273   testl(cnt2, cnt2);
6274   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
6275   if (ae == StrIntrinsicNode::LL) {
6276     // Load first bytes
6277     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
6278     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
6279   } else if (ae == StrIntrinsicNode::UU) {
6280     // Load first characters
6281     load_unsigned_short(result, Address(str1, 0));
6282     load_unsigned_short(cnt1, Address(str2, 0));
6283   } else {
6284     load_unsigned_byte(result, Address(str1, 0));
6285     load_unsigned_short(cnt1, Address(str2, 0));
6286   }
6287   subl(result, cnt1);
6288   jcc(Assembler::notZero,  POP_LABEL);
6289 
6290   if (ae == StrIntrinsicNode::UU) {
6291     // Divide length by 2 to get number of chars
6292     shrl(cnt2, 1);
6293   }
6294   cmpl(cnt2, 1);
6295   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
6296 
6297   // Check if the strings start at the same location and setup scale and stride
6298   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6299     cmpptr(str1, str2);
6300     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
6301     if (ae == StrIntrinsicNode::LL) {
6302       scale = Address::times_1;
6303       stride = 16;
6304     } else {
6305       scale = Address::times_2;
6306       stride = 8;
6307     }
6308   } else {
6309     scale1 = Address::times_1;
6310     scale2 = Address::times_2;
6311     // scale not used
6312     stride = 8;
6313   }
6314 
6315   if (UseAVX >= 2 && UseSSE42Intrinsics) {
6316     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
6317     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
6318     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
6319     Label COMPARE_TAIL_LONG;
6320     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
6321 
6322     int pcmpmask = 0x19;
6323     if (ae == StrIntrinsicNode::LL) {
6324       pcmpmask &= ~0x01;
6325     }
6326 
6327     // Setup to compare 16-chars (32-bytes) vectors,
6328     // start from first character again because it has aligned address.
6329     if (ae == StrIntrinsicNode::LL) {
6330       stride2 = 32;
6331     } else {
6332       stride2 = 16;
6333     }
6334     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6335       adr_stride = stride << scale;
6336     } else {
6337       adr_stride1 = 8;  //stride << scale1;
6338       adr_stride2 = 16; //stride << scale2;
6339     }
6340 
6341     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
6342     // rax and rdx are used by pcmpestri as elements counters
6343     movl(result, cnt2);
6344     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
6345     jcc(Assembler::zero, COMPARE_TAIL_LONG);
6346 
6347     // fast path : compare first 2 8-char vectors.
6348     bind(COMPARE_16_CHARS);
6349     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6350       movdqu(vec1, Address(str1, 0));
6351     } else {
6352       pmovzxbw(vec1, Address(str1, 0));
6353     }
6354     pcmpestri(vec1, Address(str2, 0), pcmpmask);
6355     jccb(Assembler::below, COMPARE_INDEX_CHAR);
6356 
6357     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6358       movdqu(vec1, Address(str1, adr_stride));
6359       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
6360     } else {
6361       pmovzxbw(vec1, Address(str1, adr_stride1));
6362       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
6363     }
6364     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
6365     addl(cnt1, stride);
6366 
6367     // Compare the characters at index in cnt1
6368     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
6369     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
6370     subl(result, cnt2);
6371     jmp(POP_LABEL);
6372 
6373     // Setup the registers to start vector comparison loop
6374     bind(COMPARE_WIDE_VECTORS);
6375     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6376       lea(str1, Address(str1, result, scale));
6377       lea(str2, Address(str2, result, scale));
6378     } else {
6379       lea(str1, Address(str1, result, scale1));
6380       lea(str2, Address(str2, result, scale2));
6381     }
6382     subl(result, stride2);
6383     subl(cnt2, stride2);
6384     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
6385     negptr(result);
6386 
6387     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
6388     bind(COMPARE_WIDE_VECTORS_LOOP);
6389 
6390 #ifdef _LP64
6391     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
6392       cmpl(cnt2, stride2x2);
6393       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
6394       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
6395       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
6396 
6397       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
6398       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6399         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
6400         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
6401       } else {
6402         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
6403         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
6404       }
6405       kortestql(k7, k7);
6406       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
6407       addptr(result, stride2x2);  // update since we already compared at this addr
6408       subl(cnt2, stride2x2);      // and sub the size too
6409       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
6410 
6411       vpxor(vec1, vec1);
6412       jmpb(COMPARE_WIDE_TAIL);
6413     }//if (VM_Version::supports_avx512vlbw())
6414 #endif // _LP64
6415 
6416 
6417     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
6418     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6419       vmovdqu(vec1, Address(str1, result, scale));
6420       vpxor(vec1, Address(str2, result, scale));
6421     } else {
6422       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
6423       vpxor(vec1, Address(str2, result, scale2));
6424     }
6425     vptest(vec1, vec1);
6426     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
6427     addptr(result, stride2);
6428     subl(cnt2, stride2);
6429     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
6430     // clean upper bits of YMM registers
6431     vpxor(vec1, vec1);
6432 
6433     // compare wide vectors tail
6434     bind(COMPARE_WIDE_TAIL);
6435     testptr(result, result);
6436     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
6437 
6438     movl(result, stride2);
6439     movl(cnt2, result);
6440     negptr(result);
6441     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
6442 
6443     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
6444     bind(VECTOR_NOT_EQUAL);
6445     // clean upper bits of YMM registers
6446     vpxor(vec1, vec1);
6447     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6448       lea(str1, Address(str1, result, scale));
6449       lea(str2, Address(str2, result, scale));
6450     } else {
6451       lea(str1, Address(str1, result, scale1));
6452       lea(str2, Address(str2, result, scale2));
6453     }
6454     jmp(COMPARE_16_CHARS);
6455 
6456     // Compare tail chars, length between 1 to 15 chars
6457     bind(COMPARE_TAIL_LONG);
6458     movl(cnt2, result);
6459     cmpl(cnt2, stride);
6460     jcc(Assembler::less, COMPARE_SMALL_STR);
6461 
6462     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6463       movdqu(vec1, Address(str1, 0));
6464     } else {
6465       pmovzxbw(vec1, Address(str1, 0));
6466     }
6467     pcmpestri(vec1, Address(str2, 0), pcmpmask);
6468     jcc(Assembler::below, COMPARE_INDEX_CHAR);
6469     subptr(cnt2, stride);
6470     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
6471     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6472       lea(str1, Address(str1, result, scale));
6473       lea(str2, Address(str2, result, scale));
6474     } else {
6475       lea(str1, Address(str1, result, scale1));
6476       lea(str2, Address(str2, result, scale2));
6477     }
6478     negptr(cnt2);
6479     jmpb(WHILE_HEAD_LABEL);
6480 
6481     bind(COMPARE_SMALL_STR);
6482   } else if (UseSSE42Intrinsics) {
6483     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
6484     int pcmpmask = 0x19;
6485     // Setup to compare 8-char (16-byte) vectors,
6486     // start from first character again because it has aligned address.
6487     movl(result, cnt2);
6488     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
6489     if (ae == StrIntrinsicNode::LL) {
6490       pcmpmask &= ~0x01;
6491     }
6492     jcc(Assembler::zero, COMPARE_TAIL);
6493     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6494       lea(str1, Address(str1, result, scale));
6495       lea(str2, Address(str2, result, scale));
6496     } else {
6497       lea(str1, Address(str1, result, scale1));
6498       lea(str2, Address(str2, result, scale2));
6499     }
6500     negptr(result);
6501 
6502     // pcmpestri
6503     //   inputs:
6504     //     vec1- substring
6505     //     rax - negative string length (elements count)
6506     //     mem - scanned string
6507     //     rdx - string length (elements count)
6508     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
6509     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
6510     //   outputs:
6511     //     rcx - first mismatched element index
6512     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
6513 
6514     bind(COMPARE_WIDE_VECTORS);
6515     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6516       movdqu(vec1, Address(str1, result, scale));
6517       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
6518     } else {
6519       pmovzxbw(vec1, Address(str1, result, scale1));
6520       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
6521     }
6522     // After pcmpestri cnt1(rcx) contains mismatched element index
6523 
6524     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
6525     addptr(result, stride);
6526     subptr(cnt2, stride);
6527     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
6528 
6529     // compare wide vectors tail
6530     testptr(result, result);
6531     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
6532 
6533     movl(cnt2, stride);
6534     movl(result, stride);
6535     negptr(result);
6536     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6537       movdqu(vec1, Address(str1, result, scale));
6538       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
6539     } else {
6540       pmovzxbw(vec1, Address(str1, result, scale1));
6541       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
6542     }
6543     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
6544 
6545     // Mismatched characters in the vectors
6546     bind(VECTOR_NOT_EQUAL);
6547     addptr(cnt1, result);
6548     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
6549     subl(result, cnt2);
6550     jmpb(POP_LABEL);
6551 
6552     bind(COMPARE_TAIL); // limit is zero
6553     movl(cnt2, result);
6554     // Fallthru to tail compare
6555   }
6556   // Shift str2 and str1 to the end of the arrays, negate min
6557   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6558     lea(str1, Address(str1, cnt2, scale));
6559     lea(str2, Address(str2, cnt2, scale));
6560   } else {
6561     lea(str1, Address(str1, cnt2, scale1));
6562     lea(str2, Address(str2, cnt2, scale2));
6563   }
6564   decrementl(cnt2);  // first character was compared already
6565   negptr(cnt2);
6566 
6567   // Compare the rest of the elements
6568   bind(WHILE_HEAD_LABEL);
6569   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
6570   subl(result, cnt1);
6571   jccb(Assembler::notZero, POP_LABEL);
6572   increment(cnt2);
6573   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
6574 
6575   // Strings are equal up to min length.  Return the length difference.
6576   bind(LENGTH_DIFF_LABEL);
6577   pop(result);
6578   if (ae == StrIntrinsicNode::UU) {
6579     // Divide diff by 2 to get number of chars
6580     sarl(result, 1);
6581   }
6582   jmpb(DONE_LABEL);
6583 
6584 #ifdef _LP64
6585   if (VM_Version::supports_avx512vlbw()) {
6586 
6587     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
6588 
6589     kmovql(cnt1, k7);
6590     notq(cnt1);
6591     bsfq(cnt2, cnt1);
6592     if (ae != StrIntrinsicNode::LL) {
6593       // Divide diff by 2 to get number of chars
6594       sarl(cnt2, 1);
6595     }
6596     addq(result, cnt2);
6597     if (ae == StrIntrinsicNode::LL) {
6598       load_unsigned_byte(cnt1, Address(str2, result));
6599       load_unsigned_byte(result, Address(str1, result));
6600     } else if (ae == StrIntrinsicNode::UU) {
6601       load_unsigned_short(cnt1, Address(str2, result, scale));
6602       load_unsigned_short(result, Address(str1, result, scale));
6603     } else {
6604       load_unsigned_short(cnt1, Address(str2, result, scale2));
6605       load_unsigned_byte(result, Address(str1, result, scale1));
6606     }
6607     subl(result, cnt1);
6608     jmpb(POP_LABEL);
6609   }//if (VM_Version::supports_avx512vlbw())
6610 #endif // _LP64
6611 
6612   // Discard the stored length difference
6613   bind(POP_LABEL);
6614   pop(cnt1);
6615 
6616   // That's it
6617   bind(DONE_LABEL);
6618   if(ae == StrIntrinsicNode::UL) {
6619     negl(result);
6620   }
6621 
6622 }
6623 
6624 // Search for Non-ASCII character (Negative byte value) in a byte array,
6625 // return true if it has any and false otherwise.
6626 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
6627 //   @HotSpotIntrinsicCandidate
6628 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
6629 //     for (int i = off; i < off + len; i++) {
6630 //       if (ba[i] < 0) {
6631 //         return true;
6632 //       }
6633 //     }
6634 //     return false;
6635 //   }
6636 void MacroAssembler::has_negatives(Register ary1, Register len,
6637   Register result, Register tmp1,
6638   XMMRegister vec1, XMMRegister vec2) {
6639   // rsi: byte array
6640   // rcx: len
6641   // rax: result
6642   ShortBranchVerifier sbv(this);
6643   assert_different_registers(ary1, len, result, tmp1);
6644   assert_different_registers(vec1, vec2);
6645   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
6646 
6647   // len == 0
6648   testl(len, len);
6649   jcc(Assembler::zero, FALSE_LABEL);
6650 
6651   if ((UseAVX > 2) && // AVX512
6652     VM_Version::supports_avx512vlbw() &&
6653     VM_Version::supports_bmi2()) {
6654 
6655     Label test_64_loop, test_tail;
6656     Register tmp3_aliased = len;
6657 
6658     movl(tmp1, len);
6659     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
6660 
6661     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
6662     andl(len, ~(64 - 1));    // vector count (in chars)
6663     jccb(Assembler::zero, test_tail);
6664 
6665     lea(ary1, Address(ary1, len, Address::times_1));
6666     negptr(len);
6667 
6668     bind(test_64_loop);
6669     // Check whether our 64 elements of size byte contain negatives
6670     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
6671     kortestql(k2, k2);
6672     jcc(Assembler::notZero, TRUE_LABEL);
6673 
6674     addptr(len, 64);
6675     jccb(Assembler::notZero, test_64_loop);
6676 
6677 
6678     bind(test_tail);
6679     // bail out when there is nothing to be done
6680     testl(tmp1, -1);
6681     jcc(Assembler::zero, FALSE_LABEL);
6682 
6683     // ~(~0 << len) applied up to two times (for 32-bit scenario)
6684 #ifdef _LP64
6685     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
6686     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
6687     notq(tmp3_aliased);
6688     kmovql(k3, tmp3_aliased);
6689 #else
6690     Label k_init;
6691     jmp(k_init);
6692 
6693     // We could not read 64-bits from a general purpose register thus we move
6694     // data required to compose 64 1's to the instruction stream
6695     // We emit 64 byte wide series of elements from 0..63 which later on would
6696     // be used as a compare targets with tail count contained in tmp1 register.
6697     // Result would be a k register having tmp1 consecutive number or 1
6698     // counting from least significant bit.
6699     address tmp = pc();
6700     emit_int64(0x0706050403020100);
6701     emit_int64(0x0F0E0D0C0B0A0908);
6702     emit_int64(0x1716151413121110);
6703     emit_int64(0x1F1E1D1C1B1A1918);
6704     emit_int64(0x2726252423222120);
6705     emit_int64(0x2F2E2D2C2B2A2928);
6706     emit_int64(0x3736353433323130);
6707     emit_int64(0x3F3E3D3C3B3A3938);
6708 
6709     bind(k_init);
6710     lea(len, InternalAddress(tmp));
6711     // create mask to test for negative byte inside a vector
6712     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
6713     evpcmpgtb(k3, vec1, Address(len, 0), Assembler::AVX_512bit);
6714 
6715 #endif
6716     evpcmpgtb(k2, k3, vec2, Address(ary1, 0), Assembler::AVX_512bit);
6717     ktestq(k2, k3);
6718     jcc(Assembler::notZero, TRUE_LABEL);
6719 
6720     jmp(FALSE_LABEL);
6721   } else {
6722     movl(result, len); // copy
6723 
6724     if (UseAVX == 2 && UseSSE >= 2) {
6725       // With AVX2, use 32-byte vector compare
6726       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
6727 
6728       // Compare 32-byte vectors
6729       andl(result, 0x0000001f);  //   tail count (in bytes)
6730       andl(len, 0xffffffe0);   // vector count (in bytes)
6731       jccb(Assembler::zero, COMPARE_TAIL);
6732 
6733       lea(ary1, Address(ary1, len, Address::times_1));
6734       negptr(len);
6735 
6736       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
6737       movdl(vec2, tmp1);
6738       vpbroadcastd(vec2, vec2, Assembler::AVX_256bit);
6739 
6740       bind(COMPARE_WIDE_VECTORS);
6741       vmovdqu(vec1, Address(ary1, len, Address::times_1));
6742       vptest(vec1, vec2);
6743       jccb(Assembler::notZero, TRUE_LABEL);
6744       addptr(len, 32);
6745       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
6746 
6747       testl(result, result);
6748       jccb(Assembler::zero, FALSE_LABEL);
6749 
6750       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
6751       vptest(vec1, vec2);
6752       jccb(Assembler::notZero, TRUE_LABEL);
6753       jmpb(FALSE_LABEL);
6754 
6755       bind(COMPARE_TAIL); // len is zero
6756       movl(len, result);
6757       // Fallthru to tail compare
6758     } else if (UseSSE42Intrinsics) {
6759       // With SSE4.2, use double quad vector compare
6760       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
6761 
6762       // Compare 16-byte vectors
6763       andl(result, 0x0000000f);  //   tail count (in bytes)
6764       andl(len, 0xfffffff0);   // vector count (in bytes)
6765       jcc(Assembler::zero, COMPARE_TAIL);
6766 
6767       lea(ary1, Address(ary1, len, Address::times_1));
6768       negptr(len);
6769 
6770       movl(tmp1, 0x80808080);
6771       movdl(vec2, tmp1);
6772       pshufd(vec2, vec2, 0);
6773 
6774       bind(COMPARE_WIDE_VECTORS);
6775       movdqu(vec1, Address(ary1, len, Address::times_1));
6776       ptest(vec1, vec2);
6777       jcc(Assembler::notZero, TRUE_LABEL);
6778       addptr(len, 16);
6779       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
6780 
6781       testl(result, result);
6782       jcc(Assembler::zero, FALSE_LABEL);
6783 
6784       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
6785       ptest(vec1, vec2);
6786       jccb(Assembler::notZero, TRUE_LABEL);
6787       jmpb(FALSE_LABEL);
6788 
6789       bind(COMPARE_TAIL); // len is zero
6790       movl(len, result);
6791       // Fallthru to tail compare
6792     }
6793   }
6794   // Compare 4-byte vectors
6795   andl(len, 0xfffffffc); // vector count (in bytes)
6796   jccb(Assembler::zero, COMPARE_CHAR);
6797 
6798   lea(ary1, Address(ary1, len, Address::times_1));
6799   negptr(len);
6800 
6801   bind(COMPARE_VECTORS);
6802   movl(tmp1, Address(ary1, len, Address::times_1));
6803   andl(tmp1, 0x80808080);
6804   jccb(Assembler::notZero, TRUE_LABEL);
6805   addptr(len, 4);
6806   jcc(Assembler::notZero, COMPARE_VECTORS);
6807 
6808   // Compare trailing char (final 2 bytes), if any
6809   bind(COMPARE_CHAR);
6810   testl(result, 0x2);   // tail  char
6811   jccb(Assembler::zero, COMPARE_BYTE);
6812   load_unsigned_short(tmp1, Address(ary1, 0));
6813   andl(tmp1, 0x00008080);
6814   jccb(Assembler::notZero, TRUE_LABEL);
6815   subptr(result, 2);
6816   lea(ary1, Address(ary1, 2));
6817 
6818   bind(COMPARE_BYTE);
6819   testl(result, 0x1);   // tail  byte
6820   jccb(Assembler::zero, FALSE_LABEL);
6821   load_unsigned_byte(tmp1, Address(ary1, 0));
6822   andl(tmp1, 0x00000080);
6823   jccb(Assembler::notEqual, TRUE_LABEL);
6824   jmpb(FALSE_LABEL);
6825 
6826   bind(TRUE_LABEL);
6827   movl(result, 1);   // return true
6828   jmpb(DONE);
6829 
6830   bind(FALSE_LABEL);
6831   xorl(result, result); // return false
6832 
6833   // That's it
6834   bind(DONE);
6835   if (UseAVX >= 2 && UseSSE >= 2) {
6836     // clean upper bits of YMM registers
6837     vpxor(vec1, vec1);
6838     vpxor(vec2, vec2);
6839   }
6840 }
6841 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
6842 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
6843                                    Register limit, Register result, Register chr,
6844                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
6845   ShortBranchVerifier sbv(this);
6846   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
6847 
6848   int length_offset  = arrayOopDesc::length_offset_in_bytes();
6849   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
6850 
6851   if (is_array_equ) {
6852     // Check the input args
6853     cmpoop(ary1, ary2);
6854     jcc(Assembler::equal, TRUE_LABEL);
6855 
6856     // Need additional checks for arrays_equals.
6857     testptr(ary1, ary1);
6858     jcc(Assembler::zero, FALSE_LABEL);
6859     testptr(ary2, ary2);
6860     jcc(Assembler::zero, FALSE_LABEL);
6861 
6862     // Check the lengths
6863     movl(limit, Address(ary1, length_offset));
6864     cmpl(limit, Address(ary2, length_offset));
6865     jcc(Assembler::notEqual, FALSE_LABEL);
6866   }
6867 
6868   // count == 0
6869   testl(limit, limit);
6870   jcc(Assembler::zero, TRUE_LABEL);
6871 
6872   if (is_array_equ) {
6873     // Load array address
6874     lea(ary1, Address(ary1, base_offset));
6875     lea(ary2, Address(ary2, base_offset));
6876   }
6877 
6878   if (is_array_equ && is_char) {
6879     // arrays_equals when used for char[].
6880     shll(limit, 1);      // byte count != 0
6881   }
6882   movl(result, limit); // copy
6883 
6884   if (UseAVX >= 2) {
6885     // With AVX2, use 32-byte vector compare
6886     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
6887 
6888     // Compare 32-byte vectors
6889     andl(result, 0x0000001f);  //   tail count (in bytes)
6890     andl(limit, 0xffffffe0);   // vector count (in bytes)
6891     jcc(Assembler::zero, COMPARE_TAIL);
6892 
6893     lea(ary1, Address(ary1, limit, Address::times_1));
6894     lea(ary2, Address(ary2, limit, Address::times_1));
6895     negptr(limit);
6896 
6897     bind(COMPARE_WIDE_VECTORS);
6898 
6899 #ifdef _LP64
6900     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
6901       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
6902 
6903       cmpl(limit, -64);
6904       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
6905 
6906       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
6907 
6908       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
6909       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
6910       kortestql(k7, k7);
6911       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
6912       addptr(limit, 64);  // update since we already compared at this addr
6913       cmpl(limit, -64);
6914       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
6915 
6916       // At this point we may still need to compare -limit+result bytes.
6917       // We could execute the next two instruction and just continue via non-wide path:
6918       //  cmpl(limit, 0);
6919       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
6920       // But since we stopped at the points ary{1,2}+limit which are
6921       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
6922       // (|limit| <= 32 and result < 32),
6923       // we may just compare the last 64 bytes.
6924       //
6925       addptr(result, -64);   // it is safe, bc we just came from this area
6926       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
6927       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
6928       kortestql(k7, k7);
6929       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
6930 
6931       jmp(TRUE_LABEL);
6932 
6933       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
6934 
6935     }//if (VM_Version::supports_avx512vlbw())
6936 #endif //_LP64
6937 
6938     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
6939     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
6940     vpxor(vec1, vec2);
6941 
6942     vptest(vec1, vec1);
6943     jcc(Assembler::notZero, FALSE_LABEL);
6944     addptr(limit, 32);
6945     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
6946 
6947     testl(result, result);
6948     jcc(Assembler::zero, TRUE_LABEL);
6949 
6950     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
6951     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
6952     vpxor(vec1, vec2);
6953 
6954     vptest(vec1, vec1);
6955     jccb(Assembler::notZero, FALSE_LABEL);
6956     jmpb(TRUE_LABEL);
6957 
6958     bind(COMPARE_TAIL); // limit is zero
6959     movl(limit, result);
6960     // Fallthru to tail compare
6961   } else if (UseSSE42Intrinsics) {
6962     // With SSE4.2, use double quad vector compare
6963     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
6964 
6965     // Compare 16-byte vectors
6966     andl(result, 0x0000000f);  //   tail count (in bytes)
6967     andl(limit, 0xfffffff0);   // vector count (in bytes)
6968     jcc(Assembler::zero, COMPARE_TAIL);
6969 
6970     lea(ary1, Address(ary1, limit, Address::times_1));
6971     lea(ary2, Address(ary2, limit, Address::times_1));
6972     negptr(limit);
6973 
6974     bind(COMPARE_WIDE_VECTORS);
6975     movdqu(vec1, Address(ary1, limit, Address::times_1));
6976     movdqu(vec2, Address(ary2, limit, Address::times_1));
6977     pxor(vec1, vec2);
6978 
6979     ptest(vec1, vec1);
6980     jcc(Assembler::notZero, FALSE_LABEL);
6981     addptr(limit, 16);
6982     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
6983 
6984     testl(result, result);
6985     jcc(Assembler::zero, TRUE_LABEL);
6986 
6987     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
6988     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
6989     pxor(vec1, vec2);
6990 
6991     ptest(vec1, vec1);
6992     jccb(Assembler::notZero, FALSE_LABEL);
6993     jmpb(TRUE_LABEL);
6994 
6995     bind(COMPARE_TAIL); // limit is zero
6996     movl(limit, result);
6997     // Fallthru to tail compare
6998   }
6999 
7000   // Compare 4-byte vectors
7001   andl(limit, 0xfffffffc); // vector count (in bytes)
7002   jccb(Assembler::zero, COMPARE_CHAR);
7003 
7004   lea(ary1, Address(ary1, limit, Address::times_1));
7005   lea(ary2, Address(ary2, limit, Address::times_1));
7006   negptr(limit);
7007 
7008   bind(COMPARE_VECTORS);
7009   movl(chr, Address(ary1, limit, Address::times_1));
7010   cmpl(chr, Address(ary2, limit, Address::times_1));
7011   jccb(Assembler::notEqual, FALSE_LABEL);
7012   addptr(limit, 4);
7013   jcc(Assembler::notZero, COMPARE_VECTORS);
7014 
7015   // Compare trailing char (final 2 bytes), if any
7016   bind(COMPARE_CHAR);
7017   testl(result, 0x2);   // tail  char
7018   jccb(Assembler::zero, COMPARE_BYTE);
7019   load_unsigned_short(chr, Address(ary1, 0));
7020   load_unsigned_short(limit, Address(ary2, 0));
7021   cmpl(chr, limit);
7022   jccb(Assembler::notEqual, FALSE_LABEL);
7023 
7024   if (is_array_equ && is_char) {
7025     bind(COMPARE_BYTE);
7026   } else {
7027     lea(ary1, Address(ary1, 2));
7028     lea(ary2, Address(ary2, 2));
7029 
7030     bind(COMPARE_BYTE);
7031     testl(result, 0x1);   // tail  byte
7032     jccb(Assembler::zero, TRUE_LABEL);
7033     load_unsigned_byte(chr, Address(ary1, 0));
7034     load_unsigned_byte(limit, Address(ary2, 0));
7035     cmpl(chr, limit);
7036     jccb(Assembler::notEqual, FALSE_LABEL);
7037   }
7038   bind(TRUE_LABEL);
7039   movl(result, 1);   // return true
7040   jmpb(DONE);
7041 
7042   bind(FALSE_LABEL);
7043   xorl(result, result); // return false
7044 
7045   // That's it
7046   bind(DONE);
7047   if (UseAVX >= 2) {
7048     // clean upper bits of YMM registers
7049     vpxor(vec1, vec1);
7050     vpxor(vec2, vec2);
7051   }
7052 }
7053 
7054 #endif
7055 
7056 void MacroAssembler::generate_fill(BasicType t, bool aligned,
7057                                    Register to, Register value, Register count,
7058                                    Register rtmp, XMMRegister xtmp) {
7059   ShortBranchVerifier sbv(this);
7060   assert_different_registers(to, value, count, rtmp);
7061   Label L_exit;
7062   Label L_fill_2_bytes, L_fill_4_bytes;
7063 
7064   int shift = -1;
7065   switch (t) {
7066     case T_BYTE:
7067       shift = 2;
7068       break;
7069     case T_SHORT:
7070       shift = 1;
7071       break;
7072     case T_INT:
7073       shift = 0;
7074       break;
7075     default: ShouldNotReachHere();
7076   }
7077 
7078   if (t == T_BYTE) {
7079     andl(value, 0xff);
7080     movl(rtmp, value);
7081     shll(rtmp, 8);
7082     orl(value, rtmp);
7083   }
7084   if (t == T_SHORT) {
7085     andl(value, 0xffff);
7086   }
7087   if (t == T_BYTE || t == T_SHORT) {
7088     movl(rtmp, value);
7089     shll(rtmp, 16);
7090     orl(value, rtmp);
7091   }
7092 
7093   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
7094   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
7095   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
7096     Label L_skip_align2;
7097     // align source address at 4 bytes address boundary
7098     if (t == T_BYTE) {
7099       Label L_skip_align1;
7100       // One byte misalignment happens only for byte arrays
7101       testptr(to, 1);
7102       jccb(Assembler::zero, L_skip_align1);
7103       movb(Address(to, 0), value);
7104       increment(to);
7105       decrement(count);
7106       BIND(L_skip_align1);
7107     }
7108     // Two bytes misalignment happens only for byte and short (char) arrays
7109     testptr(to, 2);
7110     jccb(Assembler::zero, L_skip_align2);
7111     movw(Address(to, 0), value);
7112     addptr(to, 2);
7113     subl(count, 1<<(shift-1));
7114     BIND(L_skip_align2);
7115   }
7116   if (UseSSE < 2) {
7117     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
7118     // Fill 32-byte chunks
7119     subl(count, 8 << shift);
7120     jcc(Assembler::less, L_check_fill_8_bytes);
7121     align(16);
7122 
7123     BIND(L_fill_32_bytes_loop);
7124 
7125     for (int i = 0; i < 32; i += 4) {
7126       movl(Address(to, i), value);
7127     }
7128 
7129     addptr(to, 32);
7130     subl(count, 8 << shift);
7131     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
7132     BIND(L_check_fill_8_bytes);
7133     addl(count, 8 << shift);
7134     jccb(Assembler::zero, L_exit);
7135     jmpb(L_fill_8_bytes);
7136 
7137     //
7138     // length is too short, just fill qwords
7139     //
7140     BIND(L_fill_8_bytes_loop);
7141     movl(Address(to, 0), value);
7142     movl(Address(to, 4), value);
7143     addptr(to, 8);
7144     BIND(L_fill_8_bytes);
7145     subl(count, 1 << (shift + 1));
7146     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
7147     // fall through to fill 4 bytes
7148   } else {
7149     Label L_fill_32_bytes;
7150     if (!UseUnalignedLoadStores) {
7151       // align to 8 bytes, we know we are 4 byte aligned to start
7152       testptr(to, 4);
7153       jccb(Assembler::zero, L_fill_32_bytes);
7154       movl(Address(to, 0), value);
7155       addptr(to, 4);
7156       subl(count, 1<<shift);
7157     }
7158     BIND(L_fill_32_bytes);
7159     {
7160       assert( UseSSE >= 2, "supported cpu only" );
7161       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
7162       movdl(xtmp, value);
7163       if (UseAVX > 2 && UseUnalignedLoadStores) {
7164         // Fill 64-byte chunks
7165         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
7166         vpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
7167 
7168         subl(count, 16 << shift);
7169         jcc(Assembler::less, L_check_fill_32_bytes);
7170         align(16);
7171 
7172         BIND(L_fill_64_bytes_loop);
7173         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
7174         addptr(to, 64);
7175         subl(count, 16 << shift);
7176         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
7177 
7178         BIND(L_check_fill_32_bytes);
7179         addl(count, 8 << shift);
7180         jccb(Assembler::less, L_check_fill_8_bytes);
7181         vmovdqu(Address(to, 0), xtmp);
7182         addptr(to, 32);
7183         subl(count, 8 << shift);
7184 
7185         BIND(L_check_fill_8_bytes);
7186       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
7187         // Fill 64-byte chunks
7188         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
7189         vpbroadcastd(xtmp, xtmp, Assembler::AVX_256bit);
7190 
7191         subl(count, 16 << shift);
7192         jcc(Assembler::less, L_check_fill_32_bytes);
7193         align(16);
7194 
7195         BIND(L_fill_64_bytes_loop);
7196         vmovdqu(Address(to, 0), xtmp);
7197         vmovdqu(Address(to, 32), xtmp);
7198         addptr(to, 64);
7199         subl(count, 16 << shift);
7200         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
7201 
7202         BIND(L_check_fill_32_bytes);
7203         addl(count, 8 << shift);
7204         jccb(Assembler::less, L_check_fill_8_bytes);
7205         vmovdqu(Address(to, 0), xtmp);
7206         addptr(to, 32);
7207         subl(count, 8 << shift);
7208 
7209         BIND(L_check_fill_8_bytes);
7210         // clean upper bits of YMM registers
7211         movdl(xtmp, value);
7212         pshufd(xtmp, xtmp, 0);
7213       } else {
7214         // Fill 32-byte chunks
7215         pshufd(xtmp, xtmp, 0);
7216 
7217         subl(count, 8 << shift);
7218         jcc(Assembler::less, L_check_fill_8_bytes);
7219         align(16);
7220 
7221         BIND(L_fill_32_bytes_loop);
7222 
7223         if (UseUnalignedLoadStores) {
7224           movdqu(Address(to, 0), xtmp);
7225           movdqu(Address(to, 16), xtmp);
7226         } else {
7227           movq(Address(to, 0), xtmp);
7228           movq(Address(to, 8), xtmp);
7229           movq(Address(to, 16), xtmp);
7230           movq(Address(to, 24), xtmp);
7231         }
7232 
7233         addptr(to, 32);
7234         subl(count, 8 << shift);
7235         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
7236 
7237         BIND(L_check_fill_8_bytes);
7238       }
7239       addl(count, 8 << shift);
7240       jccb(Assembler::zero, L_exit);
7241       jmpb(L_fill_8_bytes);
7242 
7243       //
7244       // length is too short, just fill qwords
7245       //
7246       BIND(L_fill_8_bytes_loop);
7247       movq(Address(to, 0), xtmp);
7248       addptr(to, 8);
7249       BIND(L_fill_8_bytes);
7250       subl(count, 1 << (shift + 1));
7251       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
7252     }
7253   }
7254   // fill trailing 4 bytes
7255   BIND(L_fill_4_bytes);
7256   testl(count, 1<<shift);
7257   jccb(Assembler::zero, L_fill_2_bytes);
7258   movl(Address(to, 0), value);
7259   if (t == T_BYTE || t == T_SHORT) {
7260     Label L_fill_byte;
7261     addptr(to, 4);
7262     BIND(L_fill_2_bytes);
7263     // fill trailing 2 bytes
7264     testl(count, 1<<(shift-1));
7265     jccb(Assembler::zero, L_fill_byte);
7266     movw(Address(to, 0), value);
7267     if (t == T_BYTE) {
7268       addptr(to, 2);
7269       BIND(L_fill_byte);
7270       // fill trailing byte
7271       testl(count, 1);
7272       jccb(Assembler::zero, L_exit);
7273       movb(Address(to, 0), value);
7274     } else {
7275       BIND(L_fill_byte);
7276     }
7277   } else {
7278     BIND(L_fill_2_bytes);
7279   }
7280   BIND(L_exit);
7281 }
7282 
7283 // encode char[] to byte[] in ISO_8859_1
7284    //@HotSpotIntrinsicCandidate
7285    //private static int implEncodeISOArray(byte[] sa, int sp,
7286    //byte[] da, int dp, int len) {
7287    //  int i = 0;
7288    //  for (; i < len; i++) {
7289    //    char c = StringUTF16.getChar(sa, sp++);
7290    //    if (c > '\u00FF')
7291    //      break;
7292    //    da[dp++] = (byte)c;
7293    //  }
7294    //  return i;
7295    //}
7296 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
7297   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
7298   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
7299   Register tmp5, Register result) {
7300 
7301   // rsi: src
7302   // rdi: dst
7303   // rdx: len
7304   // rcx: tmp5
7305   // rax: result
7306   ShortBranchVerifier sbv(this);
7307   assert_different_registers(src, dst, len, tmp5, result);
7308   Label L_done, L_copy_1_char, L_copy_1_char_exit;
7309 
7310   // set result
7311   xorl(result, result);
7312   // check for zero length
7313   testl(len, len);
7314   jcc(Assembler::zero, L_done);
7315 
7316   movl(result, len);
7317 
7318   // Setup pointers
7319   lea(src, Address(src, len, Address::times_2)); // char[]
7320   lea(dst, Address(dst, len, Address::times_1)); // byte[]
7321   negptr(len);
7322 
7323   if (UseSSE42Intrinsics || UseAVX >= 2) {
7324     Label L_copy_8_chars, L_copy_8_chars_exit;
7325     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
7326 
7327     if (UseAVX >= 2) {
7328       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
7329       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
7330       movdl(tmp1Reg, tmp5);
7331       vpbroadcastd(tmp1Reg, tmp1Reg, Assembler::AVX_256bit);
7332       jmp(L_chars_32_check);
7333 
7334       bind(L_copy_32_chars);
7335       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
7336       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
7337       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
7338       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
7339       jccb(Assembler::notZero, L_copy_32_chars_exit);
7340       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
7341       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
7342       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
7343 
7344       bind(L_chars_32_check);
7345       addptr(len, 32);
7346       jcc(Assembler::lessEqual, L_copy_32_chars);
7347 
7348       bind(L_copy_32_chars_exit);
7349       subptr(len, 16);
7350       jccb(Assembler::greater, L_copy_16_chars_exit);
7351 
7352     } else if (UseSSE42Intrinsics) {
7353       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
7354       movdl(tmp1Reg, tmp5);
7355       pshufd(tmp1Reg, tmp1Reg, 0);
7356       jmpb(L_chars_16_check);
7357     }
7358 
7359     bind(L_copy_16_chars);
7360     if (UseAVX >= 2) {
7361       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
7362       vptest(tmp2Reg, tmp1Reg);
7363       jcc(Assembler::notZero, L_copy_16_chars_exit);
7364       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
7365       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
7366     } else {
7367       if (UseAVX > 0) {
7368         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
7369         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
7370         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
7371       } else {
7372         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
7373         por(tmp2Reg, tmp3Reg);
7374         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
7375         por(tmp2Reg, tmp4Reg);
7376       }
7377       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
7378       jccb(Assembler::notZero, L_copy_16_chars_exit);
7379       packuswb(tmp3Reg, tmp4Reg);
7380     }
7381     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
7382 
7383     bind(L_chars_16_check);
7384     addptr(len, 16);
7385     jcc(Assembler::lessEqual, L_copy_16_chars);
7386 
7387     bind(L_copy_16_chars_exit);
7388     if (UseAVX >= 2) {
7389       // clean upper bits of YMM registers
7390       vpxor(tmp2Reg, tmp2Reg);
7391       vpxor(tmp3Reg, tmp3Reg);
7392       vpxor(tmp4Reg, tmp4Reg);
7393       movdl(tmp1Reg, tmp5);
7394       pshufd(tmp1Reg, tmp1Reg, 0);
7395     }
7396     subptr(len, 8);
7397     jccb(Assembler::greater, L_copy_8_chars_exit);
7398 
7399     bind(L_copy_8_chars);
7400     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
7401     ptest(tmp3Reg, tmp1Reg);
7402     jccb(Assembler::notZero, L_copy_8_chars_exit);
7403     packuswb(tmp3Reg, tmp1Reg);
7404     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
7405     addptr(len, 8);
7406     jccb(Assembler::lessEqual, L_copy_8_chars);
7407 
7408     bind(L_copy_8_chars_exit);
7409     subptr(len, 8);
7410     jccb(Assembler::zero, L_done);
7411   }
7412 
7413   bind(L_copy_1_char);
7414   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
7415   testl(tmp5, 0xff00);      // check if Unicode char
7416   jccb(Assembler::notZero, L_copy_1_char_exit);
7417   movb(Address(dst, len, Address::times_1, 0), tmp5);
7418   addptr(len, 1);
7419   jccb(Assembler::less, L_copy_1_char);
7420 
7421   bind(L_copy_1_char_exit);
7422   addptr(result, len); // len is negative count of not processed elements
7423 
7424   bind(L_done);
7425 }
7426 
7427 #ifdef _LP64
7428 /**
7429  * Helper for multiply_to_len().
7430  */
7431 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
7432   addq(dest_lo, src1);
7433   adcq(dest_hi, 0);
7434   addq(dest_lo, src2);
7435   adcq(dest_hi, 0);
7436 }
7437 
7438 /**
7439  * Multiply 64 bit by 64 bit first loop.
7440  */
7441 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
7442                                            Register y, Register y_idx, Register z,
7443                                            Register carry, Register product,
7444                                            Register idx, Register kdx) {
7445   //
7446   //  jlong carry, x[], y[], z[];
7447   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
7448   //    huge_128 product = y[idx] * x[xstart] + carry;
7449   //    z[kdx] = (jlong)product;
7450   //    carry  = (jlong)(product >>> 64);
7451   //  }
7452   //  z[xstart] = carry;
7453   //
7454 
7455   Label L_first_loop, L_first_loop_exit;
7456   Label L_one_x, L_one_y, L_multiply;
7457 
7458   decrementl(xstart);
7459   jcc(Assembler::negative, L_one_x);
7460 
7461   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
7462   rorq(x_xstart, 32); // convert big-endian to little-endian
7463 
7464   bind(L_first_loop);
7465   decrementl(idx);
7466   jcc(Assembler::negative, L_first_loop_exit);
7467   decrementl(idx);
7468   jcc(Assembler::negative, L_one_y);
7469   movq(y_idx, Address(y, idx, Address::times_4,  0));
7470   rorq(y_idx, 32); // convert big-endian to little-endian
7471   bind(L_multiply);
7472   movq(product, x_xstart);
7473   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
7474   addq(product, carry);
7475   adcq(rdx, 0);
7476   subl(kdx, 2);
7477   movl(Address(z, kdx, Address::times_4,  4), product);
7478   shrq(product, 32);
7479   movl(Address(z, kdx, Address::times_4,  0), product);
7480   movq(carry, rdx);
7481   jmp(L_first_loop);
7482 
7483   bind(L_one_y);
7484   movl(y_idx, Address(y,  0));
7485   jmp(L_multiply);
7486 
7487   bind(L_one_x);
7488   movl(x_xstart, Address(x,  0));
7489   jmp(L_first_loop);
7490 
7491   bind(L_first_loop_exit);
7492 }
7493 
7494 /**
7495  * Multiply 64 bit by 64 bit and add 128 bit.
7496  */
7497 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
7498                                             Register yz_idx, Register idx,
7499                                             Register carry, Register product, int offset) {
7500   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
7501   //     z[kdx] = (jlong)product;
7502 
7503   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
7504   rorq(yz_idx, 32); // convert big-endian to little-endian
7505   movq(product, x_xstart);
7506   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
7507   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
7508   rorq(yz_idx, 32); // convert big-endian to little-endian
7509 
7510   add2_with_carry(rdx, product, carry, yz_idx);
7511 
7512   movl(Address(z, idx, Address::times_4,  offset+4), product);
7513   shrq(product, 32);
7514   movl(Address(z, idx, Address::times_4,  offset), product);
7515 
7516 }
7517 
7518 /**
7519  * Multiply 128 bit by 128 bit. Unrolled inner loop.
7520  */
7521 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
7522                                              Register yz_idx, Register idx, Register jdx,
7523                                              Register carry, Register product,
7524                                              Register carry2) {
7525   //   jlong carry, x[], y[], z[];
7526   //   int kdx = ystart+1;
7527   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
7528   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
7529   //     z[kdx+idx+1] = (jlong)product;
7530   //     jlong carry2  = (jlong)(product >>> 64);
7531   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
7532   //     z[kdx+idx] = (jlong)product;
7533   //     carry  = (jlong)(product >>> 64);
7534   //   }
7535   //   idx += 2;
7536   //   if (idx > 0) {
7537   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
7538   //     z[kdx+idx] = (jlong)product;
7539   //     carry  = (jlong)(product >>> 64);
7540   //   }
7541   //
7542 
7543   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
7544 
7545   movl(jdx, idx);
7546   andl(jdx, 0xFFFFFFFC);
7547   shrl(jdx, 2);
7548 
7549   bind(L_third_loop);
7550   subl(jdx, 1);
7551   jcc(Assembler::negative, L_third_loop_exit);
7552   subl(idx, 4);
7553 
7554   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
7555   movq(carry2, rdx);
7556 
7557   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
7558   movq(carry, rdx);
7559   jmp(L_third_loop);
7560 
7561   bind (L_third_loop_exit);
7562 
7563   andl (idx, 0x3);
7564   jcc(Assembler::zero, L_post_third_loop_done);
7565 
7566   Label L_check_1;
7567   subl(idx, 2);
7568   jcc(Assembler::negative, L_check_1);
7569 
7570   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
7571   movq(carry, rdx);
7572 
7573   bind (L_check_1);
7574   addl (idx, 0x2);
7575   andl (idx, 0x1);
7576   subl(idx, 1);
7577   jcc(Assembler::negative, L_post_third_loop_done);
7578 
7579   movl(yz_idx, Address(y, idx, Address::times_4,  0));
7580   movq(product, x_xstart);
7581   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
7582   movl(yz_idx, Address(z, idx, Address::times_4,  0));
7583 
7584   add2_with_carry(rdx, product, yz_idx, carry);
7585 
7586   movl(Address(z, idx, Address::times_4,  0), product);
7587   shrq(product, 32);
7588 
7589   shlq(rdx, 32);
7590   orq(product, rdx);
7591   movq(carry, product);
7592 
7593   bind(L_post_third_loop_done);
7594 }
7595 
7596 /**
7597  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
7598  *
7599  */
7600 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
7601                                                   Register carry, Register carry2,
7602                                                   Register idx, Register jdx,
7603                                                   Register yz_idx1, Register yz_idx2,
7604                                                   Register tmp, Register tmp3, Register tmp4) {
7605   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
7606 
7607   //   jlong carry, x[], y[], z[];
7608   //   int kdx = ystart+1;
7609   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
7610   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
7611   //     jlong carry2  = (jlong)(tmp3 >>> 64);
7612   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
7613   //     carry  = (jlong)(tmp4 >>> 64);
7614   //     z[kdx+idx+1] = (jlong)tmp3;
7615   //     z[kdx+idx] = (jlong)tmp4;
7616   //   }
7617   //   idx += 2;
7618   //   if (idx > 0) {
7619   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
7620   //     z[kdx+idx] = (jlong)yz_idx1;
7621   //     carry  = (jlong)(yz_idx1 >>> 64);
7622   //   }
7623   //
7624 
7625   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
7626 
7627   movl(jdx, idx);
7628   andl(jdx, 0xFFFFFFFC);
7629   shrl(jdx, 2);
7630 
7631   bind(L_third_loop);
7632   subl(jdx, 1);
7633   jcc(Assembler::negative, L_third_loop_exit);
7634   subl(idx, 4);
7635 
7636   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
7637   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
7638   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
7639   rorxq(yz_idx2, yz_idx2, 32);
7640 
7641   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
7642   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
7643 
7644   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
7645   rorxq(yz_idx1, yz_idx1, 32);
7646   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
7647   rorxq(yz_idx2, yz_idx2, 32);
7648 
7649   if (VM_Version::supports_adx()) {
7650     adcxq(tmp3, carry);
7651     adoxq(tmp3, yz_idx1);
7652 
7653     adcxq(tmp4, tmp);
7654     adoxq(tmp4, yz_idx2);
7655 
7656     movl(carry, 0); // does not affect flags
7657     adcxq(carry2, carry);
7658     adoxq(carry2, carry);
7659   } else {
7660     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
7661     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
7662   }
7663   movq(carry, carry2);
7664 
7665   movl(Address(z, idx, Address::times_4, 12), tmp3);
7666   shrq(tmp3, 32);
7667   movl(Address(z, idx, Address::times_4,  8), tmp3);
7668 
7669   movl(Address(z, idx, Address::times_4,  4), tmp4);
7670   shrq(tmp4, 32);
7671   movl(Address(z, idx, Address::times_4,  0), tmp4);
7672 
7673   jmp(L_third_loop);
7674 
7675   bind (L_third_loop_exit);
7676 
7677   andl (idx, 0x3);
7678   jcc(Assembler::zero, L_post_third_loop_done);
7679 
7680   Label L_check_1;
7681   subl(idx, 2);
7682   jcc(Assembler::negative, L_check_1);
7683 
7684   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
7685   rorxq(yz_idx1, yz_idx1, 32);
7686   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
7687   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
7688   rorxq(yz_idx2, yz_idx2, 32);
7689 
7690   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
7691 
7692   movl(Address(z, idx, Address::times_4,  4), tmp3);
7693   shrq(tmp3, 32);
7694   movl(Address(z, idx, Address::times_4,  0), tmp3);
7695   movq(carry, tmp4);
7696 
7697   bind (L_check_1);
7698   addl (idx, 0x2);
7699   andl (idx, 0x1);
7700   subl(idx, 1);
7701   jcc(Assembler::negative, L_post_third_loop_done);
7702   movl(tmp4, Address(y, idx, Address::times_4,  0));
7703   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
7704   movl(tmp4, Address(z, idx, Address::times_4,  0));
7705 
7706   add2_with_carry(carry2, tmp3, tmp4, carry);
7707 
7708   movl(Address(z, idx, Address::times_4,  0), tmp3);
7709   shrq(tmp3, 32);
7710 
7711   shlq(carry2, 32);
7712   orq(tmp3, carry2);
7713   movq(carry, tmp3);
7714 
7715   bind(L_post_third_loop_done);
7716 }
7717 
7718 /**
7719  * Code for BigInteger::multiplyToLen() instrinsic.
7720  *
7721  * rdi: x
7722  * rax: xlen
7723  * rsi: y
7724  * rcx: ylen
7725  * r8:  z
7726  * r11: zlen
7727  * r12: tmp1
7728  * r13: tmp2
7729  * r14: tmp3
7730  * r15: tmp4
7731  * rbx: tmp5
7732  *
7733  */
7734 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
7735                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
7736   ShortBranchVerifier sbv(this);
7737   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
7738 
7739   push(tmp1);
7740   push(tmp2);
7741   push(tmp3);
7742   push(tmp4);
7743   push(tmp5);
7744 
7745   push(xlen);
7746   push(zlen);
7747 
7748   const Register idx = tmp1;
7749   const Register kdx = tmp2;
7750   const Register xstart = tmp3;
7751 
7752   const Register y_idx = tmp4;
7753   const Register carry = tmp5;
7754   const Register product  = xlen;
7755   const Register x_xstart = zlen;  // reuse register
7756 
7757   // First Loop.
7758   //
7759   //  final static long LONG_MASK = 0xffffffffL;
7760   //  int xstart = xlen - 1;
7761   //  int ystart = ylen - 1;
7762   //  long carry = 0;
7763   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
7764   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
7765   //    z[kdx] = (int)product;
7766   //    carry = product >>> 32;
7767   //  }
7768   //  z[xstart] = (int)carry;
7769   //
7770 
7771   movl(idx, ylen);      // idx = ylen;
7772   movl(kdx, zlen);      // kdx = xlen+ylen;
7773   xorq(carry, carry);   // carry = 0;
7774 
7775   Label L_done;
7776 
7777   movl(xstart, xlen);
7778   decrementl(xstart);
7779   jcc(Assembler::negative, L_done);
7780 
7781   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
7782 
7783   Label L_second_loop;
7784   testl(kdx, kdx);
7785   jcc(Assembler::zero, L_second_loop);
7786 
7787   Label L_carry;
7788   subl(kdx, 1);
7789   jcc(Assembler::zero, L_carry);
7790 
7791   movl(Address(z, kdx, Address::times_4,  0), carry);
7792   shrq(carry, 32);
7793   subl(kdx, 1);
7794 
7795   bind(L_carry);
7796   movl(Address(z, kdx, Address::times_4,  0), carry);
7797 
7798   // Second and third (nested) loops.
7799   //
7800   // for (int i = xstart-1; i >= 0; i--) { // Second loop
7801   //   carry = 0;
7802   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
7803   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
7804   //                    (z[k] & LONG_MASK) + carry;
7805   //     z[k] = (int)product;
7806   //     carry = product >>> 32;
7807   //   }
7808   //   z[i] = (int)carry;
7809   // }
7810   //
7811   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
7812 
7813   const Register jdx = tmp1;
7814 
7815   bind(L_second_loop);
7816   xorl(carry, carry);    // carry = 0;
7817   movl(jdx, ylen);       // j = ystart+1
7818 
7819   subl(xstart, 1);       // i = xstart-1;
7820   jcc(Assembler::negative, L_done);
7821 
7822   push (z);
7823 
7824   Label L_last_x;
7825   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
7826   subl(xstart, 1);       // i = xstart-1;
7827   jcc(Assembler::negative, L_last_x);
7828 
7829   if (UseBMI2Instructions) {
7830     movq(rdx,  Address(x, xstart, Address::times_4,  0));
7831     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
7832   } else {
7833     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
7834     rorq(x_xstart, 32);  // convert big-endian to little-endian
7835   }
7836 
7837   Label L_third_loop_prologue;
7838   bind(L_third_loop_prologue);
7839 
7840   push (x);
7841   push (xstart);
7842   push (ylen);
7843 
7844 
7845   if (UseBMI2Instructions) {
7846     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
7847   } else { // !UseBMI2Instructions
7848     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
7849   }
7850 
7851   pop(ylen);
7852   pop(xlen);
7853   pop(x);
7854   pop(z);
7855 
7856   movl(tmp3, xlen);
7857   addl(tmp3, 1);
7858   movl(Address(z, tmp3, Address::times_4,  0), carry);
7859   subl(tmp3, 1);
7860   jccb(Assembler::negative, L_done);
7861 
7862   shrq(carry, 32);
7863   movl(Address(z, tmp3, Address::times_4,  0), carry);
7864   jmp(L_second_loop);
7865 
7866   // Next infrequent code is moved outside loops.
7867   bind(L_last_x);
7868   if (UseBMI2Instructions) {
7869     movl(rdx, Address(x,  0));
7870   } else {
7871     movl(x_xstart, Address(x,  0));
7872   }
7873   jmp(L_third_loop_prologue);
7874 
7875   bind(L_done);
7876 
7877   pop(zlen);
7878   pop(xlen);
7879 
7880   pop(tmp5);
7881   pop(tmp4);
7882   pop(tmp3);
7883   pop(tmp2);
7884   pop(tmp1);
7885 }
7886 
7887 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
7888   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
7889   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
7890   Label VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
7891   Label VECTOR8_TAIL, VECTOR4_TAIL;
7892   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
7893   Label SAME_TILL_END, DONE;
7894   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
7895 
7896   //scale is in rcx in both Win64 and Unix
7897   ShortBranchVerifier sbv(this);
7898 
7899   shlq(length);
7900   xorq(result, result);
7901 
7902   if ((UseAVX > 2) &&
7903       VM_Version::supports_avx512vlbw()) {
7904     Label VECTOR64_LOOP, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
7905 
7906     cmpq(length, 64);
7907     jcc(Assembler::less, VECTOR32_TAIL);
7908     movq(tmp1, length);
7909     andq(tmp1, 0x3F);      // tail count
7910     andq(length, ~(0x3F)); //vector count
7911 
7912     bind(VECTOR64_LOOP);
7913     // AVX512 code to compare 64 byte vectors.
7914     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
7915     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
7916     kortestql(k7, k7);
7917     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
7918     addq(result, 64);
7919     subq(length, 64);
7920     jccb(Assembler::notZero, VECTOR64_LOOP);
7921 
7922     //bind(VECTOR64_TAIL);
7923     testq(tmp1, tmp1);
7924     jcc(Assembler::zero, SAME_TILL_END);
7925 
7926     //bind(VECTOR64_TAIL);
7927     // AVX512 code to compare upto 63 byte vectors.
7928     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
7929     shlxq(tmp2, tmp2, tmp1);
7930     notq(tmp2);
7931     kmovql(k3, tmp2);
7932 
7933     evmovdqub(rymm0, k3, Address(obja, result), Assembler::AVX_512bit);
7934     evpcmpeqb(k7, k3, rymm0, Address(objb, result), Assembler::AVX_512bit);
7935 
7936     ktestql(k7, k3);
7937     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
7938 
7939     bind(VECTOR64_NOT_EQUAL);
7940     kmovql(tmp1, k7);
7941     notq(tmp1);
7942     tzcntq(tmp1, tmp1);
7943     addq(result, tmp1);
7944     shrq(result);
7945     jmp(DONE);
7946     bind(VECTOR32_TAIL);
7947   }
7948 
7949   cmpq(length, 8);
7950   jcc(Assembler::equal, VECTOR8_LOOP);
7951   jcc(Assembler::less, VECTOR4_TAIL);
7952 
7953   if (UseAVX >= 2) {
7954     Label VECTOR16_TAIL, VECTOR32_LOOP;
7955 
7956     cmpq(length, 16);
7957     jcc(Assembler::equal, VECTOR16_LOOP);
7958     jcc(Assembler::less, VECTOR8_LOOP);
7959 
7960     cmpq(length, 32);
7961     jccb(Assembler::less, VECTOR16_TAIL);
7962 
7963     subq(length, 32);
7964     bind(VECTOR32_LOOP);
7965     vmovdqu(rymm0, Address(obja, result));
7966     vmovdqu(rymm1, Address(objb, result));
7967     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
7968     vptest(rymm2, rymm2);
7969     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
7970     addq(result, 32);
7971     subq(length, 32);
7972     jcc(Assembler::greaterEqual, VECTOR32_LOOP);
7973     addq(length, 32);
7974     jcc(Assembler::equal, SAME_TILL_END);
7975     //falling through if less than 32 bytes left //close the branch here.
7976 
7977     bind(VECTOR16_TAIL);
7978     cmpq(length, 16);
7979     jccb(Assembler::less, VECTOR8_TAIL);
7980     bind(VECTOR16_LOOP);
7981     movdqu(rymm0, Address(obja, result));
7982     movdqu(rymm1, Address(objb, result));
7983     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
7984     ptest(rymm2, rymm2);
7985     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
7986     addq(result, 16);
7987     subq(length, 16);
7988     jcc(Assembler::equal, SAME_TILL_END);
7989     //falling through if less than 16 bytes left
7990   } else {//regular intrinsics
7991 
7992     cmpq(length, 16);
7993     jccb(Assembler::less, VECTOR8_TAIL);
7994 
7995     subq(length, 16);
7996     bind(VECTOR16_LOOP);
7997     movdqu(rymm0, Address(obja, result));
7998     movdqu(rymm1, Address(objb, result));
7999     pxor(rymm0, rymm1);
8000     ptest(rymm0, rymm0);
8001     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
8002     addq(result, 16);
8003     subq(length, 16);
8004     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
8005     addq(length, 16);
8006     jcc(Assembler::equal, SAME_TILL_END);
8007     //falling through if less than 16 bytes left
8008   }
8009 
8010   bind(VECTOR8_TAIL);
8011   cmpq(length, 8);
8012   jccb(Assembler::less, VECTOR4_TAIL);
8013   bind(VECTOR8_LOOP);
8014   movq(tmp1, Address(obja, result));
8015   movq(tmp2, Address(objb, result));
8016   xorq(tmp1, tmp2);
8017   testq(tmp1, tmp1);
8018   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
8019   addq(result, 8);
8020   subq(length, 8);
8021   jcc(Assembler::equal, SAME_TILL_END);
8022   //falling through if less than 8 bytes left
8023 
8024   bind(VECTOR4_TAIL);
8025   cmpq(length, 4);
8026   jccb(Assembler::less, BYTES_TAIL);
8027   bind(VECTOR4_LOOP);
8028   movl(tmp1, Address(obja, result));
8029   xorl(tmp1, Address(objb, result));
8030   testl(tmp1, tmp1);
8031   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
8032   addq(result, 4);
8033   subq(length, 4);
8034   jcc(Assembler::equal, SAME_TILL_END);
8035   //falling through if less than 4 bytes left
8036 
8037   bind(BYTES_TAIL);
8038   bind(BYTES_LOOP);
8039   load_unsigned_byte(tmp1, Address(obja, result));
8040   load_unsigned_byte(tmp2, Address(objb, result));
8041   xorl(tmp1, tmp2);
8042   testl(tmp1, tmp1);
8043   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
8044   decq(length);
8045   jcc(Assembler::zero, SAME_TILL_END);
8046   incq(result);
8047   load_unsigned_byte(tmp1, Address(obja, result));
8048   load_unsigned_byte(tmp2, Address(objb, result));
8049   xorl(tmp1, tmp2);
8050   testl(tmp1, tmp1);
8051   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
8052   decq(length);
8053   jcc(Assembler::zero, SAME_TILL_END);
8054   incq(result);
8055   load_unsigned_byte(tmp1, Address(obja, result));
8056   load_unsigned_byte(tmp2, Address(objb, result));
8057   xorl(tmp1, tmp2);
8058   testl(tmp1, tmp1);
8059   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
8060   jmp(SAME_TILL_END);
8061 
8062   if (UseAVX >= 2) {
8063     bind(VECTOR32_NOT_EQUAL);
8064     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
8065     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
8066     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
8067     vpmovmskb(tmp1, rymm0);
8068     bsfq(tmp1, tmp1);
8069     addq(result, tmp1);
8070     shrq(result);
8071     jmp(DONE);
8072   }
8073 
8074   bind(VECTOR16_NOT_EQUAL);
8075   if (UseAVX >= 2) {
8076     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
8077     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
8078     pxor(rymm0, rymm2);
8079   } else {
8080     pcmpeqb(rymm2, rymm2);
8081     pxor(rymm0, rymm1);
8082     pcmpeqb(rymm0, rymm1);
8083     pxor(rymm0, rymm2);
8084   }
8085   pmovmskb(tmp1, rymm0);
8086   bsfq(tmp1, tmp1);
8087   addq(result, tmp1);
8088   shrq(result);
8089   jmpb(DONE);
8090 
8091   bind(VECTOR8_NOT_EQUAL);
8092   bind(VECTOR4_NOT_EQUAL);
8093   bsfq(tmp1, tmp1);
8094   shrq(tmp1, 3);
8095   addq(result, tmp1);
8096   bind(BYTES_NOT_EQUAL);
8097   shrq(result);
8098   jmpb(DONE);
8099 
8100   bind(SAME_TILL_END);
8101   mov64(result, -1);
8102 
8103   bind(DONE);
8104 }
8105 
8106 //Helper functions for square_to_len()
8107 
8108 /**
8109  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
8110  * Preserves x and z and modifies rest of the registers.
8111  */
8112 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
8113   // Perform square and right shift by 1
8114   // Handle odd xlen case first, then for even xlen do the following
8115   // jlong carry = 0;
8116   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
8117   //     huge_128 product = x[j:j+1] * x[j:j+1];
8118   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
8119   //     z[i+2:i+3] = (jlong)(product >>> 1);
8120   //     carry = (jlong)product;
8121   // }
8122 
8123   xorq(tmp5, tmp5);     // carry
8124   xorq(rdxReg, rdxReg);
8125   xorl(tmp1, tmp1);     // index for x
8126   xorl(tmp4, tmp4);     // index for z
8127 
8128   Label L_first_loop, L_first_loop_exit;
8129 
8130   testl(xlen, 1);
8131   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
8132 
8133   // Square and right shift by 1 the odd element using 32 bit multiply
8134   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
8135   imulq(raxReg, raxReg);
8136   shrq(raxReg, 1);
8137   adcq(tmp5, 0);
8138   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
8139   incrementl(tmp1);
8140   addl(tmp4, 2);
8141 
8142   // Square and  right shift by 1 the rest using 64 bit multiply
8143   bind(L_first_loop);
8144   cmpptr(tmp1, xlen);
8145   jccb(Assembler::equal, L_first_loop_exit);
8146 
8147   // Square
8148   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
8149   rorq(raxReg, 32);    // convert big-endian to little-endian
8150   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
8151 
8152   // Right shift by 1 and save carry
8153   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
8154   rcrq(rdxReg, 1);
8155   rcrq(raxReg, 1);
8156   adcq(tmp5, 0);
8157 
8158   // Store result in z
8159   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
8160   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
8161 
8162   // Update indices for x and z
8163   addl(tmp1, 2);
8164   addl(tmp4, 4);
8165   jmp(L_first_loop);
8166 
8167   bind(L_first_loop_exit);
8168 }
8169 
8170 
8171 /**
8172  * Perform the following multiply add operation using BMI2 instructions
8173  * carry:sum = sum + op1*op2 + carry
8174  * op2 should be in rdx
8175  * op2 is preserved, all other registers are modified
8176  */
8177 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
8178   // assert op2 is rdx
8179   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
8180   addq(sum, carry);
8181   adcq(tmp2, 0);
8182   addq(sum, op1);
8183   adcq(tmp2, 0);
8184   movq(carry, tmp2);
8185 }
8186 
8187 /**
8188  * Perform the following multiply add operation:
8189  * carry:sum = sum + op1*op2 + carry
8190  * Preserves op1, op2 and modifies rest of registers
8191  */
8192 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
8193   // rdx:rax = op1 * op2
8194   movq(raxReg, op2);
8195   mulq(op1);
8196 
8197   //  rdx:rax = sum + carry + rdx:rax
8198   addq(sum, carry);
8199   adcq(rdxReg, 0);
8200   addq(sum, raxReg);
8201   adcq(rdxReg, 0);
8202 
8203   // carry:sum = rdx:sum
8204   movq(carry, rdxReg);
8205 }
8206 
8207 /**
8208  * Add 64 bit long carry into z[] with carry propogation.
8209  * Preserves z and carry register values and modifies rest of registers.
8210  *
8211  */
8212 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
8213   Label L_fourth_loop, L_fourth_loop_exit;
8214 
8215   movl(tmp1, 1);
8216   subl(zlen, 2);
8217   addq(Address(z, zlen, Address::times_4, 0), carry);
8218 
8219   bind(L_fourth_loop);
8220   jccb(Assembler::carryClear, L_fourth_loop_exit);
8221   subl(zlen, 2);
8222   jccb(Assembler::negative, L_fourth_loop_exit);
8223   addq(Address(z, zlen, Address::times_4, 0), tmp1);
8224   jmp(L_fourth_loop);
8225   bind(L_fourth_loop_exit);
8226 }
8227 
8228 /**
8229  * Shift z[] left by 1 bit.
8230  * Preserves x, len, z and zlen registers and modifies rest of the registers.
8231  *
8232  */
8233 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
8234 
8235   Label L_fifth_loop, L_fifth_loop_exit;
8236 
8237   // Fifth loop
8238   // Perform primitiveLeftShift(z, zlen, 1)
8239 
8240   const Register prev_carry = tmp1;
8241   const Register new_carry = tmp4;
8242   const Register value = tmp2;
8243   const Register zidx = tmp3;
8244 
8245   // int zidx, carry;
8246   // long value;
8247   // carry = 0;
8248   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
8249   //    (carry:value)  = (z[i] << 1) | carry ;
8250   //    z[i] = value;
8251   // }
8252 
8253   movl(zidx, zlen);
8254   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
8255 
8256   bind(L_fifth_loop);
8257   decl(zidx);  // Use decl to preserve carry flag
8258   decl(zidx);
8259   jccb(Assembler::negative, L_fifth_loop_exit);
8260 
8261   if (UseBMI2Instructions) {
8262      movq(value, Address(z, zidx, Address::times_4, 0));
8263      rclq(value, 1);
8264      rorxq(value, value, 32);
8265      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
8266   }
8267   else {
8268     // clear new_carry
8269     xorl(new_carry, new_carry);
8270 
8271     // Shift z[i] by 1, or in previous carry and save new carry
8272     movq(value, Address(z, zidx, Address::times_4, 0));
8273     shlq(value, 1);
8274     adcl(new_carry, 0);
8275 
8276     orq(value, prev_carry);
8277     rorq(value, 0x20);
8278     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
8279 
8280     // Set previous carry = new carry
8281     movl(prev_carry, new_carry);
8282   }
8283   jmp(L_fifth_loop);
8284 
8285   bind(L_fifth_loop_exit);
8286 }
8287 
8288 
8289 /**
8290  * Code for BigInteger::squareToLen() intrinsic
8291  *
8292  * rdi: x
8293  * rsi: len
8294  * r8:  z
8295  * rcx: zlen
8296  * r12: tmp1
8297  * r13: tmp2
8298  * r14: tmp3
8299  * r15: tmp4
8300  * rbx: tmp5
8301  *
8302  */
8303 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) {
8304 
8305   Label L_second_loop, L_second_loop_exit, L_third_loop, L_third_loop_exit, L_last_x, L_multiply;
8306   push(tmp1);
8307   push(tmp2);
8308   push(tmp3);
8309   push(tmp4);
8310   push(tmp5);
8311 
8312   // First loop
8313   // Store the squares, right shifted one bit (i.e., divided by 2).
8314   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
8315 
8316   // Add in off-diagonal sums.
8317   //
8318   // Second, third (nested) and fourth loops.
8319   // zlen +=2;
8320   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
8321   //    carry = 0;
8322   //    long op2 = x[xidx:xidx+1];
8323   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
8324   //       k -= 2;
8325   //       long op1 = x[j:j+1];
8326   //       long sum = z[k:k+1];
8327   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
8328   //       z[k:k+1] = sum;
8329   //    }
8330   //    add_one_64(z, k, carry, tmp_regs);
8331   // }
8332 
8333   const Register carry = tmp5;
8334   const Register sum = tmp3;
8335   const Register op1 = tmp4;
8336   Register op2 = tmp2;
8337 
8338   push(zlen);
8339   push(len);
8340   addl(zlen,2);
8341   bind(L_second_loop);
8342   xorq(carry, carry);
8343   subl(zlen, 4);
8344   subl(len, 2);
8345   push(zlen);
8346   push(len);
8347   cmpl(len, 0);
8348   jccb(Assembler::lessEqual, L_second_loop_exit);
8349 
8350   // Multiply an array by one 64 bit long.
8351   if (UseBMI2Instructions) {
8352     op2 = rdxReg;
8353     movq(op2, Address(x, len, Address::times_4,  0));
8354     rorxq(op2, op2, 32);
8355   }
8356   else {
8357     movq(op2, Address(x, len, Address::times_4,  0));
8358     rorq(op2, 32);
8359   }
8360 
8361   bind(L_third_loop);
8362   decrementl(len);
8363   jccb(Assembler::negative, L_third_loop_exit);
8364   decrementl(len);
8365   jccb(Assembler::negative, L_last_x);
8366 
8367   movq(op1, Address(x, len, Address::times_4,  0));
8368   rorq(op1, 32);
8369 
8370   bind(L_multiply);
8371   subl(zlen, 2);
8372   movq(sum, Address(z, zlen, Address::times_4,  0));
8373 
8374   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
8375   if (UseBMI2Instructions) {
8376     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
8377   }
8378   else {
8379     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8380   }
8381 
8382   movq(Address(z, zlen, Address::times_4, 0), sum);
8383 
8384   jmp(L_third_loop);
8385   bind(L_third_loop_exit);
8386 
8387   // Fourth loop
8388   // Add 64 bit long carry into z with carry propogation.
8389   // Uses offsetted zlen.
8390   add_one_64(z, zlen, carry, tmp1);
8391 
8392   pop(len);
8393   pop(zlen);
8394   jmp(L_second_loop);
8395 
8396   // Next infrequent code is moved outside loops.
8397   bind(L_last_x);
8398   movl(op1, Address(x, 0));
8399   jmp(L_multiply);
8400 
8401   bind(L_second_loop_exit);
8402   pop(len);
8403   pop(zlen);
8404   pop(len);
8405   pop(zlen);
8406 
8407   // Fifth loop
8408   // Shift z left 1 bit.
8409   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
8410 
8411   // z[zlen-1] |= x[len-1] & 1;
8412   movl(tmp3, Address(x, len, Address::times_4, -4));
8413   andl(tmp3, 1);
8414   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
8415 
8416   pop(tmp5);
8417   pop(tmp4);
8418   pop(tmp3);
8419   pop(tmp2);
8420   pop(tmp1);
8421 }
8422 
8423 /**
8424  * Helper function for mul_add()
8425  * Multiply the in[] by int k and add to out[] starting at offset offs using
8426  * 128 bit by 32 bit multiply and return the carry in tmp5.
8427  * Only quad int aligned length of in[] is operated on in this function.
8428  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
8429  * This function preserves out, in and k registers.
8430  * len and offset point to the appropriate index in "in" & "out" correspondingly
8431  * tmp5 has the carry.
8432  * other registers are temporary and are modified.
8433  *
8434  */
8435 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
8436   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
8437   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
8438 
8439   Label L_first_loop, L_first_loop_exit;
8440 
8441   movl(tmp1, len);
8442   shrl(tmp1, 2);
8443 
8444   bind(L_first_loop);
8445   subl(tmp1, 1);
8446   jccb(Assembler::negative, L_first_loop_exit);
8447 
8448   subl(len, 4);
8449   subl(offset, 4);
8450 
8451   Register op2 = tmp2;
8452   const Register sum = tmp3;
8453   const Register op1 = tmp4;
8454   const Register carry = tmp5;
8455 
8456   if (UseBMI2Instructions) {
8457     op2 = rdxReg;
8458   }
8459 
8460   movq(op1, Address(in, len, Address::times_4,  8));
8461   rorq(op1, 32);
8462   movq(sum, Address(out, offset, Address::times_4,  8));
8463   rorq(sum, 32);
8464   if (UseBMI2Instructions) {
8465     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
8466   }
8467   else {
8468     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8469   }
8470   // Store back in big endian from little endian
8471   rorq(sum, 0x20);
8472   movq(Address(out, offset, Address::times_4,  8), sum);
8473 
8474   movq(op1, Address(in, len, Address::times_4,  0));
8475   rorq(op1, 32);
8476   movq(sum, Address(out, offset, Address::times_4,  0));
8477   rorq(sum, 32);
8478   if (UseBMI2Instructions) {
8479     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
8480   }
8481   else {
8482     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8483   }
8484   // Store back in big endian from little endian
8485   rorq(sum, 0x20);
8486   movq(Address(out, offset, Address::times_4,  0), sum);
8487 
8488   jmp(L_first_loop);
8489   bind(L_first_loop_exit);
8490 }
8491 
8492 /**
8493  * Code for BigInteger::mulAdd() intrinsic
8494  *
8495  * rdi: out
8496  * rsi: in
8497  * r11: offs (out.length - offset)
8498  * rcx: len
8499  * r8:  k
8500  * r12: tmp1
8501  * r13: tmp2
8502  * r14: tmp3
8503  * r15: tmp4
8504  * rbx: tmp5
8505  * Multiply the in[] by word k and add to out[], return the carry in rax
8506  */
8507 void MacroAssembler::mul_add(Register out, Register in, Register offs,
8508    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
8509    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
8510 
8511   Label L_carry, L_last_in, L_done;
8512 
8513 // carry = 0;
8514 // for (int j=len-1; j >= 0; j--) {
8515 //    long product = (in[j] & LONG_MASK) * kLong +
8516 //                   (out[offs] & LONG_MASK) + carry;
8517 //    out[offs--] = (int)product;
8518 //    carry = product >>> 32;
8519 // }
8520 //
8521   push(tmp1);
8522   push(tmp2);
8523   push(tmp3);
8524   push(tmp4);
8525   push(tmp5);
8526 
8527   Register op2 = tmp2;
8528   const Register sum = tmp3;
8529   const Register op1 = tmp4;
8530   const Register carry =  tmp5;
8531 
8532   if (UseBMI2Instructions) {
8533     op2 = rdxReg;
8534     movl(op2, k);
8535   }
8536   else {
8537     movl(op2, k);
8538   }
8539 
8540   xorq(carry, carry);
8541 
8542   //First loop
8543 
8544   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
8545   //The carry is in tmp5
8546   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
8547 
8548   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
8549   decrementl(len);
8550   jccb(Assembler::negative, L_carry);
8551   decrementl(len);
8552   jccb(Assembler::negative, L_last_in);
8553 
8554   movq(op1, Address(in, len, Address::times_4,  0));
8555   rorq(op1, 32);
8556 
8557   subl(offs, 2);
8558   movq(sum, Address(out, offs, Address::times_4,  0));
8559   rorq(sum, 32);
8560 
8561   if (UseBMI2Instructions) {
8562     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
8563   }
8564   else {
8565     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8566   }
8567 
8568   // Store back in big endian from little endian
8569   rorq(sum, 0x20);
8570   movq(Address(out, offs, Address::times_4,  0), sum);
8571 
8572   testl(len, len);
8573   jccb(Assembler::zero, L_carry);
8574 
8575   //Multiply the last in[] entry, if any
8576   bind(L_last_in);
8577   movl(op1, Address(in, 0));
8578   movl(sum, Address(out, offs, Address::times_4,  -4));
8579 
8580   movl(raxReg, k);
8581   mull(op1); //tmp4 * eax -> edx:eax
8582   addl(sum, carry);
8583   adcl(rdxReg, 0);
8584   addl(sum, raxReg);
8585   adcl(rdxReg, 0);
8586   movl(carry, rdxReg);
8587 
8588   movl(Address(out, offs, Address::times_4,  -4), sum);
8589 
8590   bind(L_carry);
8591   //return tmp5/carry as carry in rax
8592   movl(rax, carry);
8593 
8594   bind(L_done);
8595   pop(tmp5);
8596   pop(tmp4);
8597   pop(tmp3);
8598   pop(tmp2);
8599   pop(tmp1);
8600 }
8601 #endif
8602 
8603 /**
8604  * Emits code to update CRC-32 with a byte value according to constants in table
8605  *
8606  * @param [in,out]crc   Register containing the crc.
8607  * @param [in]val       Register containing the byte to fold into the CRC.
8608  * @param [in]table     Register containing the table of crc constants.
8609  *
8610  * uint32_t crc;
8611  * val = crc_table[(val ^ crc) & 0xFF];
8612  * crc = val ^ (crc >> 8);
8613  *
8614  */
8615 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
8616   xorl(val, crc);
8617   andl(val, 0xFF);
8618   shrl(crc, 8); // unsigned shift
8619   xorl(crc, Address(table, val, Address::times_4, 0));
8620 }
8621 
8622 /**
8623 * Fold four 128-bit data chunks
8624 */
8625 void MacroAssembler::fold_128bit_crc32_avx512(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
8626   evpclmulhdq(xtmp, xK, xcrc, Assembler::AVX_512bit); // [123:64]
8627   evpclmulldq(xcrc, xK, xcrc, Assembler::AVX_512bit); // [63:0]
8628   evpxorq(xcrc, xcrc, Address(buf, offset), Assembler::AVX_512bit /* vector_len */);
8629   evpxorq(xcrc, xcrc, xtmp, Assembler::AVX_512bit /* vector_len */);
8630 }
8631 
8632 /**
8633  * Fold 128-bit data chunk
8634  */
8635 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
8636   if (UseAVX > 0) {
8637     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
8638     vpclmulldq(xcrc, xK, xcrc); // [63:0]
8639     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
8640     pxor(xcrc, xtmp);
8641   } else {
8642     movdqa(xtmp, xcrc);
8643     pclmulhdq(xtmp, xK);   // [123:64]
8644     pclmulldq(xcrc, xK);   // [63:0]
8645     pxor(xcrc, xtmp);
8646     movdqu(xtmp, Address(buf, offset));
8647     pxor(xcrc, xtmp);
8648   }
8649 }
8650 
8651 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
8652   if (UseAVX > 0) {
8653     vpclmulhdq(xtmp, xK, xcrc);
8654     vpclmulldq(xcrc, xK, xcrc);
8655     pxor(xcrc, xbuf);
8656     pxor(xcrc, xtmp);
8657   } else {
8658     movdqa(xtmp, xcrc);
8659     pclmulhdq(xtmp, xK);
8660     pclmulldq(xcrc, xK);
8661     pxor(xcrc, xbuf);
8662     pxor(xcrc, xtmp);
8663   }
8664 }
8665 
8666 /**
8667  * 8-bit folds to compute 32-bit CRC
8668  *
8669  * uint64_t xcrc;
8670  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
8671  */
8672 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
8673   movdl(tmp, xcrc);
8674   andl(tmp, 0xFF);
8675   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
8676   psrldq(xcrc, 1); // unsigned shift one byte
8677   pxor(xcrc, xtmp);
8678 }
8679 
8680 /**
8681  * uint32_t crc;
8682  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
8683  */
8684 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
8685   movl(tmp, crc);
8686   andl(tmp, 0xFF);
8687   shrl(crc, 8);
8688   xorl(crc, Address(table, tmp, Address::times_4, 0));
8689 }
8690 
8691 /**
8692  * @param crc   register containing existing CRC (32-bit)
8693  * @param buf   register pointing to input byte buffer (byte*)
8694  * @param len   register containing number of bytes
8695  * @param table register that will contain address of CRC table
8696  * @param tmp   scratch register
8697  */
8698 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
8699   assert_different_registers(crc, buf, len, table, tmp, rax);
8700 
8701   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
8702   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
8703 
8704   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
8705   // context for the registers used, where all instructions below are using 128-bit mode
8706   // On EVEX without VL and BW, these instructions will all be AVX.
8707   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
8708   notl(crc); // ~crc
8709   cmpl(len, 16);
8710   jcc(Assembler::less, L_tail);
8711 
8712   // Align buffer to 16 bytes
8713   movl(tmp, buf);
8714   andl(tmp, 0xF);
8715   jccb(Assembler::zero, L_aligned);
8716   subl(tmp,  16);
8717   addl(len, tmp);
8718 
8719   align(4);
8720   BIND(L_align_loop);
8721   movsbl(rax, Address(buf, 0)); // load byte with sign extension
8722   update_byte_crc32(crc, rax, table);
8723   increment(buf);
8724   incrementl(tmp);
8725   jccb(Assembler::less, L_align_loop);
8726 
8727   BIND(L_aligned);
8728   movl(tmp, len); // save
8729   shrl(len, 4);
8730   jcc(Assembler::zero, L_tail_restore);
8731 
8732   // Fold total 512 bits of polynomial on each iteration
8733   if (VM_Version::supports_vpclmulqdq()) {
8734     Label Parallel_loop, L_No_Parallel;
8735 
8736     cmpl(len, 8);
8737     jccb(Assembler::less, L_No_Parallel);
8738 
8739     movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
8740     evmovdquq(xmm1, Address(buf, 0), Assembler::AVX_512bit);
8741     movdl(xmm5, crc);
8742     evpxorq(xmm1, xmm1, xmm5, Assembler::AVX_512bit);
8743     addptr(buf, 64);
8744     subl(len, 7);
8745     evshufi64x2(xmm0, xmm0, xmm0, 0x00, Assembler::AVX_512bit); //propagate the mask from 128 bits to 512 bits
8746 
8747     BIND(Parallel_loop);
8748     fold_128bit_crc32_avx512(xmm1, xmm0, xmm5, buf, 0);
8749     addptr(buf, 64);
8750     subl(len, 4);
8751     jcc(Assembler::greater, Parallel_loop);
8752 
8753     vextracti64x2(xmm2, xmm1, 0x01);
8754     vextracti64x2(xmm3, xmm1, 0x02);
8755     vextracti64x2(xmm4, xmm1, 0x03);
8756     jmp(L_fold_512b);
8757 
8758     BIND(L_No_Parallel);
8759   }
8760   // Fold crc into first bytes of vector
8761   movdqa(xmm1, Address(buf, 0));
8762   movdl(rax, xmm1);
8763   xorl(crc, rax);
8764   if (VM_Version::supports_sse4_1()) {
8765     pinsrd(xmm1, crc, 0);
8766   } else {
8767     pinsrw(xmm1, crc, 0);
8768     shrl(crc, 16);
8769     pinsrw(xmm1, crc, 1);
8770   }
8771   addptr(buf, 16);
8772   subl(len, 4); // len > 0
8773   jcc(Assembler::less, L_fold_tail);
8774 
8775   movdqa(xmm2, Address(buf,  0));
8776   movdqa(xmm3, Address(buf, 16));
8777   movdqa(xmm4, Address(buf, 32));
8778   addptr(buf, 48);
8779   subl(len, 3);
8780   jcc(Assembler::lessEqual, L_fold_512b);
8781 
8782   // Fold total 512 bits of polynomial on each iteration,
8783   // 128 bits per each of 4 parallel streams.
8784   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
8785 
8786   align(32);
8787   BIND(L_fold_512b_loop);
8788   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
8789   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
8790   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
8791   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
8792   addptr(buf, 64);
8793   subl(len, 4);
8794   jcc(Assembler::greater, L_fold_512b_loop);
8795 
8796   // Fold 512 bits to 128 bits.
8797   BIND(L_fold_512b);
8798   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
8799   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
8800   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
8801   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
8802 
8803   // Fold the rest of 128 bits data chunks
8804   BIND(L_fold_tail);
8805   addl(len, 3);
8806   jccb(Assembler::lessEqual, L_fold_128b);
8807   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
8808 
8809   BIND(L_fold_tail_loop);
8810   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
8811   addptr(buf, 16);
8812   decrementl(len);
8813   jccb(Assembler::greater, L_fold_tail_loop);
8814 
8815   // Fold 128 bits in xmm1 down into 32 bits in crc register.
8816   BIND(L_fold_128b);
8817   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
8818   if (UseAVX > 0) {
8819     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
8820     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
8821     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
8822   } else {
8823     movdqa(xmm2, xmm0);
8824     pclmulqdq(xmm2, xmm1, 0x1);
8825     movdqa(xmm3, xmm0);
8826     pand(xmm3, xmm2);
8827     pclmulqdq(xmm0, xmm3, 0x1);
8828   }
8829   psrldq(xmm1, 8);
8830   psrldq(xmm2, 4);
8831   pxor(xmm0, xmm1);
8832   pxor(xmm0, xmm2);
8833 
8834   // 8 8-bit folds to compute 32-bit CRC.
8835   for (int j = 0; j < 4; j++) {
8836     fold_8bit_crc32(xmm0, table, xmm1, rax);
8837   }
8838   movdl(crc, xmm0); // mov 32 bits to general register
8839   for (int j = 0; j < 4; j++) {
8840     fold_8bit_crc32(crc, table, rax);
8841   }
8842 
8843   BIND(L_tail_restore);
8844   movl(len, tmp); // restore
8845   BIND(L_tail);
8846   andl(len, 0xf);
8847   jccb(Assembler::zero, L_exit);
8848 
8849   // Fold the rest of bytes
8850   align(4);
8851   BIND(L_tail_loop);
8852   movsbl(rax, Address(buf, 0)); // load byte with sign extension
8853   update_byte_crc32(crc, rax, table);
8854   increment(buf);
8855   decrementl(len);
8856   jccb(Assembler::greater, L_tail_loop);
8857 
8858   BIND(L_exit);
8859   notl(crc); // ~c
8860 }
8861 
8862 #ifdef _LP64
8863 // S. Gueron / Information Processing Letters 112 (2012) 184
8864 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
8865 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
8866 // Output: the 64-bit carry-less product of B * CONST
8867 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
8868                                      Register tmp1, Register tmp2, Register tmp3) {
8869   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
8870   if (n > 0) {
8871     addq(tmp3, n * 256 * 8);
8872   }
8873   //    Q1 = TABLEExt[n][B & 0xFF];
8874   movl(tmp1, in);
8875   andl(tmp1, 0x000000FF);
8876   shll(tmp1, 3);
8877   addq(tmp1, tmp3);
8878   movq(tmp1, Address(tmp1, 0));
8879 
8880   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
8881   movl(tmp2, in);
8882   shrl(tmp2, 8);
8883   andl(tmp2, 0x000000FF);
8884   shll(tmp2, 3);
8885   addq(tmp2, tmp3);
8886   movq(tmp2, Address(tmp2, 0));
8887 
8888   shlq(tmp2, 8);
8889   xorq(tmp1, tmp2);
8890 
8891   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
8892   movl(tmp2, in);
8893   shrl(tmp2, 16);
8894   andl(tmp2, 0x000000FF);
8895   shll(tmp2, 3);
8896   addq(tmp2, tmp3);
8897   movq(tmp2, Address(tmp2, 0));
8898 
8899   shlq(tmp2, 16);
8900   xorq(tmp1, tmp2);
8901 
8902   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
8903   shrl(in, 24);
8904   andl(in, 0x000000FF);
8905   shll(in, 3);
8906   addq(in, tmp3);
8907   movq(in, Address(in, 0));
8908 
8909   shlq(in, 24);
8910   xorq(in, tmp1);
8911   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
8912 }
8913 
8914 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
8915                                       Register in_out,
8916                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
8917                                       XMMRegister w_xtmp2,
8918                                       Register tmp1,
8919                                       Register n_tmp2, Register n_tmp3) {
8920   if (is_pclmulqdq_supported) {
8921     movdl(w_xtmp1, in_out); // modified blindly
8922 
8923     movl(tmp1, const_or_pre_comp_const_index);
8924     movdl(w_xtmp2, tmp1);
8925     pclmulqdq(w_xtmp1, w_xtmp2, 0);
8926 
8927     movdq(in_out, w_xtmp1);
8928   } else {
8929     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
8930   }
8931 }
8932 
8933 // Recombination Alternative 2: No bit-reflections
8934 // T1 = (CRC_A * U1) << 1
8935 // T2 = (CRC_B * U2) << 1
8936 // C1 = T1 >> 32
8937 // C2 = T2 >> 32
8938 // T1 = T1 & 0xFFFFFFFF
8939 // T2 = T2 & 0xFFFFFFFF
8940 // T1 = CRC32(0, T1)
8941 // T2 = CRC32(0, T2)
8942 // C1 = C1 ^ T1
8943 // C2 = C2 ^ T2
8944 // CRC = C1 ^ C2 ^ CRC_C
8945 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,
8946                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
8947                                      Register tmp1, Register tmp2,
8948                                      Register n_tmp3) {
8949   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
8950   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
8951   shlq(in_out, 1);
8952   movl(tmp1, in_out);
8953   shrq(in_out, 32);
8954   xorl(tmp2, tmp2);
8955   crc32(tmp2, tmp1, 4);
8956   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
8957   shlq(in1, 1);
8958   movl(tmp1, in1);
8959   shrq(in1, 32);
8960   xorl(tmp2, tmp2);
8961   crc32(tmp2, tmp1, 4);
8962   xorl(in1, tmp2);
8963   xorl(in_out, in1);
8964   xorl(in_out, in2);
8965 }
8966 
8967 // Set N to predefined value
8968 // Subtract from a lenght of a buffer
8969 // execute in a loop:
8970 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
8971 // for i = 1 to N do
8972 //  CRC_A = CRC32(CRC_A, A[i])
8973 //  CRC_B = CRC32(CRC_B, B[i])
8974 //  CRC_C = CRC32(CRC_C, C[i])
8975 // end for
8976 // Recombine
8977 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,
8978                                        Register in_out1, Register in_out2, Register in_out3,
8979                                        Register tmp1, Register tmp2, Register tmp3,
8980                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
8981                                        Register tmp4, Register tmp5,
8982                                        Register n_tmp6) {
8983   Label L_processPartitions;
8984   Label L_processPartition;
8985   Label L_exit;
8986 
8987   bind(L_processPartitions);
8988   cmpl(in_out1, 3 * size);
8989   jcc(Assembler::less, L_exit);
8990     xorl(tmp1, tmp1);
8991     xorl(tmp2, tmp2);
8992     movq(tmp3, in_out2);
8993     addq(tmp3, size);
8994 
8995     bind(L_processPartition);
8996       crc32(in_out3, Address(in_out2, 0), 8);
8997       crc32(tmp1, Address(in_out2, size), 8);
8998       crc32(tmp2, Address(in_out2, size * 2), 8);
8999       addq(in_out2, 8);
9000       cmpq(in_out2, tmp3);
9001       jcc(Assembler::less, L_processPartition);
9002     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
9003             w_xtmp1, w_xtmp2, w_xtmp3,
9004             tmp4, tmp5,
9005             n_tmp6);
9006     addq(in_out2, 2 * size);
9007     subl(in_out1, 3 * size);
9008     jmp(L_processPartitions);
9009 
9010   bind(L_exit);
9011 }
9012 #else
9013 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
9014                                      Register tmp1, Register tmp2, Register tmp3,
9015                                      XMMRegister xtmp1, XMMRegister xtmp2) {
9016   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
9017   if (n > 0) {
9018     addl(tmp3, n * 256 * 8);
9019   }
9020   //    Q1 = TABLEExt[n][B & 0xFF];
9021   movl(tmp1, in_out);
9022   andl(tmp1, 0x000000FF);
9023   shll(tmp1, 3);
9024   addl(tmp1, tmp3);
9025   movq(xtmp1, Address(tmp1, 0));
9026 
9027   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
9028   movl(tmp2, in_out);
9029   shrl(tmp2, 8);
9030   andl(tmp2, 0x000000FF);
9031   shll(tmp2, 3);
9032   addl(tmp2, tmp3);
9033   movq(xtmp2, Address(tmp2, 0));
9034 
9035   psllq(xtmp2, 8);
9036   pxor(xtmp1, xtmp2);
9037 
9038   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
9039   movl(tmp2, in_out);
9040   shrl(tmp2, 16);
9041   andl(tmp2, 0x000000FF);
9042   shll(tmp2, 3);
9043   addl(tmp2, tmp3);
9044   movq(xtmp2, Address(tmp2, 0));
9045 
9046   psllq(xtmp2, 16);
9047   pxor(xtmp1, xtmp2);
9048 
9049   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
9050   shrl(in_out, 24);
9051   andl(in_out, 0x000000FF);
9052   shll(in_out, 3);
9053   addl(in_out, tmp3);
9054   movq(xtmp2, Address(in_out, 0));
9055 
9056   psllq(xtmp2, 24);
9057   pxor(xtmp1, xtmp2); // Result in CXMM
9058   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
9059 }
9060 
9061 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
9062                                       Register in_out,
9063                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
9064                                       XMMRegister w_xtmp2,
9065                                       Register tmp1,
9066                                       Register n_tmp2, Register n_tmp3) {
9067   if (is_pclmulqdq_supported) {
9068     movdl(w_xtmp1, in_out);
9069 
9070     movl(tmp1, const_or_pre_comp_const_index);
9071     movdl(w_xtmp2, tmp1);
9072     pclmulqdq(w_xtmp1, w_xtmp2, 0);
9073     // Keep result in XMM since GPR is 32 bit in length
9074   } else {
9075     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
9076   }
9077 }
9078 
9079 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,
9080                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9081                                      Register tmp1, Register tmp2,
9082                                      Register n_tmp3) {
9083   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9084   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9085 
9086   psllq(w_xtmp1, 1);
9087   movdl(tmp1, w_xtmp1);
9088   psrlq(w_xtmp1, 32);
9089   movdl(in_out, w_xtmp1);
9090 
9091   xorl(tmp2, tmp2);
9092   crc32(tmp2, tmp1, 4);
9093   xorl(in_out, tmp2);
9094 
9095   psllq(w_xtmp2, 1);
9096   movdl(tmp1, w_xtmp2);
9097   psrlq(w_xtmp2, 32);
9098   movdl(in1, w_xtmp2);
9099 
9100   xorl(tmp2, tmp2);
9101   crc32(tmp2, tmp1, 4);
9102   xorl(in1, tmp2);
9103   xorl(in_out, in1);
9104   xorl(in_out, in2);
9105 }
9106 
9107 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,
9108                                        Register in_out1, Register in_out2, Register in_out3,
9109                                        Register tmp1, Register tmp2, Register tmp3,
9110                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9111                                        Register tmp4, Register tmp5,
9112                                        Register n_tmp6) {
9113   Label L_processPartitions;
9114   Label L_processPartition;
9115   Label L_exit;
9116 
9117   bind(L_processPartitions);
9118   cmpl(in_out1, 3 * size);
9119   jcc(Assembler::less, L_exit);
9120     xorl(tmp1, tmp1);
9121     xorl(tmp2, tmp2);
9122     movl(tmp3, in_out2);
9123     addl(tmp3, size);
9124 
9125     bind(L_processPartition);
9126       crc32(in_out3, Address(in_out2, 0), 4);
9127       crc32(tmp1, Address(in_out2, size), 4);
9128       crc32(tmp2, Address(in_out2, size*2), 4);
9129       crc32(in_out3, Address(in_out2, 0+4), 4);
9130       crc32(tmp1, Address(in_out2, size+4), 4);
9131       crc32(tmp2, Address(in_out2, size*2+4), 4);
9132       addl(in_out2, 8);
9133       cmpl(in_out2, tmp3);
9134       jcc(Assembler::less, L_processPartition);
9135 
9136         push(tmp3);
9137         push(in_out1);
9138         push(in_out2);
9139         tmp4 = tmp3;
9140         tmp5 = in_out1;
9141         n_tmp6 = in_out2;
9142 
9143       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
9144             w_xtmp1, w_xtmp2, w_xtmp3,
9145             tmp4, tmp5,
9146             n_tmp6);
9147 
9148         pop(in_out2);
9149         pop(in_out1);
9150         pop(tmp3);
9151 
9152     addl(in_out2, 2 * size);
9153     subl(in_out1, 3 * size);
9154     jmp(L_processPartitions);
9155 
9156   bind(L_exit);
9157 }
9158 #endif //LP64
9159 
9160 #ifdef _LP64
9161 // Algorithm 2: Pipelined usage of the CRC32 instruction.
9162 // Input: A buffer I of L bytes.
9163 // Output: the CRC32C value of the buffer.
9164 // Notations:
9165 // Write L = 24N + r, with N = floor (L/24).
9166 // r = L mod 24 (0 <= r < 24).
9167 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
9168 // N quadwords, and R consists of r bytes.
9169 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
9170 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
9171 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
9172 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
9173 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
9174                                           Register tmp1, Register tmp2, Register tmp3,
9175                                           Register tmp4, Register tmp5, Register tmp6,
9176                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9177                                           bool is_pclmulqdq_supported) {
9178   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
9179   Label L_wordByWord;
9180   Label L_byteByByteProlog;
9181   Label L_byteByByte;
9182   Label L_exit;
9183 
9184   if (is_pclmulqdq_supported ) {
9185     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
9186     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
9187 
9188     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
9189     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
9190 
9191     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
9192     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
9193     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
9194   } else {
9195     const_or_pre_comp_const_index[0] = 1;
9196     const_or_pre_comp_const_index[1] = 0;
9197 
9198     const_or_pre_comp_const_index[2] = 3;
9199     const_or_pre_comp_const_index[3] = 2;
9200 
9201     const_or_pre_comp_const_index[4] = 5;
9202     const_or_pre_comp_const_index[5] = 4;
9203    }
9204   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
9205                     in2, in1, in_out,
9206                     tmp1, tmp2, tmp3,
9207                     w_xtmp1, w_xtmp2, w_xtmp3,
9208                     tmp4, tmp5,
9209                     tmp6);
9210   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
9211                     in2, in1, in_out,
9212                     tmp1, tmp2, tmp3,
9213                     w_xtmp1, w_xtmp2, w_xtmp3,
9214                     tmp4, tmp5,
9215                     tmp6);
9216   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
9217                     in2, in1, in_out,
9218                     tmp1, tmp2, tmp3,
9219                     w_xtmp1, w_xtmp2, w_xtmp3,
9220                     tmp4, tmp5,
9221                     tmp6);
9222   movl(tmp1, in2);
9223   andl(tmp1, 0x00000007);
9224   negl(tmp1);
9225   addl(tmp1, in2);
9226   addq(tmp1, in1);
9227 
9228   BIND(L_wordByWord);
9229   cmpq(in1, tmp1);
9230   jcc(Assembler::greaterEqual, L_byteByByteProlog);
9231     crc32(in_out, Address(in1, 0), 4);
9232     addq(in1, 4);
9233     jmp(L_wordByWord);
9234 
9235   BIND(L_byteByByteProlog);
9236   andl(in2, 0x00000007);
9237   movl(tmp2, 1);
9238 
9239   BIND(L_byteByByte);
9240   cmpl(tmp2, in2);
9241   jccb(Assembler::greater, L_exit);
9242     crc32(in_out, Address(in1, 0), 1);
9243     incq(in1);
9244     incl(tmp2);
9245     jmp(L_byteByByte);
9246 
9247   BIND(L_exit);
9248 }
9249 #else
9250 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
9251                                           Register tmp1, Register  tmp2, Register tmp3,
9252                                           Register tmp4, Register  tmp5, Register tmp6,
9253                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9254                                           bool is_pclmulqdq_supported) {
9255   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
9256   Label L_wordByWord;
9257   Label L_byteByByteProlog;
9258   Label L_byteByByte;
9259   Label L_exit;
9260 
9261   if (is_pclmulqdq_supported) {
9262     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
9263     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
9264 
9265     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
9266     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
9267 
9268     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
9269     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
9270   } else {
9271     const_or_pre_comp_const_index[0] = 1;
9272     const_or_pre_comp_const_index[1] = 0;
9273 
9274     const_or_pre_comp_const_index[2] = 3;
9275     const_or_pre_comp_const_index[3] = 2;
9276 
9277     const_or_pre_comp_const_index[4] = 5;
9278     const_or_pre_comp_const_index[5] = 4;
9279   }
9280   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
9281                     in2, in1, in_out,
9282                     tmp1, tmp2, tmp3,
9283                     w_xtmp1, w_xtmp2, w_xtmp3,
9284                     tmp4, tmp5,
9285                     tmp6);
9286   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
9287                     in2, in1, in_out,
9288                     tmp1, tmp2, tmp3,
9289                     w_xtmp1, w_xtmp2, w_xtmp3,
9290                     tmp4, tmp5,
9291                     tmp6);
9292   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
9293                     in2, in1, in_out,
9294                     tmp1, tmp2, tmp3,
9295                     w_xtmp1, w_xtmp2, w_xtmp3,
9296                     tmp4, tmp5,
9297                     tmp6);
9298   movl(tmp1, in2);
9299   andl(tmp1, 0x00000007);
9300   negl(tmp1);
9301   addl(tmp1, in2);
9302   addl(tmp1, in1);
9303 
9304   BIND(L_wordByWord);
9305   cmpl(in1, tmp1);
9306   jcc(Assembler::greaterEqual, L_byteByByteProlog);
9307     crc32(in_out, Address(in1,0), 4);
9308     addl(in1, 4);
9309     jmp(L_wordByWord);
9310 
9311   BIND(L_byteByByteProlog);
9312   andl(in2, 0x00000007);
9313   movl(tmp2, 1);
9314 
9315   BIND(L_byteByByte);
9316   cmpl(tmp2, in2);
9317   jccb(Assembler::greater, L_exit);
9318     movb(tmp1, Address(in1, 0));
9319     crc32(in_out, tmp1, 1);
9320     incl(in1);
9321     incl(tmp2);
9322     jmp(L_byteByByte);
9323 
9324   BIND(L_exit);
9325 }
9326 #endif // LP64
9327 #undef BIND
9328 #undef BLOCK_COMMENT
9329 
9330 // Compress char[] array to byte[].
9331 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
9332 //   @HotSpotIntrinsicCandidate
9333 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
9334 //     for (int i = 0; i < len; i++) {
9335 //       int c = src[srcOff++];
9336 //       if (c >>> 8 != 0) {
9337 //         return 0;
9338 //       }
9339 //       dst[dstOff++] = (byte)c;
9340 //     }
9341 //     return len;
9342 //   }
9343 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
9344   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
9345   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
9346   Register tmp5, Register result) {
9347   Label copy_chars_loop, return_length, return_zero, done;
9348 
9349   // rsi: src
9350   // rdi: dst
9351   // rdx: len
9352   // rcx: tmp5
9353   // rax: result
9354 
9355   // rsi holds start addr of source char[] to be compressed
9356   // rdi holds start addr of destination byte[]
9357   // rdx holds length
9358 
9359   assert(len != result, "");
9360 
9361   // save length for return
9362   push(len);
9363 
9364   if ((UseAVX > 2) && // AVX512
9365     VM_Version::supports_avx512vlbw() &&
9366     VM_Version::supports_bmi2()) {
9367 
9368     Label copy_32_loop, copy_loop_tail, below_threshold;
9369 
9370     // alignment
9371     Label post_alignment;
9372 
9373     // if length of the string is less than 16, handle it in an old fashioned way
9374     testl(len, -32);
9375     jcc(Assembler::zero, below_threshold);
9376 
9377     // First check whether a character is compressable ( <= 0xFF).
9378     // Create mask to test for Unicode chars inside zmm vector
9379     movl(result, 0x00FF);
9380     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
9381 
9382     testl(len, -64);
9383     jcc(Assembler::zero, post_alignment);
9384 
9385     movl(tmp5, dst);
9386     andl(tmp5, (32 - 1));
9387     negl(tmp5);
9388     andl(tmp5, (32 - 1));
9389 
9390     // bail out when there is nothing to be done
9391     testl(tmp5, 0xFFFFFFFF);
9392     jcc(Assembler::zero, post_alignment);
9393 
9394     // ~(~0 << len), where len is the # of remaining elements to process
9395     movl(result, 0xFFFFFFFF);
9396     shlxl(result, result, tmp5);
9397     notl(result);
9398     kmovdl(k3, result);
9399 
9400     evmovdquw(tmp1Reg, k3, Address(src, 0), Assembler::AVX_512bit);
9401     evpcmpuw(k2, k3, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
9402     ktestd(k2, k3);
9403     jcc(Assembler::carryClear, return_zero);
9404 
9405     evpmovwb(Address(dst, 0), k3, tmp1Reg, Assembler::AVX_512bit);
9406 
9407     addptr(src, tmp5);
9408     addptr(src, tmp5);
9409     addptr(dst, tmp5);
9410     subl(len, tmp5);
9411 
9412     bind(post_alignment);
9413     // end of alignment
9414 
9415     movl(tmp5, len);
9416     andl(tmp5, (32 - 1));    // tail count (in chars)
9417     andl(len, ~(32 - 1));    // vector count (in chars)
9418     jcc(Assembler::zero, copy_loop_tail);
9419 
9420     lea(src, Address(src, len, Address::times_2));
9421     lea(dst, Address(dst, len, Address::times_1));
9422     negptr(len);
9423 
9424     bind(copy_32_loop);
9425     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
9426     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
9427     kortestdl(k2, k2);
9428     jcc(Assembler::carryClear, return_zero);
9429 
9430     // All elements in current processed chunk are valid candidates for
9431     // compression. Write a truncated byte elements to the memory.
9432     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
9433     addptr(len, 32);
9434     jcc(Assembler::notZero, copy_32_loop);
9435 
9436     bind(copy_loop_tail);
9437     // bail out when there is nothing to be done
9438     testl(tmp5, 0xFFFFFFFF);
9439     jcc(Assembler::zero, return_length);
9440 
9441     movl(len, tmp5);
9442 
9443     // ~(~0 << len), where len is the # of remaining elements to process
9444     movl(result, 0xFFFFFFFF);
9445     shlxl(result, result, len);
9446     notl(result);
9447 
9448     kmovdl(k3, result);
9449 
9450     evmovdquw(tmp1Reg, k3, Address(src, 0), Assembler::AVX_512bit);
9451     evpcmpuw(k2, k3, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
9452     ktestd(k2, k3);
9453     jcc(Assembler::carryClear, return_zero);
9454 
9455     evpmovwb(Address(dst, 0), k3, tmp1Reg, Assembler::AVX_512bit);
9456     jmp(return_length);
9457 
9458     bind(below_threshold);
9459   }
9460 
9461   if (UseSSE42Intrinsics) {
9462     Label copy_32_loop, copy_16, copy_tail;
9463 
9464     movl(result, len);
9465 
9466     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
9467 
9468     // vectored compression
9469     andl(len, 0xfffffff0);    // vector count (in chars)
9470     andl(result, 0x0000000f);    // tail count (in chars)
9471     testl(len, len);
9472     jcc(Assembler::zero, copy_16);
9473 
9474     // compress 16 chars per iter
9475     movdl(tmp1Reg, tmp5);
9476     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
9477     pxor(tmp4Reg, tmp4Reg);
9478 
9479     lea(src, Address(src, len, Address::times_2));
9480     lea(dst, Address(dst, len, Address::times_1));
9481     negptr(len);
9482 
9483     bind(copy_32_loop);
9484     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
9485     por(tmp4Reg, tmp2Reg);
9486     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
9487     por(tmp4Reg, tmp3Reg);
9488     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
9489     jcc(Assembler::notZero, return_zero);
9490     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
9491     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
9492     addptr(len, 16);
9493     jcc(Assembler::notZero, copy_32_loop);
9494 
9495     // compress next vector of 8 chars (if any)
9496     bind(copy_16);
9497     movl(len, result);
9498     andl(len, 0xfffffff8);    // vector count (in chars)
9499     andl(result, 0x00000007);    // tail count (in chars)
9500     testl(len, len);
9501     jccb(Assembler::zero, copy_tail);
9502 
9503     movdl(tmp1Reg, tmp5);
9504     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
9505     pxor(tmp3Reg, tmp3Reg);
9506 
9507     movdqu(tmp2Reg, Address(src, 0));
9508     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
9509     jccb(Assembler::notZero, return_zero);
9510     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
9511     movq(Address(dst, 0), tmp2Reg);
9512     addptr(src, 16);
9513     addptr(dst, 8);
9514 
9515     bind(copy_tail);
9516     movl(len, result);
9517   }
9518   // compress 1 char per iter
9519   testl(len, len);
9520   jccb(Assembler::zero, return_length);
9521   lea(src, Address(src, len, Address::times_2));
9522   lea(dst, Address(dst, len, Address::times_1));
9523   negptr(len);
9524 
9525   bind(copy_chars_loop);
9526   load_unsigned_short(result, Address(src, len, Address::times_2));
9527   testl(result, 0xff00);      // check if Unicode char
9528   jccb(Assembler::notZero, return_zero);
9529   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
9530   increment(len);
9531   jcc(Assembler::notZero, copy_chars_loop);
9532 
9533   // if compression succeeded, return length
9534   bind(return_length);
9535   pop(result);
9536   jmpb(done);
9537 
9538   // if compression failed, return 0
9539   bind(return_zero);
9540   xorl(result, result);
9541   addptr(rsp, wordSize);
9542 
9543   bind(done);
9544 }
9545 
9546 // Inflate byte[] array to char[].
9547 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
9548 //   @HotSpotIntrinsicCandidate
9549 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
9550 //     for (int i = 0; i < len; i++) {
9551 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
9552 //     }
9553 //   }
9554 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
9555   XMMRegister tmp1, Register tmp2) {
9556   Label copy_chars_loop, done, below_threshold;
9557   // rsi: src
9558   // rdi: dst
9559   // rdx: len
9560   // rcx: tmp2
9561 
9562   // rsi holds start addr of source byte[] to be inflated
9563   // rdi holds start addr of destination char[]
9564   // rdx holds length
9565   assert_different_registers(src, dst, len, tmp2);
9566 
9567   if ((UseAVX > 2) && // AVX512
9568     VM_Version::supports_avx512vlbw() &&
9569     VM_Version::supports_bmi2()) {
9570 
9571     Label copy_32_loop, copy_tail;
9572     Register tmp3_aliased = len;
9573 
9574     // if length of the string is less than 16, handle it in an old fashioned way
9575     testl(len, -16);
9576     jcc(Assembler::zero, below_threshold);
9577 
9578     // In order to use only one arithmetic operation for the main loop we use
9579     // this pre-calculation
9580     movl(tmp2, len);
9581     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
9582     andl(len, -32);     // vector count
9583     jccb(Assembler::zero, copy_tail);
9584 
9585     lea(src, Address(src, len, Address::times_1));
9586     lea(dst, Address(dst, len, Address::times_2));
9587     negptr(len);
9588 
9589 
9590     // inflate 32 chars per iter
9591     bind(copy_32_loop);
9592     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
9593     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
9594     addptr(len, 32);
9595     jcc(Assembler::notZero, copy_32_loop);
9596 
9597     bind(copy_tail);
9598     // bail out when there is nothing to be done
9599     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
9600     jcc(Assembler::zero, done);
9601 
9602     // ~(~0 << length), where length is the # of remaining elements to process
9603     movl(tmp3_aliased, -1);
9604     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
9605     notl(tmp3_aliased);
9606     kmovdl(k2, tmp3_aliased);
9607     evpmovzxbw(tmp1, k2, Address(src, 0), Assembler::AVX_512bit);
9608     evmovdquw(Address(dst, 0), k2, tmp1, Assembler::AVX_512bit);
9609 
9610     jmp(done);
9611   }
9612   if (UseSSE42Intrinsics) {
9613     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
9614 
9615     movl(tmp2, len);
9616 
9617     if (UseAVX > 1) {
9618       andl(tmp2, (16 - 1));
9619       andl(len, -16);
9620       jccb(Assembler::zero, copy_new_tail);
9621     } else {
9622       andl(tmp2, 0x00000007);   // tail count (in chars)
9623       andl(len, 0xfffffff8);    // vector count (in chars)
9624       jccb(Assembler::zero, copy_tail);
9625     }
9626 
9627     // vectored inflation
9628     lea(src, Address(src, len, Address::times_1));
9629     lea(dst, Address(dst, len, Address::times_2));
9630     negptr(len);
9631 
9632     if (UseAVX > 1) {
9633       bind(copy_16_loop);
9634       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
9635       vmovdqu(Address(dst, len, Address::times_2), tmp1);
9636       addptr(len, 16);
9637       jcc(Assembler::notZero, copy_16_loop);
9638 
9639       bind(below_threshold);
9640       bind(copy_new_tail);
9641       if ((UseAVX > 2) &&
9642         VM_Version::supports_avx512vlbw() &&
9643         VM_Version::supports_bmi2()) {
9644         movl(tmp2, len);
9645       } else {
9646         movl(len, tmp2);
9647       }
9648       andl(tmp2, 0x00000007);
9649       andl(len, 0xFFFFFFF8);
9650       jccb(Assembler::zero, copy_tail);
9651 
9652       pmovzxbw(tmp1, Address(src, 0));
9653       movdqu(Address(dst, 0), tmp1);
9654       addptr(src, 8);
9655       addptr(dst, 2 * 8);
9656 
9657       jmp(copy_tail, true);
9658     }
9659 
9660     // inflate 8 chars per iter
9661     bind(copy_8_loop);
9662     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
9663     movdqu(Address(dst, len, Address::times_2), tmp1);
9664     addptr(len, 8);
9665     jcc(Assembler::notZero, copy_8_loop);
9666 
9667     bind(copy_tail);
9668     movl(len, tmp2);
9669 
9670     cmpl(len, 4);
9671     jccb(Assembler::less, copy_bytes);
9672 
9673     movdl(tmp1, Address(src, 0));  // load 4 byte chars
9674     pmovzxbw(tmp1, tmp1);
9675     movq(Address(dst, 0), tmp1);
9676     subptr(len, 4);
9677     addptr(src, 4);
9678     addptr(dst, 8);
9679 
9680     bind(copy_bytes);
9681   } else {
9682     bind(below_threshold);
9683   }
9684 
9685   testl(len, len);
9686   jccb(Assembler::zero, done);
9687   lea(src, Address(src, len, Address::times_1));
9688   lea(dst, Address(dst, len, Address::times_2));
9689   negptr(len);
9690 
9691   // inflate 1 char per iter
9692   bind(copy_chars_loop);
9693   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
9694   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
9695   increment(len);
9696   jcc(Assembler::notZero, copy_chars_loop);
9697 
9698   bind(done);
9699 }
9700 
9701 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
9702   switch (cond) {
9703     // Note some conditions are synonyms for others
9704     case Assembler::zero:         return Assembler::notZero;
9705     case Assembler::notZero:      return Assembler::zero;
9706     case Assembler::less:         return Assembler::greaterEqual;
9707     case Assembler::lessEqual:    return Assembler::greater;
9708     case Assembler::greater:      return Assembler::lessEqual;
9709     case Assembler::greaterEqual: return Assembler::less;
9710     case Assembler::below:        return Assembler::aboveEqual;
9711     case Assembler::belowEqual:   return Assembler::above;
9712     case Assembler::above:        return Assembler::belowEqual;
9713     case Assembler::aboveEqual:   return Assembler::below;
9714     case Assembler::overflow:     return Assembler::noOverflow;
9715     case Assembler::noOverflow:   return Assembler::overflow;
9716     case Assembler::negative:     return Assembler::positive;
9717     case Assembler::positive:     return Assembler::negative;
9718     case Assembler::parity:       return Assembler::noParity;
9719     case Assembler::noParity:     return Assembler::parity;
9720   }
9721   ShouldNotReachHere(); return Assembler::overflow;
9722 }
9723 
9724 SkipIfEqual::SkipIfEqual(
9725     MacroAssembler* masm, const bool* flag_addr, bool value) {
9726   _masm = masm;
9727   _masm->cmp8(ExternalAddress((address)flag_addr), value);
9728   _masm->jcc(Assembler::equal, _label);
9729 }
9730 
9731 SkipIfEqual::~SkipIfEqual() {
9732   _masm->bind(_label);
9733 }
9734 
9735 // 32-bit Windows has its own fast-path implementation
9736 // of get_thread
9737 #if !defined(WIN32) || defined(_LP64)
9738 
9739 // This is simply a call to Thread::current()
9740 void MacroAssembler::get_thread(Register thread) {
9741   if (thread != rax) {
9742     push(rax);
9743   }
9744   LP64_ONLY(push(rdi);)
9745   LP64_ONLY(push(rsi);)
9746   push(rdx);
9747   push(rcx);
9748 #ifdef _LP64
9749   push(r8);
9750   push(r9);
9751   push(r10);
9752   push(r11);
9753 #endif
9754 
9755   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
9756 
9757 #ifdef _LP64
9758   pop(r11);
9759   pop(r10);
9760   pop(r9);
9761   pop(r8);
9762 #endif
9763   pop(rcx);
9764   pop(rdx);
9765   LP64_ONLY(pop(rsi);)
9766   LP64_ONLY(pop(rdi);)
9767   if (thread != rax) {
9768     mov(thread, rax);
9769     pop(rax);
9770   }
9771 }
9772 
9773 #endif
--- EOF ---