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