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