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