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