1 /*
   2  * Copyright (c) 1997, 2017, 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/macroAssembler.inline.hpp"
  27 #include "compiler/disassembler.hpp"
  28 #include "gc/shared/cardTableModRefBS.hpp"
  29 #include "gc/shared/collectedHeap.inline.hpp"
  30 #include "interpreter/interpreter.hpp"
  31 #include "memory/resourceArea.hpp"
  32 #include "memory/universe.hpp"
  33 #include "oops/klass.inline.hpp"
  34 #include "prims/jvm.h"
  35 #include "prims/methodHandles.hpp"
  36 #include "runtime/biasedLocking.hpp"
  37 #include "runtime/interfaceSupport.hpp"
  38 #include "runtime/objectMonitor.hpp"
  39 #include "runtime/os.inline.hpp"
  40 #include "runtime/sharedRuntime.hpp"
  41 #include "runtime/stubRoutines.hpp"
  42 #include "utilities/align.hpp"
  43 #include "utilities/macros.hpp"
  44 #if INCLUDE_ALL_GCS
  45 #include "gc/g1/g1CollectedHeap.inline.hpp"
  46 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  47 #include "gc/g1/heapRegion.hpp"
  48 #endif // INCLUDE_ALL_GCS
  49 #ifdef COMPILER2
  50 #include "opto/intrinsicnode.hpp"
  51 #endif
  52 
  53 #ifdef PRODUCT
  54 #define BLOCK_COMMENT(str) /* nothing */
  55 #define STOP(error) stop(error)
  56 #else
  57 #define BLOCK_COMMENT(str) block_comment(str)
  58 #define STOP(error) block_comment(error); stop(error)
  59 #endif
  60 
  61 // Convert the raw encoding form into the form expected by the
  62 // constructor for Address.
  63 Address Address::make_raw(int base, int index, int scale, int disp, relocInfo::relocType disp_reloc) {
  64   assert(scale == 0, "not supported");
  65   RelocationHolder rspec;
  66   if (disp_reloc != relocInfo::none) {
  67     rspec = Relocation::spec_simple(disp_reloc);
  68   }
  69 
  70   Register rindex = as_Register(index);
  71   if (rindex != G0) {
  72     Address madr(as_Register(base), rindex);
  73     madr._rspec = rspec;
  74     return madr;
  75   } else {
  76     Address madr(as_Register(base), disp);
  77     madr._rspec = rspec;
  78     return madr;
  79   }
  80 }
  81 
  82 Address Argument::address_in_frame() const {
  83   // Warning: In LP64 mode disp will occupy more than 10 bits, but
  84   //          op codes such as ld or ldx, only access disp() to get
  85   //          their simm13 argument.
  86   int disp = ((_number - Argument::n_register_parameters + frame::memory_parameter_word_sp_offset) * BytesPerWord) + STACK_BIAS;
  87   if (is_in())
  88     return Address(FP, disp); // In argument.
  89   else
  90     return Address(SP, disp); // Out argument.
  91 }
  92 
  93 static const char* argumentNames[][2] = {
  94   {"A0","P0"}, {"A1","P1"}, {"A2","P2"}, {"A3","P3"}, {"A4","P4"},
  95   {"A5","P5"}, {"A6","P6"}, {"A7","P7"}, {"A8","P8"}, {"A9","P9"},
  96   {"A(n>9)","P(n>9)"}
  97 };
  98 
  99 const char* Argument::name() const {
 100   int nofArgs = sizeof argumentNames / sizeof argumentNames[0];
 101   int num = number();
 102   if (num >= nofArgs)  num = nofArgs - 1;
 103   return argumentNames[num][is_in() ? 1 : 0];
 104 }
 105 
 106 #ifdef ASSERT
 107 // On RISC, there's no benefit to verifying instruction boundaries.
 108 bool AbstractAssembler::pd_check_instruction_mark() { return false; }
 109 #endif
 110 
 111 // Patch instruction inst at offset inst_pos to refer to dest_pos
 112 // and return the resulting instruction.
 113 // We should have pcs, not offsets, but since all is relative, it will work out
 114 // OK.
 115 int MacroAssembler::patched_branch(int dest_pos, int inst, int inst_pos) {
 116   int m; // mask for displacement field
 117   int v; // new value for displacement field
 118   const int word_aligned_ones = -4;
 119   switch (inv_op(inst)) {
 120   default: ShouldNotReachHere();
 121   case call_op:    m = wdisp(word_aligned_ones, 0, 30);  v = wdisp(dest_pos, inst_pos, 30); break;
 122   case branch_op:
 123     switch (inv_op2(inst)) {
 124       case fbp_op2:    m = wdisp(  word_aligned_ones, 0, 19);  v = wdisp(  dest_pos, inst_pos, 19); break;
 125       case bp_op2:     m = wdisp(  word_aligned_ones, 0, 19);  v = wdisp(  dest_pos, inst_pos, 19); break;
 126       case fb_op2:     m = wdisp(  word_aligned_ones, 0, 22);  v = wdisp(  dest_pos, inst_pos, 22); break;
 127       case br_op2:     m = wdisp(  word_aligned_ones, 0, 22);  v = wdisp(  dest_pos, inst_pos, 22); break;
 128       case bpr_op2: {
 129         if (is_cbcond(inst)) {
 130           m = wdisp10(word_aligned_ones, 0);
 131           v = wdisp10(dest_pos, inst_pos);
 132         } else {
 133           m = wdisp16(word_aligned_ones, 0);
 134           v = wdisp16(dest_pos, inst_pos);
 135         }
 136         break;
 137       }
 138       default: ShouldNotReachHere();
 139     }
 140   }
 141   return  inst & ~m  |  v;
 142 }
 143 
 144 // Return the offset of the branch destionation of instruction inst
 145 // at offset pos.
 146 // Should have pcs, but since all is relative, it works out.
 147 int MacroAssembler::branch_destination(int inst, int pos) {
 148   int r;
 149   switch (inv_op(inst)) {
 150   default: ShouldNotReachHere();
 151   case call_op:        r = inv_wdisp(inst, pos, 30);  break;
 152   case branch_op:
 153     switch (inv_op2(inst)) {
 154       case fbp_op2:    r = inv_wdisp(  inst, pos, 19);  break;
 155       case bp_op2:     r = inv_wdisp(  inst, pos, 19);  break;
 156       case fb_op2:     r = inv_wdisp(  inst, pos, 22);  break;
 157       case br_op2:     r = inv_wdisp(  inst, pos, 22);  break;
 158       case bpr_op2: {
 159         if (is_cbcond(inst)) {
 160           r = inv_wdisp10(inst, pos);
 161         } else {
 162           r = inv_wdisp16(inst, pos);
 163         }
 164         break;
 165       }
 166       default: ShouldNotReachHere();
 167     }
 168   }
 169   return r;
 170 }
 171 
 172 void MacroAssembler::null_check(Register reg, int offset) {
 173   if (needs_explicit_null_check((intptr_t)offset)) {
 174     // provoke OS NULL exception if reg = NULL by
 175     // accessing M[reg] w/o changing any registers
 176     ld_ptr(reg, 0, G0);
 177   }
 178   else {
 179     // nothing to do, (later) access of M[reg + offset]
 180     // will provoke OS NULL exception if reg = NULL
 181   }
 182 }
 183 
 184 // Ring buffer jumps
 185 
 186 
 187 void MacroAssembler::jmp2(Register r1, Register r2, const char* file, int line ) {
 188   assert_not_delayed();
 189   jmpl(r1, r2, G0);
 190 }
 191 void MacroAssembler::jmp(Register r1, int offset, const char* file, int line ) {
 192   assert_not_delayed();
 193   jmp(r1, offset);
 194 }
 195 
 196 // This code sequence is relocatable to any address, even on LP64.
 197 void MacroAssembler::jumpl(const AddressLiteral& addrlit, Register temp, Register d, int offset, const char* file, int line) {
 198   assert_not_delayed();
 199   // Force fixed length sethi because NativeJump and NativeFarCall don't handle
 200   // variable length instruction streams.
 201   patchable_sethi(addrlit, temp);
 202   Address a(temp, addrlit.low10() + offset);  // Add the offset to the displacement.
 203   jmpl(a.base(), a.disp(), d);
 204 }
 205 
 206 void MacroAssembler::jump(const AddressLiteral& addrlit, Register temp, int offset, const char* file, int line) {
 207   jumpl(addrlit, temp, G0, offset, file, line);
 208 }
 209 
 210 
 211 // Conditional breakpoint (for assertion checks in assembly code)
 212 void MacroAssembler::breakpoint_trap(Condition c, CC cc) {
 213   trap(c, cc, G0, ST_RESERVED_FOR_USER_0);
 214 }
 215 
 216 // We want to use ST_BREAKPOINT here, but the debugger is confused by it.
 217 void MacroAssembler::breakpoint_trap() {
 218   trap(ST_RESERVED_FOR_USER_0);
 219 }
 220 
 221 // Write serialization page so VM thread can do a pseudo remote membar
 222 // We use the current thread pointer to calculate a thread specific
 223 // offset to write to within the page. This minimizes bus traffic
 224 // due to cache line collision.
 225 void MacroAssembler::serialize_memory(Register thread, Register tmp1, Register tmp2) {
 226   srl(thread, os::get_serialize_page_shift_count(), tmp2);
 227   if (Assembler::is_simm13(os::vm_page_size())) {
 228     and3(tmp2, (os::vm_page_size() - sizeof(int)), tmp2);
 229   }
 230   else {
 231     set((os::vm_page_size() - sizeof(int)), tmp1);
 232     and3(tmp2, tmp1, tmp2);
 233   }
 234   set(os::get_memory_serialize_page(), tmp1);
 235   st(G0, tmp1, tmp2);
 236 }
 237 
 238 
 239 
 240 void MacroAssembler::enter() {
 241   Unimplemented();
 242 }
 243 
 244 void MacroAssembler::leave() {
 245   Unimplemented();
 246 }
 247 
 248 // Calls to C land
 249 
 250 #ifdef ASSERT
 251 // a hook for debugging
 252 static Thread* reinitialize_thread() {
 253   return Thread::current();
 254 }
 255 #else
 256 #define reinitialize_thread Thread::current
 257 #endif
 258 
 259 #ifdef ASSERT
 260 address last_get_thread = NULL;
 261 #endif
 262 
 263 // call this when G2_thread is not known to be valid
 264 void MacroAssembler::get_thread() {
 265   save_frame(0);                // to avoid clobbering O0
 266   mov(G1, L0);                  // avoid clobbering G1
 267   mov(G5_method, L1);           // avoid clobbering G5
 268   mov(G3, L2);                  // avoid clobbering G3 also
 269   mov(G4, L5);                  // avoid clobbering G4
 270 #ifdef ASSERT
 271   AddressLiteral last_get_thread_addrlit(&last_get_thread);
 272   set(last_get_thread_addrlit, L3);
 273   rdpc(L4);
 274   inc(L4, 3 * BytesPerInstWord); // skip rdpc + inc + st_ptr to point L4 at call  st_ptr(L4, L3, 0);
 275 #endif
 276   call(CAST_FROM_FN_PTR(address, reinitialize_thread), relocInfo::runtime_call_type);
 277   delayed()->nop();
 278   mov(L0, G1);
 279   mov(L1, G5_method);
 280   mov(L2, G3);
 281   mov(L5, G4);
 282   restore(O0, 0, G2_thread);
 283 }
 284 
 285 static Thread* verify_thread_subroutine(Thread* gthread_value) {
 286   Thread* correct_value = Thread::current();
 287   guarantee(gthread_value == correct_value, "G2_thread value must be the thread");
 288   return correct_value;
 289 }
 290 
 291 void MacroAssembler::verify_thread() {
 292   if (VerifyThread) {
 293     // NOTE: this chops off the heads of the 64-bit O registers.
 294     // make sure G2_thread contains the right value
 295     save_frame_and_mov(0, Lmethod, Lmethod);   // to avoid clobbering O0 (and propagate Lmethod)
 296     mov(G1, L1);                // avoid clobbering G1
 297     // G2 saved below
 298     mov(G3, L3);                // avoid clobbering G3
 299     mov(G4, L4);                // avoid clobbering G4
 300     mov(G5_method, L5);         // avoid clobbering G5_method
 301     call(CAST_FROM_FN_PTR(address,verify_thread_subroutine), relocInfo::runtime_call_type);
 302     delayed()->mov(G2_thread, O0);
 303 
 304     mov(L1, G1);                // Restore G1
 305     // G2 restored below
 306     mov(L3, G3);                // restore G3
 307     mov(L4, G4);                // restore G4
 308     mov(L5, G5_method);         // restore G5_method
 309     restore(O0, 0, G2_thread);
 310   }
 311 }
 312 
 313 
 314 void MacroAssembler::save_thread(const Register thread_cache) {
 315   verify_thread();
 316   if (thread_cache->is_valid()) {
 317     assert(thread_cache->is_local() || thread_cache->is_in(), "bad volatile");
 318     mov(G2_thread, thread_cache);
 319   }
 320   if (VerifyThread) {
 321     // smash G2_thread, as if the VM were about to anyway
 322     set(0x67676767, G2_thread);
 323   }
 324 }
 325 
 326 
 327 void MacroAssembler::restore_thread(const Register thread_cache) {
 328   if (thread_cache->is_valid()) {
 329     assert(thread_cache->is_local() || thread_cache->is_in(), "bad volatile");
 330     mov(thread_cache, G2_thread);
 331     verify_thread();
 332   } else {
 333     // do it the slow way
 334     get_thread();
 335   }
 336 }
 337 
 338 
 339 // %%% maybe get rid of [re]set_last_Java_frame
 340 void MacroAssembler::set_last_Java_frame(Register last_java_sp, Register last_Java_pc) {
 341   assert_not_delayed();
 342   Address flags(G2_thread, JavaThread::frame_anchor_offset() +
 343                            JavaFrameAnchor::flags_offset());
 344   Address pc_addr(G2_thread, JavaThread::last_Java_pc_offset());
 345 
 346   // Always set last_Java_pc and flags first because once last_Java_sp is visible
 347   // has_last_Java_frame is true and users will look at the rest of the fields.
 348   // (Note: flags should always be zero before we get here so doesn't need to be set.)
 349 
 350 #ifdef ASSERT
 351   // Verify that flags was zeroed on return to Java
 352   Label PcOk;
 353   save_frame(0);                // to avoid clobbering O0
 354   ld_ptr(pc_addr, L0);
 355   br_null_short(L0, Assembler::pt, PcOk);
 356   STOP("last_Java_pc not zeroed before leaving Java");
 357   bind(PcOk);
 358 
 359   // Verify that flags was zeroed on return to Java
 360   Label FlagsOk;
 361   ld(flags, L0);
 362   tst(L0);
 363   br(Assembler::zero, false, Assembler::pt, FlagsOk);
 364   delayed() -> restore();
 365   STOP("flags not zeroed before leaving Java");
 366   bind(FlagsOk);
 367 #endif /* ASSERT */
 368   //
 369   // When returning from calling out from Java mode the frame anchor's last_Java_pc
 370   // will always be set to NULL. It is set here so that if we are doing a call to
 371   // native (not VM) that we capture the known pc and don't have to rely on the
 372   // native call having a standard frame linkage where we can find the pc.
 373 
 374   if (last_Java_pc->is_valid()) {
 375     st_ptr(last_Java_pc, pc_addr);
 376   }
 377 
 378 #ifdef ASSERT
 379   // Make sure that we have an odd stack
 380   Label StackOk;
 381   andcc(last_java_sp, 0x01, G0);
 382   br(Assembler::notZero, false, Assembler::pt, StackOk);
 383   delayed()->nop();
 384   STOP("Stack Not Biased in set_last_Java_frame");
 385   bind(StackOk);
 386 #endif // ASSERT
 387   assert( last_java_sp != G4_scratch, "bad register usage in set_last_Java_frame");
 388   add( last_java_sp, STACK_BIAS, G4_scratch );
 389   st_ptr(G4_scratch, G2_thread, JavaThread::last_Java_sp_offset());
 390 }
 391 
 392 void MacroAssembler::reset_last_Java_frame(void) {
 393   assert_not_delayed();
 394 
 395   Address sp_addr(G2_thread, JavaThread::last_Java_sp_offset());
 396   Address pc_addr(G2_thread, JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 397   Address flags  (G2_thread, JavaThread::frame_anchor_offset() + JavaFrameAnchor::flags_offset());
 398 
 399 #ifdef ASSERT
 400   // check that it WAS previously set
 401     save_frame_and_mov(0, Lmethod, Lmethod);     // Propagate Lmethod to helper frame
 402     ld_ptr(sp_addr, L0);
 403     tst(L0);
 404     breakpoint_trap(Assembler::zero, Assembler::ptr_cc);
 405     restore();
 406 #endif // ASSERT
 407 
 408   st_ptr(G0, sp_addr);
 409   // Always return last_Java_pc to zero
 410   st_ptr(G0, pc_addr);
 411   // Always null flags after return to Java
 412   st(G0, flags);
 413 }
 414 
 415 
 416 void MacroAssembler::call_VM_base(
 417   Register        oop_result,
 418   Register        thread_cache,
 419   Register        last_java_sp,
 420   address         entry_point,
 421   int             number_of_arguments,
 422   bool            check_exceptions)
 423 {
 424   assert_not_delayed();
 425 
 426   // determine last_java_sp register
 427   if (!last_java_sp->is_valid()) {
 428     last_java_sp = SP;
 429   }
 430   // debugging support
 431   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
 432 
 433   // 64-bit last_java_sp is biased!
 434   set_last_Java_frame(last_java_sp, noreg);
 435   if (VerifyThread)  mov(G2_thread, O0); // about to be smashed; pass early
 436   save_thread(thread_cache);
 437   // do the call
 438   call(entry_point, relocInfo::runtime_call_type);
 439   if (!VerifyThread)
 440     delayed()->mov(G2_thread, O0);  // pass thread as first argument
 441   else
 442     delayed()->nop();             // (thread already passed)
 443   restore_thread(thread_cache);
 444   reset_last_Java_frame();
 445 
 446   // check for pending exceptions. use Gtemp as scratch register.
 447   if (check_exceptions) {
 448     check_and_forward_exception(Gtemp);
 449   }
 450 
 451 #ifdef ASSERT
 452   set(badHeapWordVal, G3);
 453   set(badHeapWordVal, G4);
 454   set(badHeapWordVal, G5);
 455 #endif
 456 
 457   // get oop result if there is one and reset the value in the thread
 458   if (oop_result->is_valid()) {
 459     get_vm_result(oop_result);
 460   }
 461 }
 462 
 463 void MacroAssembler::check_and_forward_exception(Register scratch_reg)
 464 {
 465   Label L;
 466 
 467   check_and_handle_popframe(scratch_reg);
 468   check_and_handle_earlyret(scratch_reg);
 469 
 470   Address exception_addr(G2_thread, Thread::pending_exception_offset());
 471   ld_ptr(exception_addr, scratch_reg);
 472   br_null_short(scratch_reg, pt, L);
 473   // we use O7 linkage so that forward_exception_entry has the issuing PC
 474   call(StubRoutines::forward_exception_entry(), relocInfo::runtime_call_type);
 475   delayed()->nop();
 476   bind(L);
 477 }
 478 
 479 
 480 void MacroAssembler::check_and_handle_popframe(Register scratch_reg) {
 481 }
 482 
 483 
 484 void MacroAssembler::check_and_handle_earlyret(Register scratch_reg) {
 485 }
 486 
 487 
 488 void MacroAssembler::call_VM(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
 489   call_VM_base(oop_result, noreg, noreg, entry_point, number_of_arguments, check_exceptions);
 490 }
 491 
 492 
 493 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, bool check_exceptions) {
 494   // O0 is reserved for the thread
 495   mov(arg_1, O1);
 496   call_VM(oop_result, entry_point, 1, check_exceptions);
 497 }
 498 
 499 
 500 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2, bool check_exceptions) {
 501   // O0 is reserved for the thread
 502   mov(arg_1, O1);
 503   mov(arg_2, O2); assert(arg_2 != O1, "smashed argument");
 504   call_VM(oop_result, entry_point, 2, check_exceptions);
 505 }
 506 
 507 
 508 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2, Register arg_3, bool check_exceptions) {
 509   // O0 is reserved for the thread
 510   mov(arg_1, O1);
 511   mov(arg_2, O2); assert(arg_2 != O1,                "smashed argument");
 512   mov(arg_3, O3); assert(arg_3 != O1 && arg_3 != O2, "smashed argument");
 513   call_VM(oop_result, entry_point, 3, check_exceptions);
 514 }
 515 
 516 
 517 
 518 // Note: The following call_VM overloadings are useful when a "save"
 519 // has already been performed by a stub, and the last Java frame is
 520 // the previous one.  In that case, last_java_sp must be passed as FP
 521 // instead of SP.
 522 
 523 
 524 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, int number_of_arguments, bool check_exceptions) {
 525   call_VM_base(oop_result, noreg, last_java_sp, entry_point, number_of_arguments, check_exceptions);
 526 }
 527 
 528 
 529 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1, bool check_exceptions) {
 530   // O0 is reserved for the thread
 531   mov(arg_1, O1);
 532   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
 533 }
 534 
 535 
 536 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1, Register arg_2, bool check_exceptions) {
 537   // O0 is reserved for the thread
 538   mov(arg_1, O1);
 539   mov(arg_2, O2); assert(arg_2 != O1, "smashed argument");
 540   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
 541 }
 542 
 543 
 544 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1, Register arg_2, Register arg_3, bool check_exceptions) {
 545   // O0 is reserved for the thread
 546   mov(arg_1, O1);
 547   mov(arg_2, O2); assert(arg_2 != O1,                "smashed argument");
 548   mov(arg_3, O3); assert(arg_3 != O1 && arg_3 != O2, "smashed argument");
 549   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
 550 }
 551 
 552 
 553 
 554 void MacroAssembler::call_VM_leaf_base(Register thread_cache, address entry_point, int number_of_arguments) {
 555   assert_not_delayed();
 556   save_thread(thread_cache);
 557   // do the call
 558   call(entry_point, relocInfo::runtime_call_type);
 559   delayed()->nop();
 560   restore_thread(thread_cache);
 561 #ifdef ASSERT
 562   set(badHeapWordVal, G3);
 563   set(badHeapWordVal, G4);
 564   set(badHeapWordVal, G5);
 565 #endif
 566 }
 567 
 568 
 569 void MacroAssembler::call_VM_leaf(Register thread_cache, address entry_point, int number_of_arguments) {
 570   call_VM_leaf_base(thread_cache, entry_point, number_of_arguments);
 571 }
 572 
 573 
 574 void MacroAssembler::call_VM_leaf(Register thread_cache, address entry_point, Register arg_1) {
 575   mov(arg_1, O0);
 576   call_VM_leaf(thread_cache, entry_point, 1);
 577 }
 578 
 579 
 580 void MacroAssembler::call_VM_leaf(Register thread_cache, address entry_point, Register arg_1, Register arg_2) {
 581   mov(arg_1, O0);
 582   mov(arg_2, O1); assert(arg_2 != O0, "smashed argument");
 583   call_VM_leaf(thread_cache, entry_point, 2);
 584 }
 585 
 586 
 587 void MacroAssembler::call_VM_leaf(Register thread_cache, address entry_point, Register arg_1, Register arg_2, Register arg_3) {
 588   mov(arg_1, O0);
 589   mov(arg_2, O1); assert(arg_2 != O0,                "smashed argument");
 590   mov(arg_3, O2); assert(arg_3 != O0 && arg_3 != O1, "smashed argument");
 591   call_VM_leaf(thread_cache, entry_point, 3);
 592 }
 593 
 594 
 595 void MacroAssembler::get_vm_result(Register oop_result) {
 596   verify_thread();
 597   Address vm_result_addr(G2_thread, JavaThread::vm_result_offset());
 598   ld_ptr(    vm_result_addr, oop_result);
 599   st_ptr(G0, vm_result_addr);
 600   verify_oop(oop_result);
 601 }
 602 
 603 
 604 void MacroAssembler::get_vm_result_2(Register metadata_result) {
 605   verify_thread();
 606   Address vm_result_addr_2(G2_thread, JavaThread::vm_result_2_offset());
 607   ld_ptr(vm_result_addr_2, metadata_result);
 608   st_ptr(G0, vm_result_addr_2);
 609 }
 610 
 611 
 612 // We require that C code which does not return a value in vm_result will
 613 // leave it undisturbed.
 614 void MacroAssembler::set_vm_result(Register oop_result) {
 615   verify_thread();
 616   Address vm_result_addr(G2_thread, JavaThread::vm_result_offset());
 617   verify_oop(oop_result);
 618 
 619 # ifdef ASSERT
 620     // Check that we are not overwriting any other oop.
 621     save_frame_and_mov(0, Lmethod, Lmethod);     // Propagate Lmethod
 622     ld_ptr(vm_result_addr, L0);
 623     tst(L0);
 624     restore();
 625     breakpoint_trap(notZero, Assembler::ptr_cc);
 626     // }
 627 # endif
 628 
 629   st_ptr(oop_result, vm_result_addr);
 630 }
 631 
 632 
 633 void MacroAssembler::ic_call(address entry, bool emit_delay, jint method_index) {
 634   RelocationHolder rspec = virtual_call_Relocation::spec(pc(), method_index);
 635   patchable_set((intptr_t)Universe::non_oop_word(), G5_inline_cache_reg);
 636   relocate(rspec);
 637   call(entry, relocInfo::none);
 638   if (emit_delay) {
 639     delayed()->nop();
 640   }
 641 }
 642 
 643 void MacroAssembler::card_table_write(jbyte* byte_map_base,
 644                                       Register tmp, Register obj) {
 645   srlx(obj, CardTableModRefBS::card_shift, obj);
 646   assert(tmp != obj, "need separate temp reg");
 647   set((address) byte_map_base, tmp);
 648   stb(G0, tmp, obj);
 649 }
 650 
 651 
 652 void MacroAssembler::internal_sethi(const AddressLiteral& addrlit, Register d, bool ForceRelocatable) {
 653   address save_pc;
 654   int shiftcnt;
 655 #ifdef VALIDATE_PIPELINE
 656   assert_no_delay("Cannot put two instructions in delay-slot.");
 657 #endif
 658   v9_dep();
 659   save_pc = pc();
 660 
 661   int msb32 = (int) (addrlit.value() >> 32);
 662   int lsb32 = (int) (addrlit.value());
 663 
 664   if (msb32 == 0 && lsb32 >= 0) {
 665     Assembler::sethi(lsb32, d, addrlit.rspec());
 666   }
 667   else if (msb32 == -1) {
 668     Assembler::sethi(~lsb32, d, addrlit.rspec());
 669     xor3(d, ~low10(~0), d);
 670   }
 671   else {
 672     Assembler::sethi(msb32, d, addrlit.rspec());  // msb 22-bits
 673     if (msb32 & 0x3ff)                            // Any bits?
 674       or3(d, msb32 & 0x3ff, d);                   // msb 32-bits are now in lsb 32
 675     if (lsb32 & 0xFFFFFC00) {                     // done?
 676       if ((lsb32 >> 20) & 0xfff) {                // Any bits set?
 677         sllx(d, 12, d);                           // Make room for next 12 bits
 678         or3(d, (lsb32 >> 20) & 0xfff, d);         // Or in next 12
 679         shiftcnt = 0;                             // We already shifted
 680       }
 681       else
 682         shiftcnt = 12;
 683       if ((lsb32 >> 10) & 0x3ff) {
 684         sllx(d, shiftcnt + 10, d);                // Make room for last 10 bits
 685         or3(d, (lsb32 >> 10) & 0x3ff, d);         // Or in next 10
 686         shiftcnt = 0;
 687       }
 688       else
 689         shiftcnt = 10;
 690       sllx(d, shiftcnt + 10, d);                  // Shift leaving disp field 0'd
 691     }
 692     else
 693       sllx(d, 32, d);
 694   }
 695   // Pad out the instruction sequence so it can be patched later.
 696   if (ForceRelocatable || (addrlit.rtype() != relocInfo::none &&
 697                            addrlit.rtype() != relocInfo::runtime_call_type)) {
 698     while (pc() < (save_pc + (7 * BytesPerInstWord)))
 699       nop();
 700   }
 701 }
 702 
 703 
 704 void MacroAssembler::sethi(const AddressLiteral& addrlit, Register d) {
 705   internal_sethi(addrlit, d, false);
 706 }
 707 
 708 
 709 void MacroAssembler::patchable_sethi(const AddressLiteral& addrlit, Register d) {
 710   internal_sethi(addrlit, d, true);
 711 }
 712 
 713 
 714 int MacroAssembler::insts_for_sethi(address a, bool worst_case) {
 715   if (worst_case)  return 7;
 716   intptr_t iaddr = (intptr_t) a;
 717   int msb32 = (int) (iaddr >> 32);
 718   int lsb32 = (int) (iaddr);
 719   int count;
 720   if (msb32 == 0 && lsb32 >= 0)
 721     count = 1;
 722   else if (msb32 == -1)
 723     count = 2;
 724   else {
 725     count = 2;
 726     if (msb32 & 0x3ff)
 727       count++;
 728     if (lsb32 & 0xFFFFFC00 ) {
 729       if ((lsb32 >> 20) & 0xfff)  count += 2;
 730       if ((lsb32 >> 10) & 0x3ff)  count += 2;
 731     }
 732   }
 733   return count;
 734 }
 735 
 736 int MacroAssembler::worst_case_insts_for_set() {
 737   return insts_for_sethi(NULL, true) + 1;
 738 }
 739 
 740 
 741 // Keep in sync with MacroAssembler::insts_for_internal_set
 742 void MacroAssembler::internal_set(const AddressLiteral& addrlit, Register d, bool ForceRelocatable) {
 743   intptr_t value = addrlit.value();
 744 
 745   if (!ForceRelocatable && addrlit.rspec().type() == relocInfo::none) {
 746     // can optimize
 747     if (-4096 <= value && value <= 4095) {
 748       or3(G0, value, d); // setsw (this leaves upper 32 bits sign-extended)
 749       return;
 750     }
 751     if (inv_hi22(hi22(value)) == value) {
 752       sethi(addrlit, d);
 753       return;
 754     }
 755   }
 756   assert_no_delay("Cannot put two instructions in delay-slot.");
 757   internal_sethi(addrlit, d, ForceRelocatable);
 758   if (ForceRelocatable || addrlit.rspec().type() != relocInfo::none || addrlit.low10() != 0) {
 759     add(d, addrlit.low10(), d, addrlit.rspec());
 760   }
 761 }
 762 
 763 // Keep in sync with MacroAssembler::internal_set
 764 int MacroAssembler::insts_for_internal_set(intptr_t value) {
 765   // can optimize
 766   if (-4096 <= value && value <= 4095) {
 767     return 1;
 768   }
 769   if (inv_hi22(hi22(value)) == value) {
 770     return insts_for_sethi((address) value);
 771   }
 772   int count = insts_for_sethi((address) value);
 773   AddressLiteral al(value);
 774   if (al.low10() != 0) {
 775     count++;
 776   }
 777   return count;
 778 }
 779 
 780 void MacroAssembler::set(const AddressLiteral& al, Register d) {
 781   internal_set(al, d, false);
 782 }
 783 
 784 void MacroAssembler::set(intptr_t value, Register d) {
 785   AddressLiteral al(value);
 786   internal_set(al, d, false);
 787 }
 788 
 789 void MacroAssembler::set(address addr, Register d, RelocationHolder const& rspec) {
 790   AddressLiteral al(addr, rspec);
 791   internal_set(al, d, false);
 792 }
 793 
 794 void MacroAssembler::patchable_set(const AddressLiteral& al, Register d) {
 795   internal_set(al, d, true);
 796 }
 797 
 798 void MacroAssembler::patchable_set(intptr_t value, Register d) {
 799   AddressLiteral al(value);
 800   internal_set(al, d, true);
 801 }
 802 
 803 
 804 void MacroAssembler::set64(jlong value, Register d, Register tmp) {
 805   assert_not_delayed();
 806   v9_dep();
 807 
 808   int hi = (int)(value >> 32);
 809   int lo = (int)(value & ~0);
 810   int bits_33to2 = (int)((value >> 2) & ~0);
 811   // (Matcher::isSimpleConstant64 knows about the following optimizations.)
 812   if (Assembler::is_simm13(lo) && value == lo) {
 813     or3(G0, lo, d);
 814   } else if (hi == 0) {
 815     Assembler::sethi(lo, d);   // hardware version zero-extends to upper 32
 816     if (low10(lo) != 0)
 817       or3(d, low10(lo), d);
 818   }
 819   else if ((hi >> 2) == 0) {
 820     Assembler::sethi(bits_33to2, d);  // hardware version zero-extends to upper 32
 821     sllx(d, 2, d);
 822     if (low12(lo) != 0)
 823       or3(d, low12(lo), d);
 824   }
 825   else if (hi == -1) {
 826     Assembler::sethi(~lo, d);  // hardware version zero-extends to upper 32
 827     xor3(d, low10(lo) ^ ~low10(~0), d);
 828   }
 829   else if (lo == 0) {
 830     if (Assembler::is_simm13(hi)) {
 831       or3(G0, hi, d);
 832     } else {
 833       Assembler::sethi(hi, d);   // hardware version zero-extends to upper 32
 834       if (low10(hi) != 0)
 835         or3(d, low10(hi), d);
 836     }
 837     sllx(d, 32, d);
 838   }
 839   else {
 840     Assembler::sethi(hi, tmp);
 841     Assembler::sethi(lo,   d); // macro assembler version sign-extends
 842     if (low10(hi) != 0)
 843       or3 (tmp, low10(hi), tmp);
 844     if (low10(lo) != 0)
 845       or3 (  d, low10(lo),   d);
 846     sllx(tmp, 32, tmp);
 847     or3 (d, tmp, d);
 848   }
 849 }
 850 
 851 int MacroAssembler::insts_for_set64(jlong value) {
 852   v9_dep();
 853 
 854   int hi = (int) (value >> 32);
 855   int lo = (int) (value & ~0);
 856   int count = 0;
 857 
 858   // (Matcher::isSimpleConstant64 knows about the following optimizations.)
 859   if (Assembler::is_simm13(lo) && value == lo) {
 860     count++;
 861   } else if (hi == 0) {
 862     count++;
 863     if (low10(lo) != 0)
 864       count++;
 865   }
 866   else if (hi == -1) {
 867     count += 2;
 868   }
 869   else if (lo == 0) {
 870     if (Assembler::is_simm13(hi)) {
 871       count++;
 872     } else {
 873       count++;
 874       if (low10(hi) != 0)
 875         count++;
 876     }
 877     count++;
 878   }
 879   else {
 880     count += 2;
 881     if (low10(hi) != 0)
 882       count++;
 883     if (low10(lo) != 0)
 884       count++;
 885     count += 2;
 886   }
 887   return count;
 888 }
 889 
 890 // compute size in bytes of sparc frame, given
 891 // number of extraWords
 892 int MacroAssembler::total_frame_size_in_bytes(int extraWords) {
 893 
 894   int nWords = frame::memory_parameter_word_sp_offset;
 895 
 896   nWords += extraWords;
 897 
 898   if (nWords & 1) ++nWords; // round up to double-word
 899 
 900   return nWords * BytesPerWord;
 901 }
 902 
 903 
 904 // save_frame: given number of "extra" words in frame,
 905 // issue approp. save instruction (p 200, v8 manual)
 906 
 907 void MacroAssembler::save_frame(int extraWords) {
 908   int delta = -total_frame_size_in_bytes(extraWords);
 909   if (is_simm13(delta)) {
 910     save(SP, delta, SP);
 911   } else {
 912     set(delta, G3_scratch);
 913     save(SP, G3_scratch, SP);
 914   }
 915 }
 916 
 917 
 918 void MacroAssembler::save_frame_c1(int size_in_bytes) {
 919   if (is_simm13(-size_in_bytes)) {
 920     save(SP, -size_in_bytes, SP);
 921   } else {
 922     set(-size_in_bytes, G3_scratch);
 923     save(SP, G3_scratch, SP);
 924   }
 925 }
 926 
 927 
 928 void MacroAssembler::save_frame_and_mov(int extraWords,
 929                                         Register s1, Register d1,
 930                                         Register s2, Register d2) {
 931   assert_not_delayed();
 932 
 933   // The trick here is to use precisely the same memory word
 934   // that trap handlers also use to save the register.
 935   // This word cannot be used for any other purpose, but
 936   // it works fine to save the register's value, whether or not
 937   // an interrupt flushes register windows at any given moment!
 938   Address s1_addr;
 939   if (s1->is_valid() && (s1->is_in() || s1->is_local())) {
 940     s1_addr = s1->address_in_saved_window();
 941     st_ptr(s1, s1_addr);
 942   }
 943 
 944   Address s2_addr;
 945   if (s2->is_valid() && (s2->is_in() || s2->is_local())) {
 946     s2_addr = s2->address_in_saved_window();
 947     st_ptr(s2, s2_addr);
 948   }
 949 
 950   save_frame(extraWords);
 951 
 952   if (s1_addr.base() == SP) {
 953     ld_ptr(s1_addr.after_save(), d1);
 954   } else if (s1->is_valid()) {
 955     mov(s1->after_save(), d1);
 956   }
 957 
 958   if (s2_addr.base() == SP) {
 959     ld_ptr(s2_addr.after_save(), d2);
 960   } else if (s2->is_valid()) {
 961     mov(s2->after_save(), d2);
 962   }
 963 }
 964 
 965 
 966 AddressLiteral MacroAssembler::allocate_metadata_address(Metadata* obj) {
 967   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
 968   int index = oop_recorder()->allocate_metadata_index(obj);
 969   RelocationHolder rspec = metadata_Relocation::spec(index);
 970   return AddressLiteral((address)obj, rspec);
 971 }
 972 
 973 AddressLiteral MacroAssembler::constant_metadata_address(Metadata* obj) {
 974   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
 975   int index = oop_recorder()->find_index(obj);
 976   RelocationHolder rspec = metadata_Relocation::spec(index);
 977   return AddressLiteral((address)obj, rspec);
 978 }
 979 
 980 
 981 AddressLiteral MacroAssembler::constant_oop_address(jobject obj) {
 982   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
 983   assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "not an oop");
 984   int oop_index = oop_recorder()->find_index(obj);
 985   return AddressLiteral(obj, oop_Relocation::spec(oop_index));
 986 }
 987 
 988 void  MacroAssembler::set_narrow_oop(jobject obj, Register d) {
 989   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
 990   int oop_index = oop_recorder()->find_index(obj);
 991   RelocationHolder rspec = oop_Relocation::spec(oop_index);
 992 
 993   assert_not_delayed();
 994   // Relocation with special format (see relocInfo_sparc.hpp).
 995   relocate(rspec, 1);
 996   // Assembler::sethi(0x3fffff, d);
 997   emit_int32( op(branch_op) | rd(d) | op2(sethi_op2) | hi22(0x3fffff) );
 998   // Don't add relocation for 'add'. Do patching during 'sethi' processing.
 999   add(d, 0x3ff, d);
1000 
1001 }
1002 
1003 void  MacroAssembler::set_narrow_klass(Klass* k, Register d) {
1004   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
1005   int klass_index = oop_recorder()->find_index(k);
1006   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
1007   narrowOop encoded_k = Klass::encode_klass(k);
1008 
1009   assert_not_delayed();
1010   // Relocation with special format (see relocInfo_sparc.hpp).
1011   relocate(rspec, 1);
1012   // Assembler::sethi(encoded_k, d);
1013   emit_int32( op(branch_op) | rd(d) | op2(sethi_op2) | hi22(encoded_k) );
1014   // Don't add relocation for 'add'. Do patching during 'sethi' processing.
1015   add(d, low10(encoded_k), d);
1016 
1017 }
1018 
1019 void MacroAssembler::align(int modulus) {
1020   while (offset() % modulus != 0) nop();
1021 }
1022 
1023 void RegistersForDebugging::print(outputStream* s) {
1024   FlagSetting fs(Debugging, true);
1025   int j;
1026   for (j = 0; j < 8; ++j) {
1027     if (j != 6) { s->print("i%d = ", j); os::print_location(s, i[j]); }
1028     else        { s->print( "fp = "   ); os::print_location(s, i[j]); }
1029   }
1030   s->cr();
1031 
1032   for (j = 0;  j < 8;  ++j) {
1033     s->print("l%d = ", j); os::print_location(s, l[j]);
1034   }
1035   s->cr();
1036 
1037   for (j = 0; j < 8; ++j) {
1038     if (j != 6) { s->print("o%d = ", j); os::print_location(s, o[j]); }
1039     else        { s->print( "sp = "   ); os::print_location(s, o[j]); }
1040   }
1041   s->cr();
1042 
1043   for (j = 0; j < 8; ++j) {
1044     s->print("g%d = ", j); os::print_location(s, g[j]);
1045   }
1046   s->cr();
1047 
1048   // print out floats with compression
1049   for (j = 0; j < 32; ) {
1050     jfloat val = f[j];
1051     int last = j;
1052     for ( ;  last+1 < 32;  ++last ) {
1053       char b1[1024], b2[1024];
1054       sprintf(b1, "%f", val);
1055       sprintf(b2, "%f", f[last+1]);
1056       if (strcmp(b1, b2))
1057         break;
1058     }
1059     s->print("f%d", j);
1060     if ( j != last )  s->print(" - f%d", last);
1061     s->print(" = %f", val);
1062     s->fill_to(25);
1063     s->print_cr(" (0x%x)", *(int*)&val);
1064     j = last + 1;
1065   }
1066   s->cr();
1067 
1068   // and doubles (evens only)
1069   for (j = 0; j < 32; ) {
1070     jdouble val = d[j];
1071     int last = j;
1072     for ( ;  last+1 < 32;  ++last ) {
1073       char b1[1024], b2[1024];
1074       sprintf(b1, "%f", val);
1075       sprintf(b2, "%f", d[last+1]);
1076       if (strcmp(b1, b2))
1077         break;
1078     }
1079     s->print("d%d", 2 * j);
1080     if ( j != last )  s->print(" - d%d", last);
1081     s->print(" = %f", val);
1082     s->fill_to(30);
1083     s->print("(0x%x)", *(int*)&val);
1084     s->fill_to(42);
1085     s->print_cr("(0x%x)", *(1 + (int*)&val));
1086     j = last + 1;
1087   }
1088   s->cr();
1089 }
1090 
1091 void RegistersForDebugging::save_registers(MacroAssembler* a) {
1092   a->sub(FP, align_up(sizeof(RegistersForDebugging), sizeof(jdouble)) - STACK_BIAS, O0);
1093   a->flushw();
1094   int i;
1095   for (i = 0; i < 8; ++i) {
1096     a->ld_ptr(as_iRegister(i)->address_in_saved_window().after_save(), L1);  a->st_ptr( L1, O0, i_offset(i));
1097     a->ld_ptr(as_lRegister(i)->address_in_saved_window().after_save(), L1);  a->st_ptr( L1, O0, l_offset(i));
1098     a->st_ptr(as_oRegister(i)->after_save(), O0, o_offset(i));
1099     a->st_ptr(as_gRegister(i)->after_save(), O0, g_offset(i));
1100   }
1101   for (i = 0;  i < 32; ++i) {
1102     a->stf(FloatRegisterImpl::S, as_FloatRegister(i), O0, f_offset(i));
1103   }
1104   for (i = 0; i < 64; i += 2) {
1105     a->stf(FloatRegisterImpl::D, as_FloatRegister(i), O0, d_offset(i));
1106   }
1107 }
1108 
1109 void RegistersForDebugging::restore_registers(MacroAssembler* a, Register r) {
1110   for (int i = 1; i < 8;  ++i) {
1111     a->ld_ptr(r, g_offset(i), as_gRegister(i));
1112   }
1113   for (int j = 0; j < 32; ++j) {
1114     a->ldf(FloatRegisterImpl::S, O0, f_offset(j), as_FloatRegister(j));
1115   }
1116   for (int k = 0; k < 64; k += 2) {
1117     a->ldf(FloatRegisterImpl::D, O0, d_offset(k), as_FloatRegister(k));
1118   }
1119 }
1120 
1121 
1122 // pushes double TOS element of FPU stack on CPU stack; pops from FPU stack
1123 void MacroAssembler::push_fTOS() {
1124   // %%%%%% need to implement this
1125 }
1126 
1127 // pops double TOS element from CPU stack and pushes on FPU stack
1128 void MacroAssembler::pop_fTOS() {
1129   // %%%%%% need to implement this
1130 }
1131 
1132 void MacroAssembler::empty_FPU_stack() {
1133   // %%%%%% need to implement this
1134 }
1135 
1136 void MacroAssembler::_verify_oop(Register reg, const char* msg, const char * file, int line) {
1137   // plausibility check for oops
1138   if (!VerifyOops) return;
1139 
1140   if (reg == G0)  return;       // always NULL, which is always an oop
1141 
1142   BLOCK_COMMENT("verify_oop {");
1143   char buffer[64];
1144 #ifdef COMPILER1
1145   if (CommentedAssembly) {
1146     snprintf(buffer, sizeof(buffer), "verify_oop at %d", offset());
1147     block_comment(buffer);
1148   }
1149 #endif
1150 
1151   const char* real_msg = NULL;
1152   {
1153     ResourceMark rm;
1154     stringStream ss;
1155     ss.print("%s at offset %d (%s:%d)", msg, offset(), file, line);
1156     real_msg = code_string(ss.as_string());
1157   }
1158 
1159   // Call indirectly to solve generation ordering problem
1160   AddressLiteral a(StubRoutines::verify_oop_subroutine_entry_address());
1161 
1162   // Make some space on stack above the current register window.
1163   // Enough to hold 8 64-bit registers.
1164   add(SP,-8*8,SP);
1165 
1166   // Save some 64-bit registers; a normal 'save' chops the heads off
1167   // of 64-bit longs in the 32-bit build.
1168   stx(O0,SP,frame::register_save_words*wordSize+STACK_BIAS+0*8);
1169   stx(O1,SP,frame::register_save_words*wordSize+STACK_BIAS+1*8);
1170   mov(reg,O0); // Move arg into O0; arg might be in O7 which is about to be crushed
1171   stx(O7,SP,frame::register_save_words*wordSize+STACK_BIAS+7*8);
1172 
1173   // Size of set() should stay the same
1174   patchable_set((intptr_t)real_msg, O1);
1175   // Load address to call to into O7
1176   load_ptr_contents(a, O7);
1177   // Register call to verify_oop_subroutine
1178   callr(O7, G0);
1179   delayed()->nop();
1180   // recover frame size
1181   add(SP, 8*8,SP);
1182   BLOCK_COMMENT("} verify_oop");
1183 }
1184 
1185 void MacroAssembler::_verify_oop_addr(Address addr, const char* msg, const char * file, int line) {
1186   // plausibility check for oops
1187   if (!VerifyOops) return;
1188 
1189   const char* real_msg = NULL;
1190   {
1191     ResourceMark rm;
1192     stringStream ss;
1193     ss.print("%s at SP+%d (%s:%d)", msg, addr.disp(), file, line);
1194     real_msg = code_string(ss.as_string());
1195   }
1196 
1197   // Call indirectly to solve generation ordering problem
1198   AddressLiteral a(StubRoutines::verify_oop_subroutine_entry_address());
1199 
1200   // Make some space on stack above the current register window.
1201   // Enough to hold 8 64-bit registers.
1202   add(SP,-8*8,SP);
1203 
1204   // Save some 64-bit registers; a normal 'save' chops the heads off
1205   // of 64-bit longs in the 32-bit build.
1206   stx(O0,SP,frame::register_save_words*wordSize+STACK_BIAS+0*8);
1207   stx(O1,SP,frame::register_save_words*wordSize+STACK_BIAS+1*8);
1208   ld_ptr(addr.base(), addr.disp() + 8*8, O0); // Load arg into O0; arg might be in O7 which is about to be crushed
1209   stx(O7,SP,frame::register_save_words*wordSize+STACK_BIAS+7*8);
1210 
1211   // Size of set() should stay the same
1212   patchable_set((intptr_t)real_msg, O1);
1213   // Load address to call to into O7
1214   load_ptr_contents(a, O7);
1215   // Register call to verify_oop_subroutine
1216   callr(O7, G0);
1217   delayed()->nop();
1218   // recover frame size
1219   add(SP, 8*8,SP);
1220 }
1221 
1222 // side-door communication with signalHandler in os_solaris.cpp
1223 address MacroAssembler::_verify_oop_implicit_branch[3] = { NULL };
1224 
1225 // This macro is expanded just once; it creates shared code.  Contract:
1226 // receives an oop in O0.  Must restore O0 & O7 from TLS.  Must not smash ANY
1227 // registers, including flags.  May not use a register 'save', as this blows
1228 // the high bits of the O-regs if they contain Long values.  Acts as a 'leaf'
1229 // call.
1230 void MacroAssembler::verify_oop_subroutine() {
1231   // Leaf call; no frame.
1232   Label succeed, fail, null_or_fail;
1233 
1234   // O0 and O7 were saved already (O0 in O0's TLS home, O7 in O5's TLS home).
1235   // O0 is now the oop to be checked.  O7 is the return address.
1236   Register O0_obj = O0;
1237 
1238   // Save some more registers for temps.
1239   stx(O2,SP,frame::register_save_words*wordSize+STACK_BIAS+2*8);
1240   stx(O3,SP,frame::register_save_words*wordSize+STACK_BIAS+3*8);
1241   stx(O4,SP,frame::register_save_words*wordSize+STACK_BIAS+4*8);
1242   stx(O5,SP,frame::register_save_words*wordSize+STACK_BIAS+5*8);
1243 
1244   // Save flags
1245   Register O5_save_flags = O5;
1246   rdccr( O5_save_flags );
1247 
1248   { // count number of verifies
1249     Register O2_adr   = O2;
1250     Register O3_accum = O3;
1251     inc_counter(StubRoutines::verify_oop_count_addr(), O2_adr, O3_accum);
1252   }
1253 
1254   Register O2_mask = O2;
1255   Register O3_bits = O3;
1256   Register O4_temp = O4;
1257 
1258   // mark lower end of faulting range
1259   assert(_verify_oop_implicit_branch[0] == NULL, "set once");
1260   _verify_oop_implicit_branch[0] = pc();
1261 
1262   // We can't check the mark oop because it could be in the process of
1263   // locking or unlocking while this is running.
1264   set(Universe::verify_oop_mask (), O2_mask);
1265   set(Universe::verify_oop_bits (), O3_bits);
1266 
1267   // assert((obj & oop_mask) == oop_bits);
1268   and3(O0_obj, O2_mask, O4_temp);
1269   cmp_and_brx_short(O4_temp, O3_bits, notEqual, pn, null_or_fail);
1270 
1271   if ((NULL_WORD & Universe::verify_oop_mask()) == Universe::verify_oop_bits()) {
1272     // the null_or_fail case is useless; must test for null separately
1273     br_null_short(O0_obj, pn, succeed);
1274   }
1275 
1276   // Check the Klass* of this object for being in the right area of memory.
1277   // Cannot do the load in the delay above slot in case O0 is null
1278   load_klass(O0_obj, O0_obj);
1279   // assert((klass != NULL)
1280   br_null_short(O0_obj, pn, fail);
1281 
1282   wrccr( O5_save_flags ); // Restore CCR's
1283 
1284   // mark upper end of faulting range
1285   _verify_oop_implicit_branch[1] = pc();
1286 
1287   //-----------------------
1288   // all tests pass
1289   bind(succeed);
1290 
1291   // Restore prior 64-bit registers
1292   ldx(SP,frame::register_save_words*wordSize+STACK_BIAS+0*8,O0);
1293   ldx(SP,frame::register_save_words*wordSize+STACK_BIAS+1*8,O1);
1294   ldx(SP,frame::register_save_words*wordSize+STACK_BIAS+2*8,O2);
1295   ldx(SP,frame::register_save_words*wordSize+STACK_BIAS+3*8,O3);
1296   ldx(SP,frame::register_save_words*wordSize+STACK_BIAS+4*8,O4);
1297   ldx(SP,frame::register_save_words*wordSize+STACK_BIAS+5*8,O5);
1298 
1299   retl();                       // Leaf return; restore prior O7 in delay slot
1300   delayed()->ldx(SP,frame::register_save_words*wordSize+STACK_BIAS+7*8,O7);
1301 
1302   //-----------------------
1303   bind(null_or_fail);           // nulls are less common but OK
1304   br_null(O0_obj, false, pt, succeed);
1305   delayed()->wrccr( O5_save_flags ); // Restore CCR's
1306 
1307   //-----------------------
1308   // report failure:
1309   bind(fail);
1310   _verify_oop_implicit_branch[2] = pc();
1311 
1312   wrccr( O5_save_flags ); // Restore CCR's
1313 
1314   save_frame(align_up(sizeof(RegistersForDebugging) / BytesPerWord, 2));
1315 
1316   // stop_subroutine expects message pointer in I1.
1317   mov(I1, O1);
1318 
1319   // Restore prior 64-bit registers
1320   ldx(FP,frame::register_save_words*wordSize+STACK_BIAS+0*8,I0);
1321   ldx(FP,frame::register_save_words*wordSize+STACK_BIAS+1*8,I1);
1322   ldx(FP,frame::register_save_words*wordSize+STACK_BIAS+2*8,I2);
1323   ldx(FP,frame::register_save_words*wordSize+STACK_BIAS+3*8,I3);
1324   ldx(FP,frame::register_save_words*wordSize+STACK_BIAS+4*8,I4);
1325   ldx(FP,frame::register_save_words*wordSize+STACK_BIAS+5*8,I5);
1326 
1327   // factor long stop-sequence into subroutine to save space
1328   assert(StubRoutines::Sparc::stop_subroutine_entry_address(), "hasn't been generated yet");
1329 
1330   // call indirectly to solve generation ordering problem
1331   AddressLiteral al(StubRoutines::Sparc::stop_subroutine_entry_address());
1332   load_ptr_contents(al, O5);
1333   jmpl(O5, 0, O7);
1334   delayed()->nop();
1335 }
1336 
1337 
1338 void MacroAssembler::stop(const char* msg) {
1339   // save frame first to get O7 for return address
1340   // add one word to size in case struct is odd number of words long
1341   // It must be doubleword-aligned for storing doubles into it.
1342 
1343     save_frame(align_up(sizeof(RegistersForDebugging) / BytesPerWord, 2));
1344 
1345     // stop_subroutine expects message pointer in I1.
1346     // Size of set() should stay the same
1347     patchable_set((intptr_t)msg, O1);
1348 
1349     // factor long stop-sequence into subroutine to save space
1350     assert(StubRoutines::Sparc::stop_subroutine_entry_address(), "hasn't been generated yet");
1351 
1352     // call indirectly to solve generation ordering problem
1353     AddressLiteral a(StubRoutines::Sparc::stop_subroutine_entry_address());
1354     load_ptr_contents(a, O5);
1355     jmpl(O5, 0, O7);
1356     delayed()->nop();
1357 
1358     breakpoint_trap();   // make stop actually stop rather than writing
1359                          // unnoticeable results in the output files.
1360 
1361     // restore(); done in callee to save space!
1362 }
1363 
1364 
1365 void MacroAssembler::warn(const char* msg) {
1366   save_frame(align_up(sizeof(RegistersForDebugging) / BytesPerWord, 2));
1367   RegistersForDebugging::save_registers(this);
1368   mov(O0, L0);
1369   // Size of set() should stay the same
1370   patchable_set((intptr_t)msg, O0);
1371   call( CAST_FROM_FN_PTR(address, warning) );
1372   delayed()->nop();
1373 //  ret();
1374 //  delayed()->restore();
1375   RegistersForDebugging::restore_registers(this, L0);
1376   restore();
1377 }
1378 
1379 
1380 void MacroAssembler::untested(const char* what) {
1381   // We must be able to turn interactive prompting off
1382   // in order to run automated test scripts on the VM
1383   // Use the flag ShowMessageBoxOnError
1384 
1385   const char* b = NULL;
1386   {
1387     ResourceMark rm;
1388     stringStream ss;
1389     ss.print("untested: %s", what);
1390     b = code_string(ss.as_string());
1391   }
1392   if (ShowMessageBoxOnError) { STOP(b); }
1393   else                       { warn(b); }
1394 }
1395 
1396 
1397 void MacroAssembler::unimplemented(const char* what) {
1398   char* b = new char[1024];
1399   jio_snprintf(b, 1024, "unimplemented: %s", what);
1400   stop(b);
1401 }
1402 
1403 
1404 void MacroAssembler::stop_subroutine() {
1405   RegistersForDebugging::save_registers(this);
1406 
1407   // for the sake of the debugger, stick a PC on the current frame
1408   // (this assumes that the caller has performed an extra "save")
1409   mov(I7, L7);
1410   add(O7, -7 * BytesPerInt, I7);
1411 
1412   save_frame(); // one more save to free up another O7 register
1413   mov(I0, O1); // addr of reg save area
1414 
1415   // We expect pointer to message in I1. Caller must set it up in O1
1416   mov(I1, O0); // get msg
1417   call (CAST_FROM_FN_PTR(address, MacroAssembler::debug), relocInfo::runtime_call_type);
1418   delayed()->nop();
1419 
1420   restore();
1421 
1422   RegistersForDebugging::restore_registers(this, O0);
1423 
1424   save_frame(0);
1425   call(CAST_FROM_FN_PTR(address,breakpoint));
1426   delayed()->nop();
1427   restore();
1428 
1429   mov(L7, I7);
1430   retl();
1431   delayed()->restore(); // see stop above
1432 }
1433 
1434 
1435 void MacroAssembler::debug(char* msg, RegistersForDebugging* regs) {
1436   if ( ShowMessageBoxOnError ) {
1437     JavaThread* thread = JavaThread::current();
1438     JavaThreadState saved_state = thread->thread_state();
1439     thread->set_thread_state(_thread_in_vm);
1440       {
1441         // In order to get locks work, we need to fake a in_VM state
1442         ttyLocker ttyl;
1443         ::tty->print_cr("EXECUTION STOPPED: %s\n", msg);
1444         if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
1445         BytecodeCounter::print();
1446         }
1447         if (os::message_box(msg, "Execution stopped, print registers?"))
1448           regs->print(::tty);
1449       }
1450     BREAKPOINT;
1451       ThreadStateTransition::transition(JavaThread::current(), _thread_in_vm, saved_state);
1452   }
1453   else {
1454      ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
1455   }
1456   assert(false, "DEBUG MESSAGE: %s", msg);
1457 }
1458 
1459 
1460 void MacroAssembler::calc_mem_param_words(Register Rparam_words, Register Rresult) {
1461   subcc( Rparam_words, Argument::n_register_parameters, Rresult); // how many mem words?
1462   Label no_extras;
1463   br( negative, true, pt, no_extras ); // if neg, clear reg
1464   delayed()->set(0, Rresult);          // annuled, so only if taken
1465   bind( no_extras );
1466 }
1467 
1468 
1469 void MacroAssembler::calc_frame_size(Register Rextra_words, Register Rresult) {
1470   add(Rextra_words, frame::memory_parameter_word_sp_offset, Rresult);
1471   bclr(1, Rresult);
1472   sll(Rresult, LogBytesPerWord, Rresult);  // Rresult has total frame bytes
1473 }
1474 
1475 
1476 void MacroAssembler::calc_frame_size_and_save(Register Rextra_words, Register Rresult) {
1477   calc_frame_size(Rextra_words, Rresult);
1478   neg(Rresult);
1479   save(SP, Rresult, SP);
1480 }
1481 
1482 
1483 // ---------------------------------------------------------
1484 Assembler::RCondition cond2rcond(Assembler::Condition c) {
1485   switch (c) {
1486     /*case zero: */
1487     case Assembler::equal:        return Assembler::rc_z;
1488     case Assembler::lessEqual:    return Assembler::rc_lez;
1489     case Assembler::less:         return Assembler::rc_lz;
1490     /*case notZero:*/
1491     case Assembler::notEqual:     return Assembler::rc_nz;
1492     case Assembler::greater:      return Assembler::rc_gz;
1493     case Assembler::greaterEqual: return Assembler::rc_gez;
1494   }
1495   ShouldNotReachHere();
1496   return Assembler::rc_z;
1497 }
1498 
1499 // compares (32 bit) register with zero and branches.  NOT FOR USE WITH 64-bit POINTERS
1500 void MacroAssembler::cmp_zero_and_br(Condition c, Register s1, Label& L, bool a, Predict p) {
1501   tst(s1);
1502   br (c, a, p, L);
1503 }
1504 
1505 // Compares a pointer register with zero and branches on null.
1506 // Does a test & branch on 32-bit systems and a register-branch on 64-bit.
1507 void MacroAssembler::br_null( Register s1, bool a, Predict p, Label& L ) {
1508   assert_not_delayed();
1509   bpr( rc_z, a, p, s1, L );
1510 }
1511 
1512 void MacroAssembler::br_notnull( Register s1, bool a, Predict p, Label& L ) {
1513   assert_not_delayed();
1514   bpr( rc_nz, a, p, s1, L );
1515 }
1516 
1517 // Compare registers and branch with nop in delay slot or cbcond without delay slot.
1518 
1519 // Compare integer (32 bit) values (icc only).
1520 void MacroAssembler::cmp_and_br_short(Register s1, Register s2, Condition c,
1521                                       Predict p, Label& L) {
1522   assert_not_delayed();
1523   if (use_cbcond(L)) {
1524     Assembler::cbcond(c, icc, s1, s2, L);
1525   } else {
1526     cmp(s1, s2);
1527     br(c, false, p, L);
1528     delayed()->nop();
1529   }
1530 }
1531 
1532 // Compare integer (32 bit) values (icc only).
1533 void MacroAssembler::cmp_and_br_short(Register s1, int simm13a, Condition c,
1534                                       Predict p, Label& L) {
1535   assert_not_delayed();
1536   if (is_simm(simm13a,5) && use_cbcond(L)) {
1537     Assembler::cbcond(c, icc, s1, simm13a, L);
1538   } else {
1539     cmp(s1, simm13a);
1540     br(c, false, p, L);
1541     delayed()->nop();
1542   }
1543 }
1544 
1545 // Branch that tests xcc in LP64 and icc in !LP64
1546 void MacroAssembler::cmp_and_brx_short(Register s1, Register s2, Condition c,
1547                                        Predict p, Label& L) {
1548   assert_not_delayed();
1549   if (use_cbcond(L)) {
1550     Assembler::cbcond(c, ptr_cc, s1, s2, L);
1551   } else {
1552     cmp(s1, s2);
1553     brx(c, false, p, L);
1554     delayed()->nop();
1555   }
1556 }
1557 
1558 // Branch that tests xcc in LP64 and icc in !LP64
1559 void MacroAssembler::cmp_and_brx_short(Register s1, int simm13a, Condition c,
1560                                        Predict p, Label& L) {
1561   assert_not_delayed();
1562   if (is_simm(simm13a,5) && use_cbcond(L)) {
1563     Assembler::cbcond(c, ptr_cc, s1, simm13a, L);
1564   } else {
1565     cmp(s1, simm13a);
1566     brx(c, false, p, L);
1567     delayed()->nop();
1568   }
1569 }
1570 
1571 // Short branch version for compares a pointer with zero.
1572 
1573 void MacroAssembler::br_null_short(Register s1, Predict p, Label& L) {
1574   assert_not_delayed();
1575   if (use_cbcond(L)) {
1576     Assembler::cbcond(zero, ptr_cc, s1, 0, L);
1577     return;
1578   }
1579   br_null(s1, false, p, L);
1580   delayed()->nop();
1581 }
1582 
1583 void MacroAssembler::br_notnull_short(Register s1, Predict p, Label& L) {
1584   assert_not_delayed();
1585   if (use_cbcond(L)) {
1586     Assembler::cbcond(notZero, ptr_cc, s1, 0, L);
1587     return;
1588   }
1589   br_notnull(s1, false, p, L);
1590   delayed()->nop();
1591 }
1592 
1593 // Unconditional short branch
1594 void MacroAssembler::ba_short(Label& L) {
1595   if (use_cbcond(L)) {
1596     Assembler::cbcond(equal, icc, G0, G0, L);
1597     return;
1598   }
1599   br(always, false, pt, L);
1600   delayed()->nop();
1601 }
1602 
1603 // instruction sequences factored across compiler & interpreter
1604 
1605 
1606 void MacroAssembler::lcmp( Register Ra_hi, Register Ra_low,
1607                            Register Rb_hi, Register Rb_low,
1608                            Register Rresult) {
1609 
1610   Label check_low_parts, done;
1611 
1612   cmp(Ra_hi, Rb_hi );  // compare hi parts
1613   br(equal, true, pt, check_low_parts);
1614   delayed()->cmp(Ra_low, Rb_low); // test low parts
1615 
1616   // And, with an unsigned comparison, it does not matter if the numbers
1617   // are negative or not.
1618   // E.g., -2 cmp -1: the low parts are 0xfffffffe and 0xffffffff.
1619   // The second one is bigger (unsignedly).
1620 
1621   // Other notes:  The first move in each triplet can be unconditional
1622   // (and therefore probably prefetchable).
1623   // And the equals case for the high part does not need testing,
1624   // since that triplet is reached only after finding the high halves differ.
1625 
1626   mov(-1, Rresult);
1627   ba(done);
1628   delayed()->movcc(greater, false, icc,  1, Rresult);
1629 
1630   bind(check_low_parts);
1631 
1632   mov(                               -1, Rresult);
1633   movcc(equal,           false, icc,  0, Rresult);
1634   movcc(greaterUnsigned, false, icc,  1, Rresult);
1635 
1636   bind(done);
1637 }
1638 
1639 void MacroAssembler::lneg( Register Rhi, Register Rlow ) {
1640   subcc(  G0, Rlow, Rlow );
1641   subc(   G0, Rhi,  Rhi  );
1642 }
1643 
1644 void MacroAssembler::lshl( Register Rin_high,  Register Rin_low,
1645                            Register Rcount,
1646                            Register Rout_high, Register Rout_low,
1647                            Register Rtemp ) {
1648 
1649 
1650   Register Ralt_count = Rtemp;
1651   Register Rxfer_bits = Rtemp;
1652 
1653   assert( Ralt_count != Rin_high
1654       &&  Ralt_count != Rin_low
1655       &&  Ralt_count != Rcount
1656       &&  Rxfer_bits != Rin_low
1657       &&  Rxfer_bits != Rin_high
1658       &&  Rxfer_bits != Rcount
1659       &&  Rxfer_bits != Rout_low
1660       &&  Rout_low   != Rin_high,
1661         "register alias checks");
1662 
1663   Label big_shift, done;
1664 
1665   // This code can be optimized to use the 64 bit shifts in V9.
1666   // Here we use the 32 bit shifts.
1667 
1668   and3( Rcount, 0x3f, Rcount);     // take least significant 6 bits
1669   subcc(Rcount,   31, Ralt_count);
1670   br(greater, true, pn, big_shift);
1671   delayed()->dec(Ralt_count);
1672 
1673   // shift < 32 bits, Ralt_count = Rcount-31
1674 
1675   // We get the transfer bits by shifting right by 32-count the low
1676   // register. This is done by shifting right by 31-count and then by one
1677   // more to take care of the special (rare) case where count is zero
1678   // (shifting by 32 would not work).
1679 
1680   neg(Ralt_count);
1681 
1682   // The order of the next two instructions is critical in the case where
1683   // Rin and Rout are the same and should not be reversed.
1684 
1685   srl(Rin_low, Ralt_count, Rxfer_bits); // shift right by 31-count
1686   if (Rcount != Rout_low) {
1687     sll(Rin_low, Rcount, Rout_low); // low half
1688   }
1689   sll(Rin_high, Rcount, Rout_high);
1690   if (Rcount == Rout_low) {
1691     sll(Rin_low, Rcount, Rout_low); // low half
1692   }
1693   srl(Rxfer_bits, 1, Rxfer_bits ); // shift right by one more
1694   ba(done);
1695   delayed()->or3(Rout_high, Rxfer_bits, Rout_high);   // new hi value: or in shifted old hi part and xfer from low
1696 
1697   // shift >= 32 bits, Ralt_count = Rcount-32
1698   bind(big_shift);
1699   sll(Rin_low, Ralt_count, Rout_high  );
1700   clr(Rout_low);
1701 
1702   bind(done);
1703 }
1704 
1705 
1706 void MacroAssembler::lshr( Register Rin_high,  Register Rin_low,
1707                            Register Rcount,
1708                            Register Rout_high, Register Rout_low,
1709                            Register Rtemp ) {
1710 
1711   Register Ralt_count = Rtemp;
1712   Register Rxfer_bits = Rtemp;
1713 
1714   assert( Ralt_count != Rin_high
1715       &&  Ralt_count != Rin_low
1716       &&  Ralt_count != Rcount
1717       &&  Rxfer_bits != Rin_low
1718       &&  Rxfer_bits != Rin_high
1719       &&  Rxfer_bits != Rcount
1720       &&  Rxfer_bits != Rout_high
1721       &&  Rout_high  != Rin_low,
1722         "register alias checks");
1723 
1724   Label big_shift, done;
1725 
1726   // This code can be optimized to use the 64 bit shifts in V9.
1727   // Here we use the 32 bit shifts.
1728 
1729   and3( Rcount, 0x3f, Rcount);     // take least significant 6 bits
1730   subcc(Rcount,   31, Ralt_count);
1731   br(greater, true, pn, big_shift);
1732   delayed()->dec(Ralt_count);
1733 
1734   // shift < 32 bits, Ralt_count = Rcount-31
1735 
1736   // We get the transfer bits by shifting left by 32-count the high
1737   // register. This is done by shifting left by 31-count and then by one
1738   // more to take care of the special (rare) case where count is zero
1739   // (shifting by 32 would not work).
1740 
1741   neg(Ralt_count);
1742   if (Rcount != Rout_low) {
1743     srl(Rin_low, Rcount, Rout_low);
1744   }
1745 
1746   // The order of the next two instructions is critical in the case where
1747   // Rin and Rout are the same and should not be reversed.
1748 
1749   sll(Rin_high, Ralt_count, Rxfer_bits); // shift left by 31-count
1750   sra(Rin_high,     Rcount, Rout_high ); // high half
1751   sll(Rxfer_bits,        1, Rxfer_bits); // shift left by one more
1752   if (Rcount == Rout_low) {
1753     srl(Rin_low, Rcount, Rout_low);
1754   }
1755   ba(done);
1756   delayed()->or3(Rout_low, Rxfer_bits, Rout_low); // new low value: or shifted old low part and xfer from high
1757 
1758   // shift >= 32 bits, Ralt_count = Rcount-32
1759   bind(big_shift);
1760 
1761   sra(Rin_high, Ralt_count, Rout_low);
1762   sra(Rin_high,         31, Rout_high); // sign into hi
1763 
1764   bind( done );
1765 }
1766 
1767 
1768 
1769 void MacroAssembler::lushr( Register Rin_high,  Register Rin_low,
1770                             Register Rcount,
1771                             Register Rout_high, Register Rout_low,
1772                             Register Rtemp ) {
1773 
1774   Register Ralt_count = Rtemp;
1775   Register Rxfer_bits = Rtemp;
1776 
1777   assert( Ralt_count != Rin_high
1778       &&  Ralt_count != Rin_low
1779       &&  Ralt_count != Rcount
1780       &&  Rxfer_bits != Rin_low
1781       &&  Rxfer_bits != Rin_high
1782       &&  Rxfer_bits != Rcount
1783       &&  Rxfer_bits != Rout_high
1784       &&  Rout_high  != Rin_low,
1785         "register alias checks");
1786 
1787   Label big_shift, done;
1788 
1789   // This code can be optimized to use the 64 bit shifts in V9.
1790   // Here we use the 32 bit shifts.
1791 
1792   and3( Rcount, 0x3f, Rcount);     // take least significant 6 bits
1793   subcc(Rcount,   31, Ralt_count);
1794   br(greater, true, pn, big_shift);
1795   delayed()->dec(Ralt_count);
1796 
1797   // shift < 32 bits, Ralt_count = Rcount-31
1798 
1799   // We get the transfer bits by shifting left by 32-count the high
1800   // register. This is done by shifting left by 31-count and then by one
1801   // more to take care of the special (rare) case where count is zero
1802   // (shifting by 32 would not work).
1803 
1804   neg(Ralt_count);
1805   if (Rcount != Rout_low) {
1806     srl(Rin_low, Rcount, Rout_low);
1807   }
1808 
1809   // The order of the next two instructions is critical in the case where
1810   // Rin and Rout are the same and should not be reversed.
1811 
1812   sll(Rin_high, Ralt_count, Rxfer_bits); // shift left by 31-count
1813   srl(Rin_high,     Rcount, Rout_high ); // high half
1814   sll(Rxfer_bits,        1, Rxfer_bits); // shift left by one more
1815   if (Rcount == Rout_low) {
1816     srl(Rin_low, Rcount, Rout_low);
1817   }
1818   ba(done);
1819   delayed()->or3(Rout_low, Rxfer_bits, Rout_low); // new low value: or shifted old low part and xfer from high
1820 
1821   // shift >= 32 bits, Ralt_count = Rcount-32
1822   bind(big_shift);
1823 
1824   srl(Rin_high, Ralt_count, Rout_low);
1825   clr(Rout_high);
1826 
1827   bind( done );
1828 }
1829 
1830 void MacroAssembler::lcmp( Register Ra, Register Rb, Register Rresult) {
1831   cmp(Ra, Rb);
1832   mov(-1, Rresult);
1833   movcc(equal,   false, xcc,  0, Rresult);
1834   movcc(greater, false, xcc,  1, Rresult);
1835 }
1836 
1837 
1838 void MacroAssembler::load_sized_value(Address src, Register dst, size_t size_in_bytes, bool is_signed) {
1839   switch (size_in_bytes) {
1840   case  8:  ld_long(src, dst); break;
1841   case  4:  ld(     src, dst); break;
1842   case  2:  is_signed ? ldsh(src, dst) : lduh(src, dst); break;
1843   case  1:  is_signed ? ldsb(src, dst) : ldub(src, dst); break;
1844   default:  ShouldNotReachHere();
1845   }
1846 }
1847 
1848 void MacroAssembler::store_sized_value(Register src, Address dst, size_t size_in_bytes) {
1849   switch (size_in_bytes) {
1850   case  8:  st_long(src, dst); break;
1851   case  4:  st(     src, dst); break;
1852   case  2:  sth(    src, dst); break;
1853   case  1:  stb(    src, dst); break;
1854   default:  ShouldNotReachHere();
1855   }
1856 }
1857 
1858 
1859 void MacroAssembler::float_cmp( bool is_float, int unordered_result,
1860                                 FloatRegister Fa, FloatRegister Fb,
1861                                 Register Rresult) {
1862   if (is_float) {
1863     fcmp(FloatRegisterImpl::S, fcc0, Fa, Fb);
1864   } else {
1865     fcmp(FloatRegisterImpl::D, fcc0, Fa, Fb);
1866   }
1867 
1868   if (unordered_result == 1) {
1869     mov(                                    -1, Rresult);
1870     movcc(f_equal,              true, fcc0,  0, Rresult);
1871     movcc(f_unorderedOrGreater, true, fcc0,  1, Rresult);
1872   } else {
1873     mov(                                    -1, Rresult);
1874     movcc(f_equal,              true, fcc0,  0, Rresult);
1875     movcc(f_greater,            true, fcc0,  1, Rresult);
1876   }
1877 }
1878 
1879 
1880 void MacroAssembler::save_all_globals_into_locals() {
1881   mov(G1,L1);
1882   mov(G2,L2);
1883   mov(G3,L3);
1884   mov(G4,L4);
1885   mov(G5,L5);
1886   mov(G6,L6);
1887   mov(G7,L7);
1888 }
1889 
1890 void MacroAssembler::restore_globals_from_locals() {
1891   mov(L1,G1);
1892   mov(L2,G2);
1893   mov(L3,G3);
1894   mov(L4,G4);
1895   mov(L5,G5);
1896   mov(L6,G6);
1897   mov(L7,G7);
1898 }
1899 
1900 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
1901                                                       Register tmp,
1902                                                       int offset) {
1903   intptr_t value = *delayed_value_addr;
1904   if (value != 0)
1905     return RegisterOrConstant(value + offset);
1906 
1907   // load indirectly to solve generation ordering problem
1908   AddressLiteral a(delayed_value_addr);
1909   load_ptr_contents(a, tmp);
1910 
1911 #ifdef ASSERT
1912   tst(tmp);
1913   breakpoint_trap(zero, xcc);
1914 #endif
1915 
1916   if (offset != 0)
1917     add(tmp, offset, tmp);
1918 
1919   return RegisterOrConstant(tmp);
1920 }
1921 
1922 
1923 RegisterOrConstant MacroAssembler::regcon_andn_ptr(RegisterOrConstant s1, RegisterOrConstant s2, RegisterOrConstant d, Register temp) {
1924   assert(d.register_or_noreg() != G0, "lost side effect");
1925   if ((s2.is_constant() && s2.as_constant() == 0) ||
1926       (s2.is_register() && s2.as_register() == G0)) {
1927     // Do nothing, just move value.
1928     if (s1.is_register()) {
1929       if (d.is_constant())  d = temp;
1930       mov(s1.as_register(), d.as_register());
1931       return d;
1932     } else {
1933       return s1;
1934     }
1935   }
1936 
1937   if (s1.is_register()) {
1938     assert_different_registers(s1.as_register(), temp);
1939     if (d.is_constant())  d = temp;
1940     andn(s1.as_register(), ensure_simm13_or_reg(s2, temp), d.as_register());
1941     return d;
1942   } else {
1943     if (s2.is_register()) {
1944       assert_different_registers(s2.as_register(), temp);
1945       if (d.is_constant())  d = temp;
1946       set(s1.as_constant(), temp);
1947       andn(temp, s2.as_register(), d.as_register());
1948       return d;
1949     } else {
1950       intptr_t res = s1.as_constant() & ~s2.as_constant();
1951       return res;
1952     }
1953   }
1954 }
1955 
1956 RegisterOrConstant MacroAssembler::regcon_inc_ptr(RegisterOrConstant s1, RegisterOrConstant s2, RegisterOrConstant d, Register temp) {
1957   assert(d.register_or_noreg() != G0, "lost side effect");
1958   if ((s2.is_constant() && s2.as_constant() == 0) ||
1959       (s2.is_register() && s2.as_register() == G0)) {
1960     // Do nothing, just move value.
1961     if (s1.is_register()) {
1962       if (d.is_constant())  d = temp;
1963       mov(s1.as_register(), d.as_register());
1964       return d;
1965     } else {
1966       return s1;
1967     }
1968   }
1969 
1970   if (s1.is_register()) {
1971     assert_different_registers(s1.as_register(), temp);
1972     if (d.is_constant())  d = temp;
1973     add(s1.as_register(), ensure_simm13_or_reg(s2, temp), d.as_register());
1974     return d;
1975   } else {
1976     if (s2.is_register()) {
1977       assert_different_registers(s2.as_register(), temp);
1978       if (d.is_constant())  d = temp;
1979       add(s2.as_register(), ensure_simm13_or_reg(s1, temp), d.as_register());
1980       return d;
1981     } else {
1982       intptr_t res = s1.as_constant() + s2.as_constant();
1983       return res;
1984     }
1985   }
1986 }
1987 
1988 RegisterOrConstant MacroAssembler::regcon_sll_ptr(RegisterOrConstant s1, RegisterOrConstant s2, RegisterOrConstant d, Register temp) {
1989   assert(d.register_or_noreg() != G0, "lost side effect");
1990   if (!is_simm13(s2.constant_or_zero()))
1991     s2 = (s2.as_constant() & 0xFF);
1992   if ((s2.is_constant() && s2.as_constant() == 0) ||
1993       (s2.is_register() && s2.as_register() == G0)) {
1994     // Do nothing, just move value.
1995     if (s1.is_register()) {
1996       if (d.is_constant())  d = temp;
1997       mov(s1.as_register(), d.as_register());
1998       return d;
1999     } else {
2000       return s1;
2001     }
2002   }
2003 
2004   if (s1.is_register()) {
2005     assert_different_registers(s1.as_register(), temp);
2006     if (d.is_constant())  d = temp;
2007     sll_ptr(s1.as_register(), ensure_simm13_or_reg(s2, temp), d.as_register());
2008     return d;
2009   } else {
2010     if (s2.is_register()) {
2011       assert_different_registers(s2.as_register(), temp);
2012       if (d.is_constant())  d = temp;
2013       set(s1.as_constant(), temp);
2014       sll_ptr(temp, s2.as_register(), d.as_register());
2015       return d;
2016     } else {
2017       intptr_t res = s1.as_constant() << s2.as_constant();
2018       return res;
2019     }
2020   }
2021 }
2022 
2023 
2024 // Look up the method for a megamorphic invokeinterface call.
2025 // The target method is determined by <intf_klass, itable_index>.
2026 // The receiver klass is in recv_klass.
2027 // On success, the result will be in method_result, and execution falls through.
2028 // On failure, execution transfers to the given label.
2029 void MacroAssembler::lookup_interface_method(Register recv_klass,
2030                                              Register intf_klass,
2031                                              RegisterOrConstant itable_index,
2032                                              Register method_result,
2033                                              Register scan_temp,
2034                                              Register sethi_temp,
2035                                              Label& L_no_such_interface) {
2036   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
2037   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
2038          "caller must use same register for non-constant itable index as for method");
2039 
2040   Label L_no_such_interface_restore;
2041   bool did_save = false;
2042   if (scan_temp == noreg || sethi_temp == noreg) {
2043     Register recv_2 = recv_klass->is_global() ? recv_klass : L0;
2044     Register intf_2 = intf_klass->is_global() ? intf_klass : L1;
2045     assert(method_result->is_global(), "must be able to return value");
2046     scan_temp  = L2;
2047     sethi_temp = L3;
2048     save_frame_and_mov(0, recv_klass, recv_2, intf_klass, intf_2);
2049     recv_klass = recv_2;
2050     intf_klass = intf_2;
2051     did_save = true;
2052   }
2053 
2054   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
2055   int vtable_base = in_bytes(Klass::vtable_start_offset());
2056   int scan_step   = itableOffsetEntry::size() * wordSize;
2057   int vte_size    = vtableEntry::size_in_bytes();
2058 
2059   lduw(recv_klass, in_bytes(Klass::vtable_length_offset()), scan_temp);
2060   // %%% We should store the aligned, prescaled offset in the klassoop.
2061   // Then the next several instructions would fold away.
2062 
2063   int itb_offset = vtable_base;
2064   int itb_scale = exact_log2(vtableEntry::size_in_bytes());
2065   sll(scan_temp, itb_scale,  scan_temp);
2066   add(scan_temp, itb_offset, scan_temp);
2067   add(recv_klass, scan_temp, scan_temp);
2068 
2069   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
2070   RegisterOrConstant itable_offset = itable_index;
2071   itable_offset = regcon_sll_ptr(itable_index, exact_log2(itableMethodEntry::size() * wordSize), itable_offset);
2072   itable_offset = regcon_inc_ptr(itable_offset, itableMethodEntry::method_offset_in_bytes(), itable_offset);
2073   add(recv_klass, ensure_simm13_or_reg(itable_offset, sethi_temp), recv_klass);
2074 
2075   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
2076   //   if (scan->interface() == intf) {
2077   //     result = (klass + scan->offset() + itable_index);
2078   //   }
2079   // }
2080   Label L_search, L_found_method;
2081 
2082   for (int peel = 1; peel >= 0; peel--) {
2083     // %%%% Could load both offset and interface in one ldx, if they were
2084     // in the opposite order.  This would save a load.
2085     ld_ptr(scan_temp, itableOffsetEntry::interface_offset_in_bytes(), method_result);
2086 
2087     // Check that this entry is non-null.  A null entry means that
2088     // the receiver class doesn't implement the interface, and wasn't the
2089     // same as when the caller was compiled.
2090     bpr(Assembler::rc_z, false, Assembler::pn, method_result, did_save ? L_no_such_interface_restore : L_no_such_interface);
2091     delayed()->cmp(method_result, intf_klass);
2092 
2093     if (peel) {
2094       brx(Assembler::equal,    false, Assembler::pt, L_found_method);
2095     } else {
2096       brx(Assembler::notEqual, false, Assembler::pn, L_search);
2097       // (invert the test to fall through to found_method...)
2098     }
2099     delayed()->add(scan_temp, scan_step, scan_temp);
2100 
2101     if (!peel)  break;
2102 
2103     bind(L_search);
2104   }
2105 
2106   bind(L_found_method);
2107 
2108   // Got a hit.
2109   int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
2110   // scan_temp[-scan_step] points to the vtable offset we need
2111   ito_offset -= scan_step;
2112   lduw(scan_temp, ito_offset, scan_temp);
2113   ld_ptr(recv_klass, scan_temp, method_result);
2114 
2115   if (did_save) {
2116     Label L_done;
2117     ba(L_done);
2118     delayed()->restore();
2119 
2120     bind(L_no_such_interface_restore);
2121     ba(L_no_such_interface);
2122     delayed()->restore();
2123 
2124     bind(L_done);
2125   }
2126 }
2127 
2128 
2129 // virtual method calling
2130 void MacroAssembler::lookup_virtual_method(Register recv_klass,
2131                                            RegisterOrConstant vtable_index,
2132                                            Register method_result) {
2133   assert_different_registers(recv_klass, method_result, vtable_index.register_or_noreg());
2134   Register sethi_temp = method_result;
2135   const int base = in_bytes(Klass::vtable_start_offset()) +
2136                    // method pointer offset within the vtable entry:
2137                    vtableEntry::method_offset_in_bytes();
2138   RegisterOrConstant vtable_offset = vtable_index;
2139   // Each of the following three lines potentially generates an instruction.
2140   // But the total number of address formation instructions will always be
2141   // at most two, and will often be zero.  In any case, it will be optimal.
2142   // If vtable_index is a register, we will have (sll_ptr N,x; inc_ptr B,x; ld_ptr k,x).
2143   // If vtable_index is a constant, we will have at most (set B+X<<N,t; ld_ptr k,t).
2144   vtable_offset = regcon_sll_ptr(vtable_index, exact_log2(vtableEntry::size_in_bytes()), vtable_offset);
2145   vtable_offset = regcon_inc_ptr(vtable_offset, base, vtable_offset, sethi_temp);
2146   Address vtable_entry_addr(recv_klass, ensure_simm13_or_reg(vtable_offset, sethi_temp));
2147   ld_ptr(vtable_entry_addr, method_result);
2148 }
2149 
2150 
2151 void MacroAssembler::check_klass_subtype(Register sub_klass,
2152                                          Register super_klass,
2153                                          Register temp_reg,
2154                                          Register temp2_reg,
2155                                          Label& L_success) {
2156   Register sub_2 = sub_klass;
2157   Register sup_2 = super_klass;
2158   if (!sub_2->is_global())  sub_2 = L0;
2159   if (!sup_2->is_global())  sup_2 = L1;
2160   bool did_save = false;
2161   if (temp_reg == noreg || temp2_reg == noreg) {
2162     temp_reg = L2;
2163     temp2_reg = L3;
2164     save_frame_and_mov(0, sub_klass, sub_2, super_klass, sup_2);
2165     sub_klass = sub_2;
2166     super_klass = sup_2;
2167     did_save = true;
2168   }
2169   Label L_failure, L_pop_to_failure, L_pop_to_success;
2170   check_klass_subtype_fast_path(sub_klass, super_klass,
2171                                 temp_reg, temp2_reg,
2172                                 (did_save ? &L_pop_to_success : &L_success),
2173                                 (did_save ? &L_pop_to_failure : &L_failure), NULL);
2174 
2175   if (!did_save)
2176     save_frame_and_mov(0, sub_klass, sub_2, super_klass, sup_2);
2177   check_klass_subtype_slow_path(sub_2, sup_2,
2178                                 L2, L3, L4, L5,
2179                                 NULL, &L_pop_to_failure);
2180 
2181   // on success:
2182   bind(L_pop_to_success);
2183   restore();
2184   ba_short(L_success);
2185 
2186   // on failure:
2187   bind(L_pop_to_failure);
2188   restore();
2189   bind(L_failure);
2190 }
2191 
2192 
2193 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
2194                                                    Register super_klass,
2195                                                    Register temp_reg,
2196                                                    Register temp2_reg,
2197                                                    Label* L_success,
2198                                                    Label* L_failure,
2199                                                    Label* L_slow_path,
2200                                         RegisterOrConstant super_check_offset) {
2201   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
2202   int sco_offset = in_bytes(Klass::super_check_offset_offset());
2203 
2204   bool must_load_sco  = (super_check_offset.constant_or_zero() == -1);
2205   bool need_slow_path = (must_load_sco ||
2206                          super_check_offset.constant_or_zero() == sco_offset);
2207 
2208   assert_different_registers(sub_klass, super_klass, temp_reg);
2209   if (super_check_offset.is_register()) {
2210     assert_different_registers(sub_klass, super_klass, temp_reg,
2211                                super_check_offset.as_register());
2212   } else if (must_load_sco) {
2213     assert(temp2_reg != noreg, "supply either a temp or a register offset");
2214   }
2215 
2216   Label L_fallthrough;
2217   int label_nulls = 0;
2218   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
2219   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
2220   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
2221   assert(label_nulls <= 1 ||
2222          (L_slow_path == &L_fallthrough && label_nulls <= 2 && !need_slow_path),
2223          "at most one NULL in the batch, usually");
2224 
2225   // If the pointers are equal, we are done (e.g., String[] elements).
2226   // This self-check enables sharing of secondary supertype arrays among
2227   // non-primary types such as array-of-interface.  Otherwise, each such
2228   // type would need its own customized SSA.
2229   // We move this check to the front of the fast path because many
2230   // type checks are in fact trivially successful in this manner,
2231   // so we get a nicely predicted branch right at the start of the check.
2232   cmp(super_klass, sub_klass);
2233   brx(Assembler::equal, false, Assembler::pn, *L_success);
2234   delayed()->nop();
2235 
2236   // Check the supertype display:
2237   if (must_load_sco) {
2238     // The super check offset is always positive...
2239     lduw(super_klass, sco_offset, temp2_reg);
2240     super_check_offset = RegisterOrConstant(temp2_reg);
2241     // super_check_offset is register.
2242     assert_different_registers(sub_klass, super_klass, temp_reg, super_check_offset.as_register());
2243   }
2244   ld_ptr(sub_klass, super_check_offset, temp_reg);
2245   cmp(super_klass, temp_reg);
2246 
2247   // This check has worked decisively for primary supers.
2248   // Secondary supers are sought in the super_cache ('super_cache_addr').
2249   // (Secondary supers are interfaces and very deeply nested subtypes.)
2250   // This works in the same check above because of a tricky aliasing
2251   // between the super_cache and the primary super display elements.
2252   // (The 'super_check_addr' can address either, as the case requires.)
2253   // Note that the cache is updated below if it does not help us find
2254   // what we need immediately.
2255   // So if it was a primary super, we can just fail immediately.
2256   // Otherwise, it's the slow path for us (no success at this point).
2257 
2258   // Hacked ba(), which may only be used just before L_fallthrough.
2259 #define FINAL_JUMP(label)            \
2260   if (&(label) != &L_fallthrough) {  \
2261     ba(label);  delayed()->nop();    \
2262   }
2263 
2264   if (super_check_offset.is_register()) {
2265     brx(Assembler::equal, false, Assembler::pn, *L_success);
2266     delayed()->cmp(super_check_offset.as_register(), sc_offset);
2267 
2268     if (L_failure == &L_fallthrough) {
2269       brx(Assembler::equal, false, Assembler::pt, *L_slow_path);
2270       delayed()->nop();
2271     } else {
2272       brx(Assembler::notEqual, false, Assembler::pn, *L_failure);
2273       delayed()->nop();
2274       FINAL_JUMP(*L_slow_path);
2275     }
2276   } else if (super_check_offset.as_constant() == sc_offset) {
2277     // Need a slow path; fast failure is impossible.
2278     if (L_slow_path == &L_fallthrough) {
2279       brx(Assembler::equal, false, Assembler::pt, *L_success);
2280       delayed()->nop();
2281     } else {
2282       brx(Assembler::notEqual, false, Assembler::pn, *L_slow_path);
2283       delayed()->nop();
2284       FINAL_JUMP(*L_success);
2285     }
2286   } else {
2287     // No slow path; it's a fast decision.
2288     if (L_failure == &L_fallthrough) {
2289       brx(Assembler::equal, false, Assembler::pt, *L_success);
2290       delayed()->nop();
2291     } else {
2292       brx(Assembler::notEqual, false, Assembler::pn, *L_failure);
2293       delayed()->nop();
2294       FINAL_JUMP(*L_success);
2295     }
2296   }
2297 
2298   bind(L_fallthrough);
2299 
2300 #undef FINAL_JUMP
2301 }
2302 
2303 
2304 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
2305                                                    Register super_klass,
2306                                                    Register count_temp,
2307                                                    Register scan_temp,
2308                                                    Register scratch_reg,
2309                                                    Register coop_reg,
2310                                                    Label* L_success,
2311                                                    Label* L_failure) {
2312   assert_different_registers(sub_klass, super_klass,
2313                              count_temp, scan_temp, scratch_reg, coop_reg);
2314 
2315   Label L_fallthrough, L_loop;
2316   int label_nulls = 0;
2317   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
2318   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
2319   assert(label_nulls <= 1, "at most one NULL in the batch");
2320 
2321   // a couple of useful fields in sub_klass:
2322   int ss_offset = in_bytes(Klass::secondary_supers_offset());
2323   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
2324 
2325   // Do a linear scan of the secondary super-klass chain.
2326   // This code is rarely used, so simplicity is a virtue here.
2327 
2328 #ifndef PRODUCT
2329   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
2330   inc_counter((address) pst_counter, count_temp, scan_temp);
2331 #endif
2332 
2333   // We will consult the secondary-super array.
2334   ld_ptr(sub_klass, ss_offset, scan_temp);
2335 
2336   Register search_key = super_klass;
2337 
2338   // Load the array length.  (Positive movl does right thing on LP64.)
2339   lduw(scan_temp, Array<Klass*>::length_offset_in_bytes(), count_temp);
2340 
2341   // Check for empty secondary super list
2342   tst(count_temp);
2343 
2344   // In the array of super classes elements are pointer sized.
2345   int element_size = wordSize;
2346 
2347   // Top of search loop
2348   bind(L_loop);
2349   br(Assembler::equal, false, Assembler::pn, *L_failure);
2350   delayed()->add(scan_temp, element_size, scan_temp);
2351 
2352   // Skip the array header in all array accesses.
2353   int elem_offset = Array<Klass*>::base_offset_in_bytes();
2354   elem_offset -= element_size;   // the scan pointer was pre-incremented also
2355 
2356   // Load next super to check
2357     ld_ptr( scan_temp, elem_offset, scratch_reg );
2358 
2359   // Look for Rsuper_klass on Rsub_klass's secondary super-class-overflow list
2360   cmp(scratch_reg, search_key);
2361 
2362   // A miss means we are NOT a subtype and need to keep looping
2363   brx(Assembler::notEqual, false, Assembler::pn, L_loop);
2364   delayed()->deccc(count_temp); // decrement trip counter in delay slot
2365 
2366   // Success.  Cache the super we found and proceed in triumph.
2367   st_ptr(super_klass, sub_klass, sc_offset);
2368 
2369   if (L_success != &L_fallthrough) {
2370     ba(*L_success);
2371     delayed()->nop();
2372   }
2373 
2374   bind(L_fallthrough);
2375 }
2376 
2377 
2378 RegisterOrConstant MacroAssembler::argument_offset(RegisterOrConstant arg_slot,
2379                                                    Register temp_reg,
2380                                                    int extra_slot_offset) {
2381   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
2382   int stackElementSize = Interpreter::stackElementSize;
2383   int offset = extra_slot_offset * stackElementSize;
2384   if (arg_slot.is_constant()) {
2385     offset += arg_slot.as_constant() * stackElementSize;
2386     return offset;
2387   } else {
2388     assert(temp_reg != noreg, "must specify");
2389     sll_ptr(arg_slot.as_register(), exact_log2(stackElementSize), temp_reg);
2390     if (offset != 0)
2391       add(temp_reg, offset, temp_reg);
2392     return temp_reg;
2393   }
2394 }
2395 
2396 
2397 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
2398                                          Register temp_reg,
2399                                          int extra_slot_offset) {
2400   return Address(Gargs, argument_offset(arg_slot, temp_reg, extra_slot_offset));
2401 }
2402 
2403 
2404 void MacroAssembler::biased_locking_enter(Register obj_reg, Register mark_reg,
2405                                           Register temp_reg,
2406                                           Label& done, Label* slow_case,
2407                                           BiasedLockingCounters* counters) {
2408   assert(UseBiasedLocking, "why call this otherwise?");
2409 
2410   if (PrintBiasedLockingStatistics) {
2411     assert_different_registers(obj_reg, mark_reg, temp_reg, O7);
2412     if (counters == NULL)
2413       counters = BiasedLocking::counters();
2414   }
2415 
2416   Label cas_label;
2417 
2418   // Biased locking
2419   // See whether the lock is currently biased toward our thread and
2420   // whether the epoch is still valid
2421   // Note that the runtime guarantees sufficient alignment of JavaThread
2422   // pointers to allow age to be placed into low bits
2423   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
2424   and3(mark_reg, markOopDesc::biased_lock_mask_in_place, temp_reg);
2425   cmp_and_brx_short(temp_reg, markOopDesc::biased_lock_pattern, Assembler::notEqual, Assembler::pn, cas_label);
2426 
2427   load_klass(obj_reg, temp_reg);
2428   ld_ptr(Address(temp_reg, Klass::prototype_header_offset()), temp_reg);
2429   or3(G2_thread, temp_reg, temp_reg);
2430   xor3(mark_reg, temp_reg, temp_reg);
2431   andcc(temp_reg, ~((int) markOopDesc::age_mask_in_place), temp_reg);
2432   if (counters != NULL) {
2433     cond_inc(Assembler::equal, (address) counters->biased_lock_entry_count_addr(), mark_reg, temp_reg);
2434     // Reload mark_reg as we may need it later
2435     ld_ptr(Address(obj_reg, oopDesc::mark_offset_in_bytes()), mark_reg);
2436   }
2437   brx(Assembler::equal, true, Assembler::pt, done);
2438   delayed()->nop();
2439 
2440   Label try_revoke_bias;
2441   Label try_rebias;
2442   Address mark_addr = Address(obj_reg, oopDesc::mark_offset_in_bytes());
2443   assert(mark_addr.disp() == 0, "cas must take a zero displacement");
2444 
2445   // At this point we know that the header has the bias pattern and
2446   // that we are not the bias owner in the current epoch. We need to
2447   // figure out more details about the state of the header in order to
2448   // know what operations can be legally performed on the object's
2449   // header.
2450 
2451   // If the low three bits in the xor result aren't clear, that means
2452   // the prototype header is no longer biased and we have to revoke
2453   // the bias on this object.
2454   btst(markOopDesc::biased_lock_mask_in_place, temp_reg);
2455   brx(Assembler::notZero, false, Assembler::pn, try_revoke_bias);
2456 
2457   // Biasing is still enabled for this data type. See whether the
2458   // epoch of the current bias is still valid, meaning that the epoch
2459   // bits of the mark word are equal to the epoch bits of the
2460   // prototype header. (Note that the prototype header's epoch bits
2461   // only change at a safepoint.) If not, attempt to rebias the object
2462   // toward the current thread. Note that we must be absolutely sure
2463   // that the current epoch is invalid in order to do this because
2464   // otherwise the manipulations it performs on the mark word are
2465   // illegal.
2466   delayed()->btst(markOopDesc::epoch_mask_in_place, temp_reg);
2467   brx(Assembler::notZero, false, Assembler::pn, try_rebias);
2468 
2469   // The epoch of the current bias is still valid but we know nothing
2470   // about the owner; it might be set or it might be clear. Try to
2471   // acquire the bias of the object using an atomic operation. If this
2472   // fails we will go in to the runtime to revoke the object's bias.
2473   // Note that we first construct the presumed unbiased header so we
2474   // don't accidentally blow away another thread's valid bias.
2475   delayed()->and3(mark_reg,
2476                   markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place,
2477                   mark_reg);
2478   or3(G2_thread, mark_reg, temp_reg);
2479   cas_ptr(mark_addr.base(), mark_reg, temp_reg);
2480   // If the biasing toward our thread failed, this means that
2481   // another thread succeeded in biasing it toward itself and we
2482   // need to revoke that bias. The revocation will occur in the
2483   // interpreter runtime in the slow case.
2484   cmp(mark_reg, temp_reg);
2485   if (counters != NULL) {
2486     cond_inc(Assembler::zero, (address) counters->anonymously_biased_lock_entry_count_addr(), mark_reg, temp_reg);
2487   }
2488   if (slow_case != NULL) {
2489     brx(Assembler::notEqual, true, Assembler::pn, *slow_case);
2490     delayed()->nop();
2491   }
2492   ba_short(done);
2493 
2494   bind(try_rebias);
2495   // At this point we know the epoch has expired, meaning that the
2496   // current "bias owner", if any, is actually invalid. Under these
2497   // circumstances _only_, we are allowed to use the current header's
2498   // value as the comparison value when doing the cas to acquire the
2499   // bias in the current epoch. In other words, we allow transfer of
2500   // the bias from one thread to another directly in this situation.
2501   //
2502   // FIXME: due to a lack of registers we currently blow away the age
2503   // bits in this situation. Should attempt to preserve them.
2504   load_klass(obj_reg, temp_reg);
2505   ld_ptr(Address(temp_reg, Klass::prototype_header_offset()), temp_reg);
2506   or3(G2_thread, temp_reg, temp_reg);
2507   cas_ptr(mark_addr.base(), mark_reg, temp_reg);
2508   // If the biasing toward our thread failed, this means that
2509   // another thread succeeded in biasing it toward itself and we
2510   // need to revoke that bias. The revocation will occur in the
2511   // interpreter runtime in the slow case.
2512   cmp(mark_reg, temp_reg);
2513   if (counters != NULL) {
2514     cond_inc(Assembler::zero, (address) counters->rebiased_lock_entry_count_addr(), mark_reg, temp_reg);
2515   }
2516   if (slow_case != NULL) {
2517     brx(Assembler::notEqual, true, Assembler::pn, *slow_case);
2518     delayed()->nop();
2519   }
2520   ba_short(done);
2521 
2522   bind(try_revoke_bias);
2523   // The prototype mark in the klass doesn't have the bias bit set any
2524   // more, indicating that objects of this data type are not supposed
2525   // to be biased any more. We are going to try to reset the mark of
2526   // this object to the prototype value and fall through to the
2527   // CAS-based locking scheme. Note that if our CAS fails, it means
2528   // that another thread raced us for the privilege of revoking the
2529   // bias of this particular object, so it's okay to continue in the
2530   // normal locking code.
2531   //
2532   // FIXME: due to a lack of registers we currently blow away the age
2533   // bits in this situation. Should attempt to preserve them.
2534   load_klass(obj_reg, temp_reg);
2535   ld_ptr(Address(temp_reg, Klass::prototype_header_offset()), temp_reg);
2536   cas_ptr(mark_addr.base(), mark_reg, temp_reg);
2537   // Fall through to the normal CAS-based lock, because no matter what
2538   // the result of the above CAS, some thread must have succeeded in
2539   // removing the bias bit from the object's header.
2540   if (counters != NULL) {
2541     cmp(mark_reg, temp_reg);
2542     cond_inc(Assembler::zero, (address) counters->revoked_lock_entry_count_addr(), mark_reg, temp_reg);
2543   }
2544 
2545   bind(cas_label);
2546 }
2547 
2548 void MacroAssembler::biased_locking_exit (Address mark_addr, Register temp_reg, Label& done,
2549                                           bool allow_delay_slot_filling) {
2550   // Check for biased locking unlock case, which is a no-op
2551   // Note: we do not have to check the thread ID for two reasons.
2552   // First, the interpreter checks for IllegalMonitorStateException at
2553   // a higher level. Second, if the bias was revoked while we held the
2554   // lock, the object could not be rebiased toward another thread, so
2555   // the bias bit would be clear.
2556   ld_ptr(mark_addr, temp_reg);
2557   and3(temp_reg, markOopDesc::biased_lock_mask_in_place, temp_reg);
2558   cmp(temp_reg, markOopDesc::biased_lock_pattern);
2559   brx(Assembler::equal, allow_delay_slot_filling, Assembler::pt, done);
2560   delayed();
2561   if (!allow_delay_slot_filling) {
2562     nop();
2563   }
2564 }
2565 
2566 
2567 // compiler_lock_object() and compiler_unlock_object() are direct transliterations
2568 // of i486.ad fast_lock() and fast_unlock().  See those methods for detailed comments.
2569 // The code could be tightened up considerably.
2570 //
2571 // box->dhw disposition - post-conditions at DONE_LABEL.
2572 // -   Successful inflated lock:  box->dhw != 0.
2573 //     Any non-zero value suffices.
2574 //     Consider G2_thread, rsp, boxReg, or markOopDesc::unused_mark()
2575 // -   Successful Stack-lock: box->dhw == mark.
2576 //     box->dhw must contain the displaced mark word value
2577 // -   Failure -- icc.ZFlag == 0 and box->dhw is undefined.
2578 //     The slow-path fast_enter() and slow_enter() operators
2579 //     are responsible for setting box->dhw = NonZero (typically markOopDesc::unused_mark()).
2580 // -   Biased: box->dhw is undefined
2581 //
2582 // SPARC refworkload performance - specifically jetstream and scimark - are
2583 // extremely sensitive to the size of the code emitted by compiler_lock_object
2584 // and compiler_unlock_object.  Critically, the key factor is code size, not path
2585 // length.  (Simply experiments to pad CLO with unexecuted NOPs demonstrte the
2586 // effect).
2587 
2588 
2589 void MacroAssembler::compiler_lock_object(Register Roop, Register Rmark,
2590                                           Register Rbox, Register Rscratch,
2591                                           BiasedLockingCounters* counters,
2592                                           bool try_bias) {
2593    Address mark_addr(Roop, oopDesc::mark_offset_in_bytes());
2594 
2595    verify_oop(Roop);
2596    Label done ;
2597 
2598    if (counters != NULL) {
2599      inc_counter((address) counters->total_entry_count_addr(), Rmark, Rscratch);
2600    }
2601 
2602    if (EmitSync & 1) {
2603      mov(3, Rscratch);
2604      st_ptr(Rscratch, Rbox, BasicLock::displaced_header_offset_in_bytes());
2605      cmp(SP, G0);
2606      return ;
2607    }
2608 
2609    if (EmitSync & 2) {
2610 
2611      // Fetch object's markword
2612      ld_ptr(mark_addr, Rmark);
2613 
2614      if (try_bias) {
2615         biased_locking_enter(Roop, Rmark, Rscratch, done, NULL, counters);
2616      }
2617 
2618      // Save Rbox in Rscratch to be used for the cas operation
2619      mov(Rbox, Rscratch);
2620 
2621      // set Rmark to markOop | markOopDesc::unlocked_value
2622      or3(Rmark, markOopDesc::unlocked_value, Rmark);
2623 
2624      // Initialize the box.  (Must happen before we update the object mark!)
2625      st_ptr(Rmark, Rbox, BasicLock::displaced_header_offset_in_bytes());
2626 
2627      // compare object markOop with Rmark and if equal exchange Rscratch with object markOop
2628      assert(mark_addr.disp() == 0, "cas must take a zero displacement");
2629      cas_ptr(mark_addr.base(), Rmark, Rscratch);
2630 
2631      // if compare/exchange succeeded we found an unlocked object and we now have locked it
2632      // hence we are done
2633      cmp(Rmark, Rscratch);
2634      sub(Rscratch, STACK_BIAS, Rscratch);
2635      brx(Assembler::equal, false, Assembler::pt, done);
2636      delayed()->sub(Rscratch, SP, Rscratch);  //pull next instruction into delay slot
2637 
2638      // we did not find an unlocked object so see if this is a recursive case
2639      // sub(Rscratch, SP, Rscratch);
2640      assert(os::vm_page_size() > 0xfff, "page size too small - change the constant");
2641      andcc(Rscratch, 0xfffff003, Rscratch);
2642      st_ptr(Rscratch, Rbox, BasicLock::displaced_header_offset_in_bytes());
2643      bind (done);
2644      return ;
2645    }
2646 
2647    Label Egress ;
2648 
2649    if (EmitSync & 256) {
2650       Label IsInflated ;
2651 
2652       ld_ptr(mark_addr, Rmark);           // fetch obj->mark
2653       // Triage: biased, stack-locked, neutral, inflated
2654       if (try_bias) {
2655         biased_locking_enter(Roop, Rmark, Rscratch, done, NULL, counters);
2656         // Invariant: if control reaches this point in the emitted stream
2657         // then Rmark has not been modified.
2658       }
2659 
2660       // Store mark into displaced mark field in the on-stack basic-lock "box"
2661       // Critically, this must happen before the CAS
2662       // Maximize the ST-CAS distance to minimize the ST-before-CAS penalty.
2663       st_ptr(Rmark, Rbox, BasicLock::displaced_header_offset_in_bytes());
2664       andcc(Rmark, 2, G0);
2665       brx(Assembler::notZero, false, Assembler::pn, IsInflated);
2666       delayed()->
2667 
2668       // Try stack-lock acquisition.
2669       // Beware: the 1st instruction is in a delay slot
2670       mov(Rbox,  Rscratch);
2671       or3(Rmark, markOopDesc::unlocked_value, Rmark);
2672       assert(mark_addr.disp() == 0, "cas must take a zero displacement");
2673       cas_ptr(mark_addr.base(), Rmark, Rscratch);
2674       cmp(Rmark, Rscratch);
2675       brx(Assembler::equal, false, Assembler::pt, done);
2676       delayed()->sub(Rscratch, SP, Rscratch);
2677 
2678       // Stack-lock attempt failed - check for recursive stack-lock.
2679       // See the comments below about how we might remove this case.
2680       sub(Rscratch, STACK_BIAS, Rscratch);
2681       assert(os::vm_page_size() > 0xfff, "page size too small - change the constant");
2682       andcc(Rscratch, 0xfffff003, Rscratch);
2683       br(Assembler::always, false, Assembler::pt, done);
2684       delayed()-> st_ptr(Rscratch, Rbox, BasicLock::displaced_header_offset_in_bytes());
2685 
2686       bind(IsInflated);
2687       if (EmitSync & 64) {
2688          // If m->owner != null goto IsLocked
2689          // Pessimistic form: Test-and-CAS vs CAS
2690          // The optimistic form avoids RTS->RTO cache line upgrades.
2691          ld_ptr(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner), Rscratch);
2692          andcc(Rscratch, Rscratch, G0);
2693          brx(Assembler::notZero, false, Assembler::pn, done);
2694          delayed()->nop();
2695          // m->owner == null : it's unlocked.
2696       }
2697 
2698       // Try to CAS m->owner from null to Self
2699       // Invariant: if we acquire the lock then _recursions should be 0.
2700       add(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner), Rmark);
2701       mov(G2_thread, Rscratch);
2702       cas_ptr(Rmark, G0, Rscratch);
2703       cmp(Rscratch, G0);
2704       // Intentional fall-through into done
2705    } else {
2706       // Aggressively avoid the Store-before-CAS penalty
2707       // Defer the store into box->dhw until after the CAS
2708       Label IsInflated, Recursive ;
2709 
2710 // Anticipate CAS -- Avoid RTS->RTO upgrade
2711 // prefetch (mark_addr, Assembler::severalWritesAndPossiblyReads);
2712 
2713       ld_ptr(mark_addr, Rmark);           // fetch obj->mark
2714       // Triage: biased, stack-locked, neutral, inflated
2715 
2716       if (try_bias) {
2717         biased_locking_enter(Roop, Rmark, Rscratch, done, NULL, counters);
2718         // Invariant: if control reaches this point in the emitted stream
2719         // then Rmark has not been modified.
2720       }
2721       andcc(Rmark, 2, G0);
2722       brx(Assembler::notZero, false, Assembler::pn, IsInflated);
2723       delayed()->                         // Beware - dangling delay-slot
2724 
2725       // Try stack-lock acquisition.
2726       // Transiently install BUSY (0) encoding in the mark word.
2727       // if the CAS of 0 into the mark was successful then we execute:
2728       //   ST box->dhw  = mark   -- save fetched mark in on-stack basiclock box
2729       //   ST obj->mark = box    -- overwrite transient 0 value
2730       // This presumes TSO, of course.
2731 
2732       mov(0, Rscratch);
2733       or3(Rmark, markOopDesc::unlocked_value, Rmark);
2734       assert(mark_addr.disp() == 0, "cas must take a zero displacement");
2735       cas_ptr(mark_addr.base(), Rmark, Rscratch);
2736 // prefetch (mark_addr, Assembler::severalWritesAndPossiblyReads);
2737       cmp(Rscratch, Rmark);
2738       brx(Assembler::notZero, false, Assembler::pn, Recursive);
2739       delayed()->st_ptr(Rmark, Rbox, BasicLock::displaced_header_offset_in_bytes());
2740       if (counters != NULL) {
2741         cond_inc(Assembler::equal, (address) counters->fast_path_entry_count_addr(), Rmark, Rscratch);
2742       }
2743       ba(done);
2744       delayed()->st_ptr(Rbox, mark_addr);
2745 
2746       bind(Recursive);
2747       // Stack-lock attempt failed - check for recursive stack-lock.
2748       // Tests show that we can remove the recursive case with no impact
2749       // on refworkload 0.83.  If we need to reduce the size of the code
2750       // emitted by compiler_lock_object() the recursive case is perfect
2751       // candidate.
2752       //
2753       // A more extreme idea is to always inflate on stack-lock recursion.
2754       // This lets us eliminate the recursive checks in compiler_lock_object
2755       // and compiler_unlock_object and the (box->dhw == 0) encoding.
2756       // A brief experiment - requiring changes to synchronizer.cpp, interpreter,
2757       // and showed a performance *increase*.  In the same experiment I eliminated
2758       // the fast-path stack-lock code from the interpreter and always passed
2759       // control to the "slow" operators in synchronizer.cpp.
2760 
2761       // RScratch contains the fetched obj->mark value from the failed CAS.
2762       sub(Rscratch, STACK_BIAS, Rscratch);
2763       sub(Rscratch, SP, Rscratch);
2764       assert(os::vm_page_size() > 0xfff, "page size too small - change the constant");
2765       andcc(Rscratch, 0xfffff003, Rscratch);
2766       if (counters != NULL) {
2767         // Accounting needs the Rscratch register
2768         st_ptr(Rscratch, Rbox, BasicLock::displaced_header_offset_in_bytes());
2769         cond_inc(Assembler::equal, (address) counters->fast_path_entry_count_addr(), Rmark, Rscratch);
2770         ba_short(done);
2771       } else {
2772         ba(done);
2773         delayed()->st_ptr(Rscratch, Rbox, BasicLock::displaced_header_offset_in_bytes());
2774       }
2775 
2776       bind   (IsInflated);
2777 
2778       // Try to CAS m->owner from null to Self
2779       // Invariant: if we acquire the lock then _recursions should be 0.
2780       add(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner), Rmark);
2781       mov(G2_thread, Rscratch);
2782       cas_ptr(Rmark, G0, Rscratch);
2783       andcc(Rscratch, Rscratch, G0);             // set ICCs for done: icc.zf iff success
2784       // set icc.zf : 1=success 0=failure
2785       // ST box->displaced_header = NonZero.
2786       // Any non-zero value suffices:
2787       //    markOopDesc::unused_mark(), G2_thread, RBox, RScratch, rsp, etc.
2788       st_ptr(Rbox, Rbox, BasicLock::displaced_header_offset_in_bytes());
2789       // Intentional fall-through into done
2790    }
2791 
2792    bind   (done);
2793 }
2794 
2795 void MacroAssembler::compiler_unlock_object(Register Roop, Register Rmark,
2796                                             Register Rbox, Register Rscratch,
2797                                             bool try_bias) {
2798    Address mark_addr(Roop, oopDesc::mark_offset_in_bytes());
2799 
2800    Label done ;
2801 
2802    if (EmitSync & 4) {
2803      cmp(SP, G0);
2804      return ;
2805    }
2806 
2807    if (EmitSync & 8) {
2808      if (try_bias) {
2809         biased_locking_exit(mark_addr, Rscratch, done);
2810      }
2811 
2812      // Test first if it is a fast recursive unlock
2813      ld_ptr(Rbox, BasicLock::displaced_header_offset_in_bytes(), Rmark);
2814      br_null_short(Rmark, Assembler::pt, done);
2815 
2816      // Check if it is still a light weight lock, this is is true if we see
2817      // the stack address of the basicLock in the markOop of the object
2818      assert(mark_addr.disp() == 0, "cas must take a zero displacement");
2819      cas_ptr(mark_addr.base(), Rbox, Rmark);
2820      ba(done);
2821      delayed()->cmp(Rbox, Rmark);
2822      bind(done);
2823      return ;
2824    }
2825 
2826    // Beware ... If the aggregate size of the code emitted by CLO and CUO is
2827    // is too large performance rolls abruptly off a cliff.
2828    // This could be related to inlining policies, code cache management, or
2829    // I$ effects.
2830    Label LStacked ;
2831 
2832    if (try_bias) {
2833       // TODO: eliminate redundant LDs of obj->mark
2834       biased_locking_exit(mark_addr, Rscratch, done);
2835    }
2836 
2837    ld_ptr(Roop, oopDesc::mark_offset_in_bytes(), Rmark);
2838    ld_ptr(Rbox, BasicLock::displaced_header_offset_in_bytes(), Rscratch);
2839    andcc(Rscratch, Rscratch, G0);
2840    brx(Assembler::zero, false, Assembler::pn, done);
2841    delayed()->nop();      // consider: relocate fetch of mark, above, into this DS
2842    andcc(Rmark, 2, G0);
2843    brx(Assembler::zero, false, Assembler::pt, LStacked);
2844    delayed()->nop();
2845 
2846    // It's inflated
2847    // Conceptually we need a #loadstore|#storestore "release" MEMBAR before
2848    // the ST of 0 into _owner which releases the lock.  This prevents loads
2849    // and stores within the critical section from reordering (floating)
2850    // past the store that releases the lock.  But TSO is a strong memory model
2851    // and that particular flavor of barrier is a noop, so we can safely elide it.
2852    // Note that we use 1-0 locking by default for the inflated case.  We
2853    // close the resultant (and rare) race by having contended threads in
2854    // monitorenter periodically poll _owner.
2855 
2856    if (EmitSync & 1024) {
2857      // Emit code to check that _owner == Self
2858      // We could fold the _owner test into subsequent code more efficiently
2859      // than using a stand-alone check, but since _owner checking is off by
2860      // default we don't bother. We also might consider predicating the
2861      // _owner==Self check on Xcheck:jni or running on a debug build.
2862      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), Rscratch);
2863      orcc(Rscratch, G0, G0);
2864      brx(Assembler::notZero, false, Assembler::pn, done);
2865      delayed()->nop();
2866    }
2867 
2868    if (EmitSync & 512) {
2869      // classic lock release code absent 1-0 locking
2870      //   m->Owner = null;
2871      //   membar #storeload
2872      //   if (m->cxq|m->EntryList) == null goto Success
2873      //   if (m->succ != null) goto Success
2874      //   if CAS (&m->Owner,0,Self) != 0 goto Success
2875      //   goto SlowPath
2876      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)), Rbox);
2877      orcc(Rbox, G0, G0);
2878      brx(Assembler::notZero, false, Assembler::pn, done);
2879      delayed()->nop();
2880      st_ptr(G0, Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2881      if (os::is_MP()) { membar(StoreLoad); }
2882      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)), Rscratch);
2883      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)), Rbox);
2884      orcc(Rbox, Rscratch, G0);
2885      brx(Assembler::zero, false, Assembler::pt, done);
2886      delayed()->
2887      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), Rscratch);
2888      andcc(Rscratch, Rscratch, G0);
2889      brx(Assembler::notZero, false, Assembler::pt, done);
2890      delayed()->andcc(G0, G0, G0);
2891      add(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner), Rmark);
2892      mov(G2_thread, Rscratch);
2893      cas_ptr(Rmark, G0, Rscratch);
2894      cmp(Rscratch, G0);
2895      // invert icc.zf and goto done
2896      brx(Assembler::notZero, false, Assembler::pt, done);
2897      delayed()->cmp(G0, G0);
2898      br(Assembler::always, false, Assembler::pt, done);
2899      delayed()->cmp(G0, 1);
2900    } else {
2901      // 1-0 form : avoids CAS and MEMBAR in the common case
2902      // Do not bother to ratify that m->Owner == Self.
2903      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)), Rbox);
2904      orcc(Rbox, G0, G0);
2905      brx(Assembler::notZero, false, Assembler::pn, done);
2906      delayed()->
2907      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)), Rscratch);
2908      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)), Rbox);
2909      orcc(Rbox, Rscratch, G0);
2910      if (EmitSync & 16384) {
2911        // As an optional optimization, if (EntryList|cxq) != null and _succ is null then
2912        // we should transfer control directly to the slow-path.
2913        // This test makes the reacquire operation below very infrequent.
2914        // The logic is equivalent to :
2915        //   if (cxq|EntryList) == null : Owner=null; goto Success
2916        //   if succ == null : goto SlowPath
2917        //   Owner=null; membar #storeload
2918        //   if succ != null : goto Success
2919        //   if CAS(&Owner,null,Self) != null goto Success
2920        //   goto SlowPath
2921        brx(Assembler::zero, true, Assembler::pt, done);
2922        delayed()->
2923        st_ptr(G0, Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2924        ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), Rscratch);
2925        andcc(Rscratch, Rscratch, G0) ;
2926        brx(Assembler::zero, false, Assembler::pt, done);
2927        delayed()->orcc(G0, 1, G0);
2928        st_ptr(G0, Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2929      } else {
2930        brx(Assembler::zero, false, Assembler::pt, done);
2931        delayed()->
2932        st_ptr(G0, Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2933      }
2934      if (os::is_MP()) { membar(StoreLoad); }
2935      // Check that _succ is (or remains) non-zero
2936      ld_ptr(Address(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), Rscratch);
2937      andcc(Rscratch, Rscratch, G0);
2938      brx(Assembler::notZero, false, Assembler::pt, done);
2939      delayed()->andcc(G0, G0, G0);
2940      add(Rmark, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner), Rmark);
2941      mov(G2_thread, Rscratch);
2942      cas_ptr(Rmark, G0, Rscratch);
2943      cmp(Rscratch, G0);
2944      // invert icc.zf and goto done
2945      // A slightly better v8+/v9 idiom would be the following:
2946      //   movrnz Rscratch,1,Rscratch
2947      //   ba done
2948      //   xorcc Rscratch,1,G0
2949      // In v8+ mode the idiom would be valid IFF Rscratch was a G or O register
2950      brx(Assembler::notZero, false, Assembler::pt, done);
2951      delayed()->cmp(G0, G0);
2952      br(Assembler::always, false, Assembler::pt, done);
2953      delayed()->cmp(G0, 1);
2954    }
2955 
2956    bind   (LStacked);
2957    // Consider: we could replace the expensive CAS in the exit
2958    // path with a simple ST of the displaced mark value fetched from
2959    // the on-stack basiclock box.  That admits a race where a thread T2
2960    // in the slow lock path -- inflating with monitor M -- could race a
2961    // thread T1 in the fast unlock path, resulting in a missed wakeup for T2.
2962    // More precisely T1 in the stack-lock unlock path could "stomp" the
2963    // inflated mark value M installed by T2, resulting in an orphan
2964    // object monitor M and T2 becoming stranded.  We can remedy that situation
2965    // by having T2 periodically poll the object's mark word using timed wait
2966    // operations.  If T2 discovers that a stomp has occurred it vacates
2967    // the monitor M and wakes any other threads stranded on the now-orphan M.
2968    // In addition the monitor scavenger, which performs deflation,
2969    // would also need to check for orpan monitors and stranded threads.
2970    //
2971    // Finally, inflation is also used when T2 needs to assign a hashCode
2972    // to O and O is stack-locked by T1.  The "stomp" race could cause
2973    // an assigned hashCode value to be lost.  We can avoid that condition
2974    // and provide the necessary hashCode stability invariants by ensuring
2975    // that hashCode generation is idempotent between copying GCs.
2976    // For example we could compute the hashCode of an object O as
2977    // O's heap address XOR some high quality RNG value that is refreshed
2978    // at GC-time.  The monitor scavenger would install the hashCode
2979    // found in any orphan monitors.  Again, the mechanism admits a
2980    // lost-update "stomp" WAW race but detects and recovers as needed.
2981    //
2982    // A prototype implementation showed excellent results, although
2983    // the scavenger and timeout code was rather involved.
2984 
2985    cas_ptr(mark_addr.base(), Rbox, Rscratch);
2986    cmp(Rbox, Rscratch);
2987    // Intentional fall through into done ...
2988 
2989    bind(done);
2990 }
2991 
2992 
2993 
2994 void MacroAssembler::print_CPU_state() {
2995   // %%%%% need to implement this
2996 }
2997 
2998 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
2999   // %%%%% need to implement this
3000 }
3001 
3002 void MacroAssembler::push_IU_state() {
3003   // %%%%% need to implement this
3004 }
3005 
3006 
3007 void MacroAssembler::pop_IU_state() {
3008   // %%%%% need to implement this
3009 }
3010 
3011 
3012 void MacroAssembler::push_FPU_state() {
3013   // %%%%% need to implement this
3014 }
3015 
3016 
3017 void MacroAssembler::pop_FPU_state() {
3018   // %%%%% need to implement this
3019 }
3020 
3021 
3022 void MacroAssembler::push_CPU_state() {
3023   // %%%%% need to implement this
3024 }
3025 
3026 
3027 void MacroAssembler::pop_CPU_state() {
3028   // %%%%% need to implement this
3029 }
3030 
3031 
3032 
3033 void MacroAssembler::verify_tlab() {
3034 #ifdef ASSERT
3035   if (UseTLAB && VerifyOops) {
3036     Label next, next2, ok;
3037     Register t1 = L0;
3038     Register t2 = L1;
3039     Register t3 = L2;
3040 
3041     save_frame(0);
3042     ld_ptr(G2_thread, in_bytes(JavaThread::tlab_top_offset()), t1);
3043     ld_ptr(G2_thread, in_bytes(JavaThread::tlab_start_offset()), t2);
3044     or3(t1, t2, t3);
3045     cmp_and_br_short(t1, t2, Assembler::greaterEqual, Assembler::pn, next);
3046     STOP("assert(top >= start)");
3047     should_not_reach_here();
3048 
3049     bind(next);
3050     ld_ptr(G2_thread, in_bytes(JavaThread::tlab_top_offset()), t1);
3051     ld_ptr(G2_thread, in_bytes(JavaThread::tlab_end_offset()), t2);
3052     or3(t3, t2, t3);
3053     cmp_and_br_short(t1, t2, Assembler::lessEqual, Assembler::pn, next2);
3054     STOP("assert(top <= end)");
3055     should_not_reach_here();
3056 
3057     bind(next2);
3058     and3(t3, MinObjAlignmentInBytesMask, t3);
3059     cmp_and_br_short(t3, 0, Assembler::lessEqual, Assembler::pn, ok);
3060     STOP("assert(aligned)");
3061     should_not_reach_here();
3062 
3063     bind(ok);
3064     restore();
3065   }
3066 #endif
3067 }
3068 
3069 
3070 void MacroAssembler::eden_allocate(
3071   Register obj,                        // result: pointer to object after successful allocation
3072   Register var_size_in_bytes,          // object size in bytes if unknown at compile time; invalid otherwise
3073   int      con_size_in_bytes,          // object size in bytes if   known at compile time
3074   Register t1,                         // temp register
3075   Register t2,                         // temp register
3076   Label&   slow_case                   // continuation point if fast allocation fails
3077 ){
3078   // make sure arguments make sense
3079   assert_different_registers(obj, var_size_in_bytes, t1, t2);
3080   assert(0 <= con_size_in_bytes && Assembler::is_simm13(con_size_in_bytes), "illegal object size");
3081   assert((con_size_in_bytes & MinObjAlignmentInBytesMask) == 0, "object size is not multiple of alignment");
3082 
3083   if (!Universe::heap()->supports_inline_contig_alloc()) {
3084     // No allocation in the shared eden.
3085     ba(slow_case);
3086     delayed()->nop();
3087   } else {
3088     // get eden boundaries
3089     // note: we need both top & top_addr!
3090     const Register top_addr = t1;
3091     const Register end      = t2;
3092 
3093     CollectedHeap* ch = Universe::heap();
3094     set((intx)ch->top_addr(), top_addr);
3095     intx delta = (intx)ch->end_addr() - (intx)ch->top_addr();
3096     ld_ptr(top_addr, delta, end);
3097     ld_ptr(top_addr, 0, obj);
3098 
3099     // try to allocate
3100     Label retry;
3101     bind(retry);
3102 #ifdef ASSERT
3103     // make sure eden top is properly aligned
3104     {
3105       Label L;
3106       btst(MinObjAlignmentInBytesMask, obj);
3107       br(Assembler::zero, false, Assembler::pt, L);
3108       delayed()->nop();
3109       STOP("eden top is not properly aligned");
3110       bind(L);
3111     }
3112 #endif // ASSERT
3113     const Register free = end;
3114     sub(end, obj, free);                                   // compute amount of free space
3115     if (var_size_in_bytes->is_valid()) {
3116       // size is unknown at compile time
3117       cmp(free, var_size_in_bytes);
3118       brx(Assembler::lessUnsigned, false, Assembler::pn, slow_case); // if there is not enough space go the slow case
3119       delayed()->add(obj, var_size_in_bytes, end);
3120     } else {
3121       // size is known at compile time
3122       cmp(free, con_size_in_bytes);
3123       brx(Assembler::lessUnsigned, false, Assembler::pn, slow_case); // if there is not enough space go the slow case
3124       delayed()->add(obj, con_size_in_bytes, end);
3125     }
3126     // Compare obj with the value at top_addr; if still equal, swap the value of
3127     // end with the value at top_addr. If not equal, read the value at top_addr
3128     // into end.
3129     cas_ptr(top_addr, obj, end);
3130     // if someone beat us on the allocation, try again, otherwise continue
3131     cmp(obj, end);
3132     brx(Assembler::notEqual, false, Assembler::pn, retry);
3133     delayed()->mov(end, obj);                              // nop if successfull since obj == end
3134 
3135 #ifdef ASSERT
3136     // make sure eden top is properly aligned
3137     {
3138       Label L;
3139       const Register top_addr = t1;
3140 
3141       set((intx)ch->top_addr(), top_addr);
3142       ld_ptr(top_addr, 0, top_addr);
3143       btst(MinObjAlignmentInBytesMask, top_addr);
3144       br(Assembler::zero, false, Assembler::pt, L);
3145       delayed()->nop();
3146       STOP("eden top is not properly aligned");
3147       bind(L);
3148     }
3149 #endif // ASSERT
3150   }
3151 }
3152 
3153 
3154 void MacroAssembler::tlab_allocate(
3155   Register obj,                        // result: pointer to object after successful allocation
3156   Register var_size_in_bytes,          // object size in bytes if unknown at compile time; invalid otherwise
3157   int      con_size_in_bytes,          // object size in bytes if   known at compile time
3158   Register t1,                         // temp register
3159   Label&   slow_case                   // continuation point if fast allocation fails
3160 ){
3161   // make sure arguments make sense
3162   assert_different_registers(obj, var_size_in_bytes, t1);
3163   assert(0 <= con_size_in_bytes && is_simm13(con_size_in_bytes), "illegal object size");
3164   assert((con_size_in_bytes & MinObjAlignmentInBytesMask) == 0, "object size is not multiple of alignment");
3165 
3166   const Register free  = t1;
3167 
3168   verify_tlab();
3169 
3170   ld_ptr(G2_thread, in_bytes(JavaThread::tlab_top_offset()), obj);
3171 
3172   // calculate amount of free space
3173   ld_ptr(G2_thread, in_bytes(JavaThread::tlab_end_offset()), free);
3174   sub(free, obj, free);
3175 
3176   Label done;
3177   if (var_size_in_bytes == noreg) {
3178     cmp(free, con_size_in_bytes);
3179   } else {
3180     cmp(free, var_size_in_bytes);
3181   }
3182   br(Assembler::less, false, Assembler::pn, slow_case);
3183   // calculate the new top pointer
3184   if (var_size_in_bytes == noreg) {
3185     delayed()->add(obj, con_size_in_bytes, free);
3186   } else {
3187     delayed()->add(obj, var_size_in_bytes, free);
3188   }
3189 
3190   bind(done);
3191 
3192 #ifdef ASSERT
3193   // make sure new free pointer is properly aligned
3194   {
3195     Label L;
3196     btst(MinObjAlignmentInBytesMask, free);
3197     br(Assembler::zero, false, Assembler::pt, L);
3198     delayed()->nop();
3199     STOP("updated TLAB free is not properly aligned");
3200     bind(L);
3201   }
3202 #endif // ASSERT
3203 
3204   // update the tlab top pointer
3205   st_ptr(free, G2_thread, in_bytes(JavaThread::tlab_top_offset()));
3206   verify_tlab();
3207 }
3208 
3209 
3210 void MacroAssembler::tlab_refill(Label& retry, Label& try_eden, Label& slow_case) {
3211   Register top = O0;
3212   Register t1 = G1;
3213   Register t2 = G3;
3214   Register t3 = O1;
3215   assert_different_registers(top, t1, t2, t3, G4, G5 /* preserve G4 and G5 */);
3216   Label do_refill, discard_tlab;
3217 
3218   if (!Universe::heap()->supports_inline_contig_alloc()) {
3219     // No allocation in the shared eden.
3220     ba(slow_case);
3221     delayed()->nop();
3222   }
3223 
3224   ld_ptr(G2_thread, in_bytes(JavaThread::tlab_top_offset()), top);
3225   ld_ptr(G2_thread, in_bytes(JavaThread::tlab_end_offset()), t1);
3226   ld_ptr(G2_thread, in_bytes(JavaThread::tlab_refill_waste_limit_offset()), t2);
3227 
3228   // calculate amount of free space
3229   sub(t1, top, t1);
3230   srl_ptr(t1, LogHeapWordSize, t1);
3231 
3232   // Retain tlab and allocate object in shared space if
3233   // the amount free in the tlab is too large to discard.
3234   cmp(t1, t2);
3235 
3236   brx(Assembler::lessEqual, false, Assembler::pt, discard_tlab);
3237   // increment waste limit to prevent getting stuck on this slow path
3238   if (Assembler::is_simm13(ThreadLocalAllocBuffer::refill_waste_limit_increment())) {
3239     delayed()->add(t2, ThreadLocalAllocBuffer::refill_waste_limit_increment(), t2);
3240   } else {
3241     delayed()->nop();
3242     // set64 does not use the temp register if the given constant is 32 bit. So
3243     // we can just use any register; using G0 results in ignoring of the upper 32 bit
3244     // of that value.
3245     set64(ThreadLocalAllocBuffer::refill_waste_limit_increment(), t3, G0);
3246     add(t2, t3, t2);
3247   }
3248 
3249   st_ptr(t2, G2_thread, in_bytes(JavaThread::tlab_refill_waste_limit_offset()));
3250   if (TLABStats) {
3251     // increment number of slow_allocations
3252     ld(G2_thread, in_bytes(JavaThread::tlab_slow_allocations_offset()), t2);
3253     add(t2, 1, t2);
3254     stw(t2, G2_thread, in_bytes(JavaThread::tlab_slow_allocations_offset()));
3255   }
3256   ba(try_eden);
3257   delayed()->nop();
3258 
3259   bind(discard_tlab);
3260   if (TLABStats) {
3261     // increment number of refills
3262     ld(G2_thread, in_bytes(JavaThread::tlab_number_of_refills_offset()), t2);
3263     add(t2, 1, t2);
3264     stw(t2, G2_thread, in_bytes(JavaThread::tlab_number_of_refills_offset()));
3265     // accumulate wastage
3266     ld(G2_thread, in_bytes(JavaThread::tlab_fast_refill_waste_offset()), t2);
3267     add(t2, t1, t2);
3268     stw(t2, G2_thread, in_bytes(JavaThread::tlab_fast_refill_waste_offset()));
3269   }
3270 
3271   // if tlab is currently allocated (top or end != null) then
3272   // fill [top, end + alignment_reserve) with array object
3273   br_null_short(top, Assembler::pn, do_refill);
3274 
3275   set((intptr_t)markOopDesc::prototype()->copy_set_hash(0x2), t2);
3276   st_ptr(t2, top, oopDesc::mark_offset_in_bytes()); // set up the mark word
3277   // set klass to intArrayKlass
3278   sub(t1, typeArrayOopDesc::header_size(T_INT), t1);
3279   add(t1, ThreadLocalAllocBuffer::alignment_reserve(), t1);
3280   sll_ptr(t1, log2_intptr(HeapWordSize/sizeof(jint)), t1);
3281   st(t1, top, arrayOopDesc::length_offset_in_bytes());
3282   set((intptr_t)Universe::intArrayKlassObj_addr(), t2);
3283   ld_ptr(t2, 0, t2);
3284   // store klass last.  concurrent gcs assumes klass length is valid if
3285   // klass field is not null.
3286   store_klass(t2, top);
3287   verify_oop(top);
3288 
3289   ld_ptr(G2_thread, in_bytes(JavaThread::tlab_start_offset()), t1);
3290   sub(top, t1, t1); // size of tlab's allocated portion
3291   incr_allocated_bytes(t1, t2, t3);
3292 
3293   // refill the tlab with an eden allocation
3294   bind(do_refill);
3295   ld_ptr(G2_thread, in_bytes(JavaThread::tlab_size_offset()), t1);
3296   sll_ptr(t1, LogHeapWordSize, t1);
3297   // allocate new tlab, address returned in top
3298   eden_allocate(top, t1, 0, t2, t3, slow_case);
3299 
3300   st_ptr(top, G2_thread, in_bytes(JavaThread::tlab_start_offset()));
3301   st_ptr(top, G2_thread, in_bytes(JavaThread::tlab_top_offset()));
3302 #ifdef ASSERT
3303   // check that tlab_size (t1) is still valid
3304   {
3305     Label ok;
3306     ld_ptr(G2_thread, in_bytes(JavaThread::tlab_size_offset()), t2);
3307     sll_ptr(t2, LogHeapWordSize, t2);
3308     cmp_and_br_short(t1, t2, Assembler::equal, Assembler::pt, ok);
3309     STOP("assert(t1 == tlab_size)");
3310     should_not_reach_here();
3311 
3312     bind(ok);
3313   }
3314 #endif // ASSERT
3315   add(top, t1, top); // t1 is tlab_size
3316   sub(top, ThreadLocalAllocBuffer::alignment_reserve_in_bytes(), top);
3317   st_ptr(top, G2_thread, in_bytes(JavaThread::tlab_end_offset()));
3318 
3319   if (ZeroTLAB) {
3320     // This is a fast TLAB refill, therefore the GC is not notified of it.
3321     // So compiled code must fill the new TLAB with zeroes.
3322     ld_ptr(G2_thread, in_bytes(JavaThread::tlab_start_offset()), t2);
3323     zero_memory(t2, t1);
3324   }
3325   verify_tlab();
3326   ba(retry);
3327   delayed()->nop();
3328 }
3329 
3330 void MacroAssembler::zero_memory(Register base, Register index) {
3331   assert_different_registers(base, index);
3332   Label loop;
3333   bind(loop);
3334   subcc(index, HeapWordSize, index);
3335   brx(Assembler::greaterEqual, true, Assembler::pt, loop);
3336   delayed()->st_ptr(G0, base, index);
3337 }
3338 
3339 void MacroAssembler::incr_allocated_bytes(RegisterOrConstant size_in_bytes,
3340                                           Register t1, Register t2) {
3341   // Bump total bytes allocated by this thread
3342   assert(t1->is_global(), "must be global reg"); // so all 64 bits are saved on a context switch
3343   assert_different_registers(size_in_bytes.register_or_noreg(), t1, t2);
3344   // v8 support has gone the way of the dodo
3345   ldx(G2_thread, in_bytes(JavaThread::allocated_bytes_offset()), t1);
3346   add(t1, ensure_simm13_or_reg(size_in_bytes, t2), t1);
3347   stx(t1, G2_thread, in_bytes(JavaThread::allocated_bytes_offset()));
3348 }
3349 
3350 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
3351   switch (cond) {
3352     // Note some conditions are synonyms for others
3353     case Assembler::never:                return Assembler::always;
3354     case Assembler::zero:                 return Assembler::notZero;
3355     case Assembler::lessEqual:            return Assembler::greater;
3356     case Assembler::less:                 return Assembler::greaterEqual;
3357     case Assembler::lessEqualUnsigned:    return Assembler::greaterUnsigned;
3358     case Assembler::lessUnsigned:         return Assembler::greaterEqualUnsigned;
3359     case Assembler::negative:             return Assembler::positive;
3360     case Assembler::overflowSet:          return Assembler::overflowClear;
3361     case Assembler::always:               return Assembler::never;
3362     case Assembler::notZero:              return Assembler::zero;
3363     case Assembler::greater:              return Assembler::lessEqual;
3364     case Assembler::greaterEqual:         return Assembler::less;
3365     case Assembler::greaterUnsigned:      return Assembler::lessEqualUnsigned;
3366     case Assembler::greaterEqualUnsigned: return Assembler::lessUnsigned;
3367     case Assembler::positive:             return Assembler::negative;
3368     case Assembler::overflowClear:        return Assembler::overflowSet;
3369   }
3370 
3371   ShouldNotReachHere(); return Assembler::overflowClear;
3372 }
3373 
3374 void MacroAssembler::cond_inc(Assembler::Condition cond, address counter_ptr,
3375                               Register Rtmp1, Register Rtmp2 /*, Register Rtmp3, Register Rtmp4 */) {
3376   Condition negated_cond = negate_condition(cond);
3377   Label L;
3378   brx(negated_cond, false, Assembler::pt, L);
3379   delayed()->nop();
3380   inc_counter(counter_ptr, Rtmp1, Rtmp2);
3381   bind(L);
3382 }
3383 
3384 void MacroAssembler::inc_counter(address counter_addr, Register Rtmp1, Register Rtmp2) {
3385   AddressLiteral addrlit(counter_addr);
3386   sethi(addrlit, Rtmp1);                 // Move hi22 bits into temporary register.
3387   Address addr(Rtmp1, addrlit.low10());  // Build an address with low10 bits.
3388   ld(addr, Rtmp2);
3389   inc(Rtmp2);
3390   st(Rtmp2, addr);
3391 }
3392 
3393 void MacroAssembler::inc_counter(int* counter_addr, Register Rtmp1, Register Rtmp2) {
3394   inc_counter((address) counter_addr, Rtmp1, Rtmp2);
3395 }
3396 
3397 SkipIfEqual::SkipIfEqual(
3398     MacroAssembler* masm, Register temp, const bool* flag_addr,
3399     Assembler::Condition condition) {
3400   _masm = masm;
3401   AddressLiteral flag(flag_addr);
3402   _masm->sethi(flag, temp);
3403   _masm->ldub(temp, flag.low10(), temp);
3404   _masm->tst(temp);
3405   _masm->br(condition, false, Assembler::pt, _label);
3406   _masm->delayed()->nop();
3407 }
3408 
3409 SkipIfEqual::~SkipIfEqual() {
3410   _masm->bind(_label);
3411 }
3412 
3413 
3414 // Writes to stack successive pages until offset reached to check for
3415 // stack overflow + shadow pages.  This clobbers tsp and scratch.
3416 void MacroAssembler::bang_stack_size(Register Rsize, Register Rtsp,
3417                                      Register Rscratch) {
3418   // Use stack pointer in temp stack pointer
3419   mov(SP, Rtsp);
3420 
3421   // Bang stack for total size given plus stack shadow page size.
3422   // Bang one page at a time because a large size can overflow yellow and
3423   // red zones (the bang will fail but stack overflow handling can't tell that
3424   // it was a stack overflow bang vs a regular segv).
3425   int offset = os::vm_page_size();
3426   Register Roffset = Rscratch;
3427 
3428   Label loop;
3429   bind(loop);
3430   set((-offset)+STACK_BIAS, Rscratch);
3431   st(G0, Rtsp, Rscratch);
3432   set(offset, Roffset);
3433   sub(Rsize, Roffset, Rsize);
3434   cmp(Rsize, G0);
3435   br(Assembler::greater, false, Assembler::pn, loop);
3436   delayed()->sub(Rtsp, Roffset, Rtsp);
3437 
3438   // Bang down shadow pages too.
3439   // At this point, (tmp-0) is the last address touched, so don't
3440   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
3441   // was post-decremented.)  Skip this address by starting at i=1, and
3442   // touch a few more pages below.  N.B.  It is important to touch all
3443   // the way down to and including i=StackShadowPages.
3444   for (int i = 1; i < JavaThread::stack_shadow_zone_size() / os::vm_page_size(); i++) {
3445     set((-i*offset)+STACK_BIAS, Rscratch);
3446     st(G0, Rtsp, Rscratch);
3447   }
3448 }
3449 
3450 void MacroAssembler::reserved_stack_check() {
3451   // testing if reserved zone needs to be enabled
3452   Label no_reserved_zone_enabling;
3453 
3454   ld_ptr(G2_thread, JavaThread::reserved_stack_activation_offset(), G4_scratch);
3455   cmp_and_brx_short(SP, G4_scratch, Assembler::lessUnsigned, Assembler::pt, no_reserved_zone_enabling);
3456 
3457   call_VM_leaf(L0, CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), G2_thread);
3458 
3459   AddressLiteral stub(StubRoutines::throw_delayed_StackOverflowError_entry());
3460   jump_to(stub, G4_scratch);
3461   delayed()->restore();
3462 
3463   should_not_reach_here();
3464 
3465   bind(no_reserved_zone_enabling);
3466 }
3467 
3468 ///////////////////////////////////////////////////////////////////////////////////
3469 #if INCLUDE_ALL_GCS
3470 
3471 static address satb_log_enqueue_with_frame = NULL;
3472 static u_char* satb_log_enqueue_with_frame_end = NULL;
3473 
3474 static address satb_log_enqueue_frameless = NULL;
3475 static u_char* satb_log_enqueue_frameless_end = NULL;
3476 
3477 static int EnqueueCodeSize = 128 DEBUG_ONLY( + 256); // Instructions?
3478 
3479 static void generate_satb_log_enqueue(bool with_frame) {
3480   BufferBlob* bb = BufferBlob::create("enqueue_with_frame", EnqueueCodeSize);
3481   CodeBuffer buf(bb);
3482   MacroAssembler masm(&buf);
3483 
3484 #define __ masm.
3485 
3486   address start = __ pc();
3487   Register pre_val;
3488 
3489   Label refill, restart;
3490   if (with_frame) {
3491     __ save_frame(0);
3492     pre_val = I0;  // Was O0 before the save.
3493   } else {
3494     pre_val = O0;
3495   }
3496 
3497   int satb_q_index_byte_offset =
3498     in_bytes(JavaThread::satb_mark_queue_offset() +
3499              SATBMarkQueue::byte_offset_of_index());
3500 
3501   int satb_q_buf_byte_offset =
3502     in_bytes(JavaThread::satb_mark_queue_offset() +
3503              SATBMarkQueue::byte_offset_of_buf());
3504 
3505   assert(in_bytes(SATBMarkQueue::byte_width_of_index()) == sizeof(intptr_t) &&
3506          in_bytes(SATBMarkQueue::byte_width_of_buf()) == sizeof(intptr_t),
3507          "check sizes in assembly below");
3508 
3509   __ bind(restart);
3510 
3511   // Load the index into the SATB buffer. SATBMarkQueue::_index is a size_t
3512   // so ld_ptr is appropriate.
3513   __ ld_ptr(G2_thread, satb_q_index_byte_offset, L0);
3514 
3515   // index == 0?
3516   __ cmp_and_brx_short(L0, G0, Assembler::equal, Assembler::pn, refill);
3517 
3518   __ ld_ptr(G2_thread, satb_q_buf_byte_offset, L1);
3519   __ sub(L0, oopSize, L0);
3520 
3521   __ st_ptr(pre_val, L1, L0);  // [_buf + index] := I0
3522   if (!with_frame) {
3523     // Use return-from-leaf
3524     __ retl();
3525     __ delayed()->st_ptr(L0, G2_thread, satb_q_index_byte_offset);
3526   } else {
3527     // Not delayed.
3528     __ st_ptr(L0, G2_thread, satb_q_index_byte_offset);
3529   }
3530   if (with_frame) {
3531     __ ret();
3532     __ delayed()->restore();
3533   }
3534   __ bind(refill);
3535 
3536   address handle_zero =
3537     CAST_FROM_FN_PTR(address,
3538                      &SATBMarkQueueSet::handle_zero_index_for_thread);
3539   // This should be rare enough that we can afford to save all the
3540   // scratch registers that the calling context might be using.
3541   __ mov(G1_scratch, L0);
3542   __ mov(G3_scratch, L1);
3543   __ mov(G4, L2);
3544   // We need the value of O0 above (for the write into the buffer), so we
3545   // save and restore it.
3546   __ mov(O0, L3);
3547   // Since the call will overwrite O7, we save and restore that, as well.
3548   __ mov(O7, L4);
3549   __ call_VM_leaf(L5, handle_zero, G2_thread);
3550   __ mov(L0, G1_scratch);
3551   __ mov(L1, G3_scratch);
3552   __ mov(L2, G4);
3553   __ mov(L3, O0);
3554   __ br(Assembler::always, /*annul*/false, Assembler::pt, restart);
3555   __ delayed()->mov(L4, O7);
3556 
3557   if (with_frame) {
3558     satb_log_enqueue_with_frame = start;
3559     satb_log_enqueue_with_frame_end = __ pc();
3560   } else {
3561     satb_log_enqueue_frameless = start;
3562     satb_log_enqueue_frameless_end = __ pc();
3563   }
3564 
3565 #undef __
3566 }
3567 
3568 static inline void generate_satb_log_enqueue_if_necessary(bool with_frame) {
3569   if (with_frame) {
3570     if (satb_log_enqueue_with_frame == 0) {
3571       generate_satb_log_enqueue(with_frame);
3572       assert(satb_log_enqueue_with_frame != 0, "postcondition.");
3573     }
3574   } else {
3575     if (satb_log_enqueue_frameless == 0) {
3576       generate_satb_log_enqueue(with_frame);
3577       assert(satb_log_enqueue_frameless != 0, "postcondition.");
3578     }
3579   }
3580 }
3581 
3582 void MacroAssembler::g1_write_barrier_pre(Register obj,
3583                                           Register index,
3584                                           int offset,
3585                                           Register pre_val,
3586                                           Register tmp,
3587                                           bool preserve_o_regs) {
3588   Label filtered;
3589 
3590   if (obj == noreg) {
3591     // We are not loading the previous value so make
3592     // sure that we don't trash the value in pre_val
3593     // with the code below.
3594     assert_different_registers(pre_val, tmp);
3595   } else {
3596     // We will be loading the previous value
3597     // in this code so...
3598     assert(offset == 0 || index == noreg, "choose one");
3599     assert(pre_val == noreg, "check this code");
3600   }
3601 
3602   // Is marking active?
3603   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
3604     ld(G2,
3605        in_bytes(JavaThread::satb_mark_queue_offset() +
3606                 SATBMarkQueue::byte_offset_of_active()),
3607        tmp);
3608   } else {
3609     guarantee(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1,
3610               "Assumption");
3611     ldsb(G2,
3612          in_bytes(JavaThread::satb_mark_queue_offset() +
3613                   SATBMarkQueue::byte_offset_of_active()),
3614          tmp);
3615   }
3616 
3617   // Is marking active?
3618   cmp_and_br_short(tmp, G0, Assembler::equal, Assembler::pt, filtered);
3619 
3620   // Do we need to load the previous value?
3621   if (obj != noreg) {
3622     // Load the previous value...
3623     if (index == noreg) {
3624       if (Assembler::is_simm13(offset)) {
3625         load_heap_oop(obj, offset, tmp);
3626       } else {
3627         set(offset, tmp);
3628         load_heap_oop(obj, tmp, tmp);
3629       }
3630     } else {
3631       load_heap_oop(obj, index, tmp);
3632     }
3633     // Previous value has been loaded into tmp
3634     pre_val = tmp;
3635   }
3636 
3637   assert(pre_val != noreg, "must have a real register");
3638 
3639   // Is the previous value null?
3640   cmp_and_brx_short(pre_val, G0, Assembler::equal, Assembler::pt, filtered);
3641 
3642   // OK, it's not filtered, so we'll need to call enqueue.  In the normal
3643   // case, pre_val will be a scratch G-reg, but there are some cases in
3644   // which it's an O-reg.  In the first case, do a normal call.  In the
3645   // latter, do a save here and call the frameless version.
3646 
3647   guarantee(pre_val->is_global() || pre_val->is_out(),
3648             "Or we need to think harder.");
3649 
3650   if (pre_val->is_global() && !preserve_o_regs) {
3651     generate_satb_log_enqueue_if_necessary(true); // with frame
3652 
3653     call(satb_log_enqueue_with_frame);
3654     delayed()->mov(pre_val, O0);
3655   } else {
3656     generate_satb_log_enqueue_if_necessary(false); // frameless
3657 
3658     save_frame(0);
3659     call(satb_log_enqueue_frameless);
3660     delayed()->mov(pre_val->after_save(), O0);
3661     restore();
3662   }
3663 
3664   bind(filtered);
3665 }
3666 
3667 static address dirty_card_log_enqueue = 0;
3668 static u_char* dirty_card_log_enqueue_end = 0;
3669 
3670 // This gets to assume that o0 contains the object address.
3671 static void generate_dirty_card_log_enqueue(jbyte* byte_map_base) {
3672   BufferBlob* bb = BufferBlob::create("dirty_card_enqueue", EnqueueCodeSize*2);
3673   CodeBuffer buf(bb);
3674   MacroAssembler masm(&buf);
3675 #define __ masm.
3676   address start = __ pc();
3677 
3678   Label not_already_dirty, restart, refill, young_card;
3679 
3680   __ srlx(O0, CardTableModRefBS::card_shift, O0);
3681   AddressLiteral addrlit(byte_map_base);
3682   __ set(addrlit, O1); // O1 := <card table base>
3683   __ ldub(O0, O1, O2); // O2 := [O0 + O1]
3684 
3685   __ cmp_and_br_short(O2, G1SATBCardTableModRefBS::g1_young_card_val(), Assembler::equal, Assembler::pt, young_card);
3686 
3687   __ membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
3688   __ ldub(O0, O1, O2); // O2 := [O0 + O1]
3689 
3690   assert(CardTableModRefBS::dirty_card_val() == 0, "otherwise check this code");
3691   __ cmp_and_br_short(O2, G0, Assembler::notEqual, Assembler::pt, not_already_dirty);
3692 
3693   __ bind(young_card);
3694   // We didn't take the branch, so we're already dirty: return.
3695   // Use return-from-leaf
3696   __ retl();
3697   __ delayed()->nop();
3698 
3699   // Not dirty.
3700   __ bind(not_already_dirty);
3701 
3702   // Get O0 + O1 into a reg by itself
3703   __ add(O0, O1, O3);
3704 
3705   // First, dirty it.
3706   __ stb(G0, O3, G0);  // [cardPtr] := 0  (i.e., dirty).
3707 
3708   int dirty_card_q_index_byte_offset =
3709     in_bytes(JavaThread::dirty_card_queue_offset() +
3710              DirtyCardQueue::byte_offset_of_index());
3711   int dirty_card_q_buf_byte_offset =
3712     in_bytes(JavaThread::dirty_card_queue_offset() +
3713              DirtyCardQueue::byte_offset_of_buf());
3714   __ bind(restart);
3715 
3716   // Load the index into the update buffer. DirtyCardQueue::_index is
3717   // a size_t so ld_ptr is appropriate here.
3718   __ ld_ptr(G2_thread, dirty_card_q_index_byte_offset, L0);
3719 
3720   // index == 0?
3721   __ cmp_and_brx_short(L0, G0, Assembler::equal, Assembler::pn, refill);
3722 
3723   __ ld_ptr(G2_thread, dirty_card_q_buf_byte_offset, L1);
3724   __ sub(L0, oopSize, L0);
3725 
3726   __ st_ptr(O3, L1, L0);  // [_buf + index] := I0
3727   // Use return-from-leaf
3728   __ retl();
3729   __ delayed()->st_ptr(L0, G2_thread, dirty_card_q_index_byte_offset);
3730 
3731   __ bind(refill);
3732   address handle_zero =
3733     CAST_FROM_FN_PTR(address,
3734                      &DirtyCardQueueSet::handle_zero_index_for_thread);
3735   // This should be rare enough that we can afford to save all the
3736   // scratch registers that the calling context might be using.
3737   __ mov(G1_scratch, L3);
3738   __ mov(G3_scratch, L5);
3739   // We need the value of O3 above (for the write into the buffer), so we
3740   // save and restore it.
3741   __ mov(O3, L6);
3742   // Since the call will overwrite O7, we save and restore that, as well.
3743   __ mov(O7, L4);
3744 
3745   __ call_VM_leaf(L7_thread_cache, handle_zero, G2_thread);
3746   __ mov(L3, G1_scratch);
3747   __ mov(L5, G3_scratch);
3748   __ mov(L6, O3);
3749   __ br(Assembler::always, /*annul*/false, Assembler::pt, restart);
3750   __ delayed()->mov(L4, O7);
3751 
3752   dirty_card_log_enqueue = start;
3753   dirty_card_log_enqueue_end = __ pc();
3754   // XXX Should have a guarantee here about not going off the end!
3755   // Does it already do so?  Do an experiment...
3756 
3757 #undef __
3758 
3759 }
3760 
3761 static inline void
3762 generate_dirty_card_log_enqueue_if_necessary(jbyte* byte_map_base) {
3763   if (dirty_card_log_enqueue == 0) {
3764     generate_dirty_card_log_enqueue(byte_map_base);
3765     assert(dirty_card_log_enqueue != 0, "postcondition.");
3766   }
3767 }
3768 
3769 
3770 void MacroAssembler::g1_write_barrier_post(Register store_addr, Register new_val, Register tmp) {
3771 
3772   Label filtered;
3773   MacroAssembler* post_filter_masm = this;
3774 
3775   if (new_val == G0) return;
3776 
3777   G1SATBCardTableLoggingModRefBS* bs =
3778     barrier_set_cast<G1SATBCardTableLoggingModRefBS>(Universe::heap()->barrier_set());
3779 
3780   if (G1RSBarrierRegionFilter) {
3781     xor3(store_addr, new_val, tmp);
3782     srlx(tmp, HeapRegion::LogOfHRGrainBytes, tmp);
3783 
3784     // XXX Should I predict this taken or not?  Does it matter?
3785     cmp_and_brx_short(tmp, G0, Assembler::equal, Assembler::pt, filtered);
3786   }
3787 
3788   // If the "store_addr" register is an "in" or "local" register, move it to
3789   // a scratch reg so we can pass it as an argument.
3790   bool use_scr = !(store_addr->is_global() || store_addr->is_out());
3791   // Pick a scratch register different from "tmp".
3792   Register scr = (tmp == G1_scratch ? G3_scratch : G1_scratch);
3793   // Make sure we use up the delay slot!
3794   if (use_scr) {
3795     post_filter_masm->mov(store_addr, scr);
3796   } else {
3797     post_filter_masm->nop();
3798   }
3799   generate_dirty_card_log_enqueue_if_necessary(bs->byte_map_base);
3800   save_frame(0);
3801   call(dirty_card_log_enqueue);
3802   if (use_scr) {
3803     delayed()->mov(scr, O0);
3804   } else {
3805     delayed()->mov(store_addr->after_save(), O0);
3806   }
3807   restore();
3808 
3809   bind(filtered);
3810 }
3811 
3812 #endif // INCLUDE_ALL_GCS
3813 ///////////////////////////////////////////////////////////////////////////////////
3814 
3815 void MacroAssembler::card_write_barrier_post(Register store_addr, Register new_val, Register tmp) {
3816   // If we're writing constant NULL, we can skip the write barrier.
3817   if (new_val == G0) return;
3818   CardTableModRefBS* bs =
3819     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
3820   assert(bs->kind() == BarrierSet::CardTableForRS ||
3821          bs->kind() == BarrierSet::CardTableExtension, "wrong barrier");
3822   card_table_write(bs->byte_map_base, tmp, store_addr);
3823 }
3824 
3825 // ((OopHandle)result).resolve();
3826 void MacroAssembler::resolve_oop_handle(Register result) {
3827   // OopHandle::resolve is an indirection.
3828   ld_ptr(result, 0, result);
3829 }
3830 
3831 void MacroAssembler::load_mirror(Register mirror, Register method) {
3832   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
3833   ld_ptr(method, in_bytes(Method::const_offset()), mirror);
3834   ld_ptr(mirror, in_bytes(ConstMethod::constants_offset()), mirror);
3835   ld_ptr(mirror, ConstantPool::pool_holder_offset_in_bytes(), mirror);
3836   ld_ptr(mirror, mirror_offset, mirror);
3837 }
3838 
3839 void MacroAssembler::load_klass(Register src_oop, Register klass) {
3840   // The number of bytes in this code is used by
3841   // MachCallDynamicJavaNode::ret_addr_offset()
3842   // if this changes, change that.
3843   if (UseCompressedClassPointers) {
3844     lduw(src_oop, oopDesc::klass_offset_in_bytes(), klass);
3845     decode_klass_not_null(klass);
3846   } else {
3847     ld_ptr(src_oop, oopDesc::klass_offset_in_bytes(), klass);
3848   }
3849 }
3850 
3851 void MacroAssembler::store_klass(Register klass, Register dst_oop) {
3852   if (UseCompressedClassPointers) {
3853     assert(dst_oop != klass, "not enough registers");
3854     encode_klass_not_null(klass);
3855     st(klass, dst_oop, oopDesc::klass_offset_in_bytes());
3856   } else {
3857     st_ptr(klass, dst_oop, oopDesc::klass_offset_in_bytes());
3858   }
3859 }
3860 
3861 void MacroAssembler::store_klass_gap(Register s, Register d) {
3862   if (UseCompressedClassPointers) {
3863     assert(s != d, "not enough registers");
3864     st(s, d, oopDesc::klass_gap_offset_in_bytes());
3865   }
3866 }
3867 
3868 void MacroAssembler::load_heap_oop(const Address& s, Register d) {
3869   if (UseCompressedOops) {
3870     lduw(s, d);
3871     decode_heap_oop(d);
3872   } else {
3873     ld_ptr(s, d);
3874   }
3875 }
3876 
3877 void MacroAssembler::load_heap_oop(Register s1, Register s2, Register d) {
3878    if (UseCompressedOops) {
3879     lduw(s1, s2, d);
3880     decode_heap_oop(d, d);
3881   } else {
3882     ld_ptr(s1, s2, d);
3883   }
3884 }
3885 
3886 void MacroAssembler::load_heap_oop(Register s1, int simm13a, Register d) {
3887    if (UseCompressedOops) {
3888     lduw(s1, simm13a, d);
3889     decode_heap_oop(d, d);
3890   } else {
3891     ld_ptr(s1, simm13a, d);
3892   }
3893 }
3894 
3895 void MacroAssembler::load_heap_oop(Register s1, RegisterOrConstant s2, Register d) {
3896   if (s2.is_constant())  load_heap_oop(s1, s2.as_constant(), d);
3897   else                   load_heap_oop(s1, s2.as_register(), d);
3898 }
3899 
3900 void MacroAssembler::store_heap_oop(Register d, Register s1, Register s2) {
3901   if (UseCompressedOops) {
3902     assert(s1 != d && s2 != d, "not enough registers");
3903     encode_heap_oop(d);
3904     st(d, s1, s2);
3905   } else {
3906     st_ptr(d, s1, s2);
3907   }
3908 }
3909 
3910 void MacroAssembler::store_heap_oop(Register d, Register s1, int simm13a) {
3911   if (UseCompressedOops) {
3912     assert(s1 != d, "not enough registers");
3913     encode_heap_oop(d);
3914     st(d, s1, simm13a);
3915   } else {
3916     st_ptr(d, s1, simm13a);
3917   }
3918 }
3919 
3920 void MacroAssembler::store_heap_oop(Register d, const Address& a, int offset) {
3921   if (UseCompressedOops) {
3922     assert(a.base() != d, "not enough registers");
3923     encode_heap_oop(d);
3924     st(d, a, offset);
3925   } else {
3926     st_ptr(d, a, offset);
3927   }
3928 }
3929 
3930 
3931 void MacroAssembler::encode_heap_oop(Register src, Register dst) {
3932   assert (UseCompressedOops, "must be compressed");
3933   assert (Universe::heap() != NULL, "java heap should be initialized");
3934   assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3935   verify_oop(src);
3936   if (Universe::narrow_oop_base() == NULL) {
3937     srlx(src, LogMinObjAlignmentInBytes, dst);
3938     return;
3939   }
3940   Label done;
3941   if (src == dst) {
3942     // optimize for frequent case src == dst
3943     bpr(rc_nz, true, Assembler::pt, src, done);
3944     delayed() -> sub(src, G6_heapbase, dst); // annuled if not taken
3945     bind(done);
3946     srlx(src, LogMinObjAlignmentInBytes, dst);
3947   } else {
3948     bpr(rc_z, false, Assembler::pn, src, done);
3949     delayed() -> mov(G0, dst);
3950     // could be moved before branch, and annulate delay,
3951     // but may add some unneeded work decoding null
3952     sub(src, G6_heapbase, dst);
3953     srlx(dst, LogMinObjAlignmentInBytes, dst);
3954     bind(done);
3955   }
3956 }
3957 
3958 
3959 void MacroAssembler::encode_heap_oop_not_null(Register r) {
3960   assert (UseCompressedOops, "must be compressed");
3961   assert (Universe::heap() != NULL, "java heap should be initialized");
3962   assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3963   verify_oop(r);
3964   if (Universe::narrow_oop_base() != NULL)
3965     sub(r, G6_heapbase, r);
3966   srlx(r, LogMinObjAlignmentInBytes, r);
3967 }
3968 
3969 void MacroAssembler::encode_heap_oop_not_null(Register src, Register dst) {
3970   assert (UseCompressedOops, "must be compressed");
3971   assert (Universe::heap() != NULL, "java heap should be initialized");
3972   assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3973   verify_oop(src);
3974   if (Universe::narrow_oop_base() == NULL) {
3975     srlx(src, LogMinObjAlignmentInBytes, dst);
3976   } else {
3977     sub(src, G6_heapbase, dst);
3978     srlx(dst, LogMinObjAlignmentInBytes, dst);
3979   }
3980 }
3981 
3982 // Same algorithm as oops.inline.hpp decode_heap_oop.
3983 void  MacroAssembler::decode_heap_oop(Register src, Register dst) {
3984   assert (UseCompressedOops, "must be compressed");
3985   assert (Universe::heap() != NULL, "java heap should be initialized");
3986   assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3987   sllx(src, LogMinObjAlignmentInBytes, dst);
3988   if (Universe::narrow_oop_base() != NULL) {
3989     Label done;
3990     bpr(rc_nz, true, Assembler::pt, dst, done);
3991     delayed() -> add(dst, G6_heapbase, dst); // annuled if not taken
3992     bind(done);
3993   }
3994   verify_oop(dst);
3995 }
3996 
3997 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
3998   // Do not add assert code to this unless you change vtableStubs_sparc.cpp
3999   // pd_code_size_limit.
4000   // Also do not verify_oop as this is called by verify_oop.
4001   assert (UseCompressedOops, "must be compressed");
4002   assert (Universe::heap() != NULL, "java heap should be initialized");
4003   assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
4004   sllx(r, LogMinObjAlignmentInBytes, r);
4005   if (Universe::narrow_oop_base() != NULL)
4006     add(r, G6_heapbase, r);
4007 }
4008 
4009 void  MacroAssembler::decode_heap_oop_not_null(Register src, Register dst) {
4010   // Do not add assert code to this unless you change vtableStubs_sparc.cpp
4011   // pd_code_size_limit.
4012   // Also do not verify_oop as this is called by verify_oop.
4013   assert (UseCompressedOops, "must be compressed");
4014   assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
4015   sllx(src, LogMinObjAlignmentInBytes, dst);
4016   if (Universe::narrow_oop_base() != NULL)
4017     add(dst, G6_heapbase, dst);
4018 }
4019 
4020 void MacroAssembler::encode_klass_not_null(Register r) {
4021   assert (UseCompressedClassPointers, "must be compressed");
4022   if (Universe::narrow_klass_base() != NULL) {
4023     assert(r != G6_heapbase, "bad register choice");
4024     set((intptr_t)Universe::narrow_klass_base(), G6_heapbase);
4025     sub(r, G6_heapbase, r);
4026     if (Universe::narrow_klass_shift() != 0) {
4027       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
4028       srlx(r, LogKlassAlignmentInBytes, r);
4029     }
4030     reinit_heapbase();
4031   } else {
4032     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift() || Universe::narrow_klass_shift() == 0, "decode alg wrong");
4033     srlx(r, Universe::narrow_klass_shift(), r);
4034   }
4035 }
4036 
4037 void MacroAssembler::encode_klass_not_null(Register src, Register dst) {
4038   if (src == dst) {
4039     encode_klass_not_null(src);
4040   } else {
4041     assert (UseCompressedClassPointers, "must be compressed");
4042     if (Universe::narrow_klass_base() != NULL) {
4043       set((intptr_t)Universe::narrow_klass_base(), dst);
4044       sub(src, dst, dst);
4045       if (Universe::narrow_klass_shift() != 0) {
4046         srlx(dst, LogKlassAlignmentInBytes, dst);
4047       }
4048     } else {
4049       // shift src into dst
4050       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift() || Universe::narrow_klass_shift() == 0, "decode alg wrong");
4051       srlx(src, Universe::narrow_klass_shift(), dst);
4052     }
4053   }
4054 }
4055 
4056 // Function instr_size_for_decode_klass_not_null() counts the instructions
4057 // generated by decode_klass_not_null() and reinit_heapbase().  Hence, if
4058 // the instructions they generate change, then this method needs to be updated.
4059 int MacroAssembler::instr_size_for_decode_klass_not_null() {
4060   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
4061   int num_instrs = 1;  // shift src,dst or add
4062   if (Universe::narrow_klass_base() != NULL) {
4063     // set + add + set
4064     num_instrs += insts_for_internal_set((intptr_t)Universe::narrow_klass_base()) +
4065                   insts_for_internal_set((intptr_t)Universe::narrow_ptrs_base());
4066     if (Universe::narrow_klass_shift() != 0) {
4067       num_instrs += 1;  // sllx
4068     }
4069   }
4070   return num_instrs * BytesPerInstWord;
4071 }
4072 
4073 // !!! If the instructions that get generated here change then function
4074 // instr_size_for_decode_klass_not_null() needs to get updated.
4075 void  MacroAssembler::decode_klass_not_null(Register r) {
4076   // Do not add assert code to this unless you change vtableStubs_sparc.cpp
4077   // pd_code_size_limit.
4078   assert (UseCompressedClassPointers, "must be compressed");
4079   if (Universe::narrow_klass_base() != NULL) {
4080     assert(r != G6_heapbase, "bad register choice");
4081     set((intptr_t)Universe::narrow_klass_base(), G6_heapbase);
4082     if (Universe::narrow_klass_shift() != 0)
4083       sllx(r, LogKlassAlignmentInBytes, r);
4084     add(r, G6_heapbase, r);
4085     reinit_heapbase();
4086   } else {
4087     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift() || Universe::narrow_klass_shift() == 0, "decode alg wrong");
4088     sllx(r, Universe::narrow_klass_shift(), r);
4089   }
4090 }
4091 
4092 void  MacroAssembler::decode_klass_not_null(Register src, Register dst) {
4093   if (src == dst) {
4094     decode_klass_not_null(src);
4095   } else {
4096     // Do not add assert code to this unless you change vtableStubs_sparc.cpp
4097     // pd_code_size_limit.
4098     assert (UseCompressedClassPointers, "must be compressed");
4099     if (Universe::narrow_klass_base() != NULL) {
4100       if (Universe::narrow_klass_shift() != 0) {
4101         assert((src != G6_heapbase) && (dst != G6_heapbase), "bad register choice");
4102         set((intptr_t)Universe::narrow_klass_base(), G6_heapbase);
4103         sllx(src, LogKlassAlignmentInBytes, dst);
4104         add(dst, G6_heapbase, dst);
4105         reinit_heapbase();
4106       } else {
4107         set((intptr_t)Universe::narrow_klass_base(), dst);
4108         add(src, dst, dst);
4109       }
4110     } else {
4111       // shift/mov src into dst.
4112       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift() || Universe::narrow_klass_shift() == 0, "decode alg wrong");
4113       sllx(src, Universe::narrow_klass_shift(), dst);
4114     }
4115   }
4116 }
4117 
4118 void MacroAssembler::reinit_heapbase() {
4119   if (UseCompressedOops || UseCompressedClassPointers) {
4120     if (Universe::heap() != NULL) {
4121       set((intptr_t)Universe::narrow_ptrs_base(), G6_heapbase);
4122     } else {
4123       AddressLiteral base(Universe::narrow_ptrs_base_addr());
4124       load_ptr_contents(base, G6_heapbase);
4125     }
4126   }
4127 }
4128 
4129 #ifdef COMPILER2
4130 
4131 // Compress char[] to byte[] by compressing 16 bytes at once. Return 0 on failure.
4132 void MacroAssembler::string_compress_16(Register src, Register dst, Register cnt, Register result,
4133                                         Register tmp1, Register tmp2, Register tmp3, Register tmp4,
4134                                         FloatRegister ftmp1, FloatRegister ftmp2, FloatRegister ftmp3, Label& Ldone) {
4135   Label Lloop, Lslow;
4136   assert(UseVIS >= 3, "VIS3 is required");
4137   assert_different_registers(src, dst, cnt, tmp1, tmp2, tmp3, tmp4, result);
4138   assert_different_registers(ftmp1, ftmp2, ftmp3);
4139 
4140   // Check if cnt >= 8 (= 16 bytes)
4141   cmp(cnt, 8);
4142   br(Assembler::less, false, Assembler::pn, Lslow);
4143   delayed()->mov(cnt, result); // copy count
4144 
4145   // Check for 8-byte alignment of src and dst
4146   or3(src, dst, tmp1);
4147   andcc(tmp1, 7, G0);
4148   br(Assembler::notZero, false, Assembler::pn, Lslow);
4149   delayed()->nop();
4150 
4151   // Set mask for bshuffle instruction
4152   Register mask = tmp4;
4153   set(0x13579bdf, mask);
4154   bmask(mask, G0, G0);
4155 
4156   // Set mask to 0xff00 ff00 ff00 ff00 to check for non-latin1 characters
4157   Assembler::sethi(0xff00fc00, mask); // mask = 0x0000 0000 ff00 fc00
4158   add(mask, 0x300, mask);             // mask = 0x0000 0000 ff00 ff00
4159   sllx(mask, 32, tmp1);               // tmp1 = 0xff00 ff00 0000 0000
4160   or3(mask, tmp1, mask);              // mask = 0xff00 ff00 ff00 ff00
4161 
4162   // Load first 8 bytes
4163   ldx(src, 0, tmp1);
4164 
4165   bind(Lloop);
4166   // Load next 8 bytes
4167   ldx(src, 8, tmp2);
4168 
4169   // Check for non-latin1 character by testing if the most significant byte of a char is set.
4170   // Although we have to move the data between integer and floating point registers, this is
4171   // still faster than the corresponding VIS instructions (ford/fand/fcmpd).
4172   or3(tmp1, tmp2, tmp3);
4173   btst(tmp3, mask);
4174   // annul zeroing if branch is not taken to preserve original count
4175   brx(Assembler::notZero, true, Assembler::pn, Ldone);
4176   delayed()->mov(G0, result); // 0 - failed
4177 
4178   // Move bytes into float register
4179   movxtod(tmp1, ftmp1);
4180   movxtod(tmp2, ftmp2);
4181 
4182   // Compress by copying one byte per char from ftmp1 and ftmp2 to ftmp3
4183   bshuffle(ftmp1, ftmp2, ftmp3);
4184   stf(FloatRegisterImpl::D, ftmp3, dst, 0);
4185 
4186   // Increment addresses and decrement count
4187   inc(src, 16);
4188   inc(dst, 8);
4189   dec(cnt, 8);
4190 
4191   cmp(cnt, 8);
4192   // annul LDX if branch is not taken to prevent access past end of string
4193   br(Assembler::greaterEqual, true, Assembler::pt, Lloop);
4194   delayed()->ldx(src, 0, tmp1);
4195 
4196   // Fallback to slow version
4197   bind(Lslow);
4198 }
4199 
4200 // Compress char[] to byte[]. Return 0 on failure.
4201 void MacroAssembler::string_compress(Register src, Register dst, Register cnt, Register result, Register tmp, Label& Ldone) {
4202   Label Lloop;
4203   assert_different_registers(src, dst, cnt, tmp, result);
4204 
4205   lduh(src, 0, tmp);
4206 
4207   bind(Lloop);
4208   inc(src, sizeof(jchar));
4209   cmp(tmp, 0xff);
4210   // annul zeroing if branch is not taken to preserve original count
4211   br(Assembler::greater, true, Assembler::pn, Ldone); // don't check xcc
4212   delayed()->mov(G0, result); // 0 - failed
4213   deccc(cnt);
4214   stb(tmp, dst, 0);
4215   inc(dst);
4216   // annul LDUH if branch is not taken to prevent access past end of string
4217   br(Assembler::notZero, true, Assembler::pt, Lloop);
4218   delayed()->lduh(src, 0, tmp); // hoisted
4219 }
4220 
4221 // Inflate byte[] to char[] by inflating 16 bytes at once.
4222 void MacroAssembler::string_inflate_16(Register src, Register dst, Register cnt, Register tmp,
4223                                        FloatRegister ftmp1, FloatRegister ftmp2, FloatRegister ftmp3, FloatRegister ftmp4, Label& Ldone) {
4224   Label Lloop, Lslow;
4225   assert(UseVIS >= 3, "VIS3 is required");
4226   assert_different_registers(src, dst, cnt, tmp);
4227   assert_different_registers(ftmp1, ftmp2, ftmp3, ftmp4);
4228 
4229   // Check if cnt >= 8 (= 16 bytes)
4230   cmp(cnt, 8);
4231   br(Assembler::less, false, Assembler::pn, Lslow);
4232   delayed()->nop();
4233 
4234   // Check for 8-byte alignment of src and dst
4235   or3(src, dst, tmp);
4236   andcc(tmp, 7, G0);
4237   br(Assembler::notZero, false, Assembler::pn, Lslow);
4238   // Initialize float register to zero
4239   FloatRegister zerof = ftmp4;
4240   delayed()->fzero(FloatRegisterImpl::D, zerof);
4241 
4242   // Load first 8 bytes
4243   ldf(FloatRegisterImpl::D, src, 0, ftmp1);
4244 
4245   bind(Lloop);
4246   inc(src, 8);
4247   dec(cnt, 8);
4248 
4249   // Inflate the string by interleaving each byte from the source array
4250   // with a zero byte and storing the result in the destination array.
4251   fpmerge(zerof, ftmp1->successor(), ftmp2);
4252   stf(FloatRegisterImpl::D, ftmp2, dst, 8);
4253   fpmerge(zerof, ftmp1, ftmp3);
4254   stf(FloatRegisterImpl::D, ftmp3, dst, 0);
4255 
4256   inc(dst, 16);
4257 
4258   cmp(cnt, 8);
4259   // annul LDX if branch is not taken to prevent access past end of string
4260   br(Assembler::greaterEqual, true, Assembler::pt, Lloop);
4261   delayed()->ldf(FloatRegisterImpl::D, src, 0, ftmp1);
4262 
4263   // Fallback to slow version
4264   bind(Lslow);
4265 }
4266 
4267 // Inflate byte[] to char[].
4268 void MacroAssembler::string_inflate(Register src, Register dst, Register cnt, Register tmp, Label& Ldone) {
4269   Label Loop;
4270   assert_different_registers(src, dst, cnt, tmp);
4271 
4272   ldub(src, 0, tmp);
4273   bind(Loop);
4274   inc(src);
4275   deccc(cnt);
4276   sth(tmp, dst, 0);
4277   inc(dst, sizeof(jchar));
4278   // annul LDUB if branch is not taken to prevent access past end of string
4279   br(Assembler::notZero, true, Assembler::pt, Loop);
4280   delayed()->ldub(src, 0, tmp); // hoisted
4281 }
4282 
4283 void MacroAssembler::string_compare(Register str1, Register str2,
4284                                     Register cnt1, Register cnt2,
4285                                     Register tmp1, Register tmp2,
4286                                     Register result, int ae) {
4287   Label Ldone, Lloop;
4288   assert_different_registers(str1, str2, cnt1, cnt2, tmp1, result);
4289   int stride1, stride2;
4290 
4291   // Note: Making use of the fact that compareTo(a, b) == -compareTo(b, a)
4292   // we interchange str1 and str2 in the UL case and negate the result.
4293   // Like this, str1 is always latin1 encoded, expect for the UU case.
4294 
4295   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
4296     srl(cnt2, 1, cnt2);
4297   }
4298 
4299   // See if the lengths are different, and calculate min in cnt1.
4300   // Save diff in case we need it for a tie-breaker.
4301   Label Lskip;
4302   Register diff = tmp1;
4303   subcc(cnt1, cnt2, diff);
4304   br(Assembler::greater, true, Assembler::pt, Lskip);
4305   // cnt2 is shorter, so use its count:
4306   delayed()->mov(cnt2, cnt1);
4307   bind(Lskip);
4308 
4309   // Rename registers
4310   Register limit1 = cnt1;
4311   Register limit2 = limit1;
4312   Register chr1   = result;
4313   Register chr2   = cnt2;
4314   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
4315     // We need an additional register to keep track of two limits
4316     assert_different_registers(str1, str2, cnt1, cnt2, tmp1, tmp2, result);
4317     limit2 = tmp2;
4318   }
4319 
4320   // Is the minimum length zero?
4321   cmp(limit1, (int)0); // use cast to resolve overloading ambiguity
4322   br(Assembler::equal, true, Assembler::pn, Ldone);
4323   // result is difference in lengths
4324   if (ae == StrIntrinsicNode::UU) {
4325     delayed()->sra(diff, 1, result);  // Divide by 2 to get number of chars
4326   } else {
4327     delayed()->mov(diff, result);
4328   }
4329 
4330   // Load first characters
4331   if (ae == StrIntrinsicNode::LL) {
4332     stride1 = stride2 = sizeof(jbyte);
4333     ldub(str1, 0, chr1);
4334     ldub(str2, 0, chr2);
4335   } else if (ae == StrIntrinsicNode::UU) {
4336     stride1 = stride2 = sizeof(jchar);
4337     lduh(str1, 0, chr1);
4338     lduh(str2, 0, chr2);
4339   } else {
4340     stride1 = sizeof(jbyte);
4341     stride2 = sizeof(jchar);
4342     ldub(str1, 0, chr1);
4343     lduh(str2, 0, chr2);
4344   }
4345 
4346   // Compare first characters
4347   subcc(chr1, chr2, chr1);
4348   br(Assembler::notZero, false, Assembler::pt, Ldone);
4349   assert(chr1 == result, "result must be pre-placed");
4350   delayed()->nop();
4351 
4352   // Check if the strings start at same location
4353   cmp(str1, str2);
4354   brx(Assembler::equal, true, Assembler::pn, Ldone);
4355   delayed()->mov(G0, result);  // result is zero
4356 
4357   // We have no guarantee that on 64 bit the higher half of limit is 0
4358   signx(limit1);
4359 
4360   // Get limit
4361   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
4362     sll(limit1, 1, limit2);
4363     subcc(limit2, stride2, chr2);
4364   }
4365   subcc(limit1, stride1, chr1);
4366   br(Assembler::zero, true, Assembler::pn, Ldone);
4367   // result is difference in lengths
4368   if (ae == StrIntrinsicNode::UU) {
4369     delayed()->sra(diff, 1, result);  // Divide by 2 to get number of chars
4370   } else {
4371     delayed()->mov(diff, result);
4372   }
4373 
4374   // Shift str1 and str2 to the end of the arrays, negate limit
4375   add(str1, limit1, str1);
4376   add(str2, limit2, str2);
4377   neg(chr1, limit1);  // limit1 = -(limit1-stride1)
4378   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
4379     neg(chr2, limit2);  // limit2 = -(limit2-stride2)
4380   }
4381 
4382   // Compare the rest of the characters
4383   load_sized_value(Address(str1, limit1), chr1, (ae == StrIntrinsicNode::UU) ? 2 : 1, false);
4384 
4385   bind(Lloop);
4386   load_sized_value(Address(str2, limit2), chr2, (ae == StrIntrinsicNode::LL) ? 1 : 2, false);
4387 
4388   subcc(chr1, chr2, chr1);
4389   br(Assembler::notZero, false, Assembler::pt, Ldone);
4390   assert(chr1 == result, "result must be pre-placed");
4391   delayed()->inccc(limit1, stride1);
4392   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
4393     inccc(limit2, stride2);
4394   }
4395 
4396   // annul LDUB if branch is not taken to prevent access past end of string
4397   br(Assembler::notZero, true, Assembler::pt, Lloop);
4398   delayed()->load_sized_value(Address(str1, limit1), chr1, (ae == StrIntrinsicNode::UU) ? 2 : 1, false);
4399 
4400   // If strings are equal up to min length, return the length difference.
4401   if (ae == StrIntrinsicNode::UU) {
4402     // Divide by 2 to get number of chars
4403     sra(diff, 1, result);
4404   } else {
4405     mov(diff, result);
4406   }
4407 
4408   // Otherwise, return the difference between the first mismatched chars.
4409   bind(Ldone);
4410   if(ae == StrIntrinsicNode::UL) {
4411     // Negate result (see note above)
4412     neg(result);
4413   }
4414 }
4415 
4416 void MacroAssembler::array_equals(bool is_array_equ, Register ary1, Register ary2,
4417                                   Register limit, Register tmp, Register result, bool is_byte) {
4418   Label Ldone, Lloop, Lremaining;
4419   assert_different_registers(ary1, ary2, limit, tmp, result);
4420 
4421   int length_offset  = arrayOopDesc::length_offset_in_bytes();
4422   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_byte ? T_BYTE : T_CHAR);
4423   assert(base_offset % 8 == 0, "Base offset must be 8-byte aligned");
4424 
4425   if (is_array_equ) {
4426     // return true if the same array
4427     cmp(ary1, ary2);
4428     brx(Assembler::equal, true, Assembler::pn, Ldone);
4429     delayed()->mov(1, result);  // equal
4430 
4431     br_null(ary1, true, Assembler::pn, Ldone);
4432     delayed()->clr(result);     // not equal
4433 
4434     br_null(ary2, true, Assembler::pn, Ldone);
4435     delayed()->clr(result);     // not equal
4436 
4437     // load the lengths of arrays
4438     ld(Address(ary1, length_offset), limit);
4439     ld(Address(ary2, length_offset), tmp);
4440 
4441     // return false if the two arrays are not equal length
4442     cmp(limit, tmp);
4443     br(Assembler::notEqual, true, Assembler::pn, Ldone);
4444     delayed()->clr(result);     // not equal
4445   }
4446 
4447   cmp_zero_and_br(Assembler::zero, limit, Ldone, true, Assembler::pn);
4448   delayed()->mov(1, result); // zero-length arrays are equal
4449 
4450   if (is_array_equ) {
4451     // load array addresses
4452     add(ary1, base_offset, ary1);
4453     add(ary2, base_offset, ary2);
4454     // set byte count
4455     if (!is_byte) {
4456       sll(limit, exact_log2(sizeof(jchar)), limit);
4457     }
4458   } else {
4459     // We have no guarantee that on 64 bit the higher half of limit is 0
4460     signx(limit);
4461   }
4462 
4463 #ifdef ASSERT
4464   // Sanity check for doubleword (8-byte) alignment of ary1 and ary2.
4465   // Guaranteed on 64-bit systems (see arrayOopDesc::header_size_in_bytes()).
4466   Label Laligned;
4467   or3(ary1, ary2, tmp);
4468   andcc(tmp, 7, tmp);
4469   br_null_short(tmp, Assembler::pn, Laligned);
4470   STOP("First array element is not 8-byte aligned.");
4471   should_not_reach_here();
4472   bind(Laligned);
4473 #endif
4474 
4475   // Shift ary1 and ary2 to the end of the arrays, negate limit
4476   add(ary1, limit, ary1);
4477   add(ary2, limit, ary2);
4478   neg(limit, limit);
4479 
4480   // MAIN LOOP
4481   // Load and compare array elements of size 'byte_width' until the elements are not
4482   // equal or we reached the end of the arrays. If the size of the arrays is not a
4483   // multiple of 'byte_width', we simply read over the end of the array, bail out and
4484   // compare the remaining bytes below by skipping the garbage bytes.
4485   ldx(ary1, limit, result);
4486   bind(Lloop);
4487   ldx(ary2, limit, tmp);
4488   inccc(limit, 8);
4489   // Bail out if we reached the end (but still do the comparison)
4490   br(Assembler::positive, false, Assembler::pn, Lremaining);
4491   delayed()->cmp(result, tmp);
4492   // Check equality of elements
4493   brx(Assembler::equal, false, Assembler::pt, target(Lloop));
4494   delayed()->ldx(ary1, limit, result);
4495 
4496   ba(Ldone);
4497   delayed()->clr(result); // not equal
4498 
4499   // TAIL COMPARISON
4500   // We got here because we reached the end of the arrays. 'limit' is the number of
4501   // garbage bytes we may have compared by reading over the end of the arrays. Shift
4502   // out the garbage and compare the remaining elements.
4503   bind(Lremaining);
4504   // Optimistic shortcut: elements potentially including garbage are equal
4505   brx(Assembler::equal, true, Assembler::pt, target(Ldone));
4506   delayed()->mov(1, result); // equal
4507   // Shift 'limit' bytes to the right and compare
4508   sll(limit, 3, limit); // bytes to bits
4509   srlx(result, limit, result);
4510   srlx(tmp, limit, tmp);
4511   cmp(result, tmp);
4512   clr(result);
4513   movcc(Assembler::equal, false, xcc, 1, result);
4514 
4515   bind(Ldone);
4516 }
4517 
4518 void MacroAssembler::has_negatives(Register inp, Register size, Register result, Register t2, Register t3, Register t4, Register t5) {
4519 
4520   // test for negative bytes in input string of a given size
4521   // result 1 if found, 0 otherwise.
4522 
4523   Label Lcore, Ltail, Lreturn, Lcore_rpt;
4524 
4525   assert_different_registers(inp, size, t2, t3, t4, t5, result);
4526 
4527   Register i     = result;  // result used as integer index i until very end
4528   Register lmask = t2;      // t2 is aliased to lmask
4529 
4530   // INITIALIZATION
4531   // ===========================================================
4532   // initialize highbits mask -> lmask = 0x8080808080808080  (8B/64b)
4533   // compute unaligned offset -> i
4534   // compute core end index   -> t5
4535   Assembler::sethi(0x80808000, t2);   //! sethi macro fails to emit optimal
4536   add(t2, 0x80, t2);
4537   sllx(t2, 32, t3);
4538   or3(t3, t2, lmask);                 // 0x8080808080808080 -> lmask
4539   sra(size,0,size);
4540   andcc(inp, 0x7, i);                 // unaligned offset -> i
4541   br(Assembler::zero, true, Assembler::pn, Lcore); // starts 8B aligned?
4542   delayed()->add(size, -8, t5);       // (annuled) core end index -> t5
4543 
4544   // ===========================================================
4545 
4546   // UNALIGNED HEAD
4547   // ===========================================================
4548   // * unaligned head handling: grab aligned 8B containing unaligned inp(ut)
4549   // * obliterate (ignore) bytes outside string by shifting off reg ends
4550   // * compare with bitmask, short circuit return true if one or more high
4551   //   bits set.
4552   cmp(size, 0);
4553   br(Assembler::zero, true, Assembler::pn, Lreturn); // short-circuit?
4554   delayed()->mov(0,result);      // annuled so i not clobbered for following
4555   neg(i, t4);
4556   add(i, size, t5);
4557   ldx(inp, t4, t3);  // raw aligned 8B containing unaligned head -> t3
4558   mov(8, t4);
4559   sub(t4, t5, t4);
4560   sra(t4, 31, t5);
4561   andn(t4, t5, t5);
4562   add(i, t5, t4);
4563   sll(t5, 3, t5);
4564   sll(t4, 3, t4);   // # bits to shift right, left -> t5,t4
4565   srlx(t3, t5, t3);
4566   sllx(t3, t4, t3); // bytes outside string in 8B header obliterated -> t3
4567   andcc(lmask, t3, G0);
4568   brx(Assembler::notZero, true, Assembler::pn, Lreturn); // short circuit?
4569   delayed()->mov(1,result);      // annuled so i not clobbered for following
4570   add(size, -8, t5);             // core end index -> t5
4571   mov(8, t4);
4572   sub(t4, i, i);                 // # bytes examined in unalgn head (<8) -> i
4573   // ===========================================================
4574 
4575   // ALIGNED CORE
4576   // ===========================================================
4577   // * iterate index i over aligned 8B sections of core, comparing with
4578   //   bitmask, short circuit return true if one or more high bits set
4579   // t5 contains core end index/loop limit which is the index
4580   //     of the MSB of last (unaligned) 8B fully contained in the string.
4581   // inp   contains address of first byte in string/array
4582   // lmask contains 8B high bit mask for comparison
4583   // i     contains next index to be processed (adr. inp+i is on 8B boundary)
4584   bind(Lcore);
4585   cmp_and_br_short(i, t5, Assembler::greater, Assembler::pn, Ltail);
4586   bind(Lcore_rpt);
4587   ldx(inp, i, t3);
4588   andcc(t3, lmask, G0);
4589   brx(Assembler::notZero, true, Assembler::pn, Lreturn);
4590   delayed()->mov(1, result);    // annuled so i not clobbered for following
4591   add(i, 8, i);
4592   cmp_and_br_short(i, t5, Assembler::lessEqual, Assembler::pn, Lcore_rpt);
4593   // ===========================================================
4594 
4595   // ALIGNED TAIL (<8B)
4596   // ===========================================================
4597   // handle aligned tail of 7B or less as complete 8B, obliterating end of
4598   // string bytes by shifting them off end, compare what's left with bitmask
4599   // inp   contains address of first byte in string/array
4600   // lmask contains 8B high bit mask for comparison
4601   // i     contains next index to be processed (adr. inp+i is on 8B boundary)
4602   bind(Ltail);
4603   subcc(size, i, t4);   // # of remaining bytes in string -> t4
4604   // return 0 if no more remaining bytes
4605   br(Assembler::lessEqual, true, Assembler::pn, Lreturn);
4606   delayed()->mov(0, result); // annuled so i not clobbered for following
4607   ldx(inp, i, t3);       // load final 8B (aligned) containing tail -> t3
4608   mov(8, t5);
4609   sub(t5, t4, t4);
4610   mov(0, result);        // ** i clobbered at this point
4611   sll(t4, 3, t4);        // bits beyond end of string          -> t4
4612   srlx(t3, t4, t3);      // bytes beyond end now obliterated   -> t3
4613   andcc(lmask, t3, G0);
4614   movcc(Assembler::notZero, false, xcc,  1, result);
4615   bind(Lreturn);
4616 }
4617 
4618 #endif
4619 
4620 
4621 // Use BIS for zeroing (count is in bytes).
4622 void MacroAssembler::bis_zeroing(Register to, Register count, Register temp, Label& Ldone) {
4623   assert(UseBlockZeroing && VM_Version::has_blk_zeroing(), "only works with BIS zeroing");
4624   Register end = count;
4625   int cache_line_size = VM_Version::prefetch_data_size();
4626   assert(cache_line_size > 0, "cache line size should be known for this code");
4627   // Minimum count when BIS zeroing can be used since
4628   // it needs membar which is expensive.
4629   int block_zero_size  = MAX2(cache_line_size*3, (int)BlockZeroingLowLimit);
4630 
4631   Label small_loop;
4632   // Check if count is negative (dead code) or zero.
4633   // Note, count uses 64bit in 64 bit VM.
4634   cmp_and_brx_short(count, 0, Assembler::lessEqual, Assembler::pn, Ldone);
4635 
4636   // Use BIS zeroing only for big arrays since it requires membar.
4637   if (Assembler::is_simm13(block_zero_size)) { // < 4096
4638     cmp(count, block_zero_size);
4639   } else {
4640     set(block_zero_size, temp);
4641     cmp(count, temp);
4642   }
4643   br(Assembler::lessUnsigned, false, Assembler::pt, small_loop);
4644   delayed()->add(to, count, end);
4645 
4646   // Note: size is >= three (32 bytes) cache lines.
4647 
4648   // Clean the beginning of space up to next cache line.
4649   for (int offs = 0; offs < cache_line_size; offs += 8) {
4650     stx(G0, to, offs);
4651   }
4652 
4653   // align to next cache line
4654   add(to, cache_line_size, to);
4655   and3(to, -cache_line_size, to);
4656 
4657   // Note: size left >= two (32 bytes) cache lines.
4658 
4659   // BIS should not be used to zero tail (64 bytes)
4660   // to avoid zeroing a header of the following object.
4661   sub(end, (cache_line_size*2)-8, end);
4662 
4663   Label bis_loop;
4664   bind(bis_loop);
4665   stxa(G0, to, G0, Assembler::ASI_ST_BLKINIT_PRIMARY);
4666   add(to, cache_line_size, to);
4667   cmp_and_brx_short(to, end, Assembler::lessUnsigned, Assembler::pt, bis_loop);
4668 
4669   // BIS needs membar.
4670   membar(Assembler::StoreLoad);
4671 
4672   add(end, (cache_line_size*2)-8, end); // restore end
4673   cmp_and_brx_short(to, end, Assembler::greaterEqualUnsigned, Assembler::pn, Ldone);
4674 
4675   // Clean the tail.
4676   bind(small_loop);
4677   stx(G0, to, 0);
4678   add(to, 8, to);
4679   cmp_and_brx_short(to, end, Assembler::lessUnsigned, Assembler::pt, small_loop);
4680   nop(); // Separate short branches
4681 }
4682 
4683 /**
4684  * Update CRC-32[C] with a byte value according to constants in table
4685  *
4686  * @param [in,out]crc   Register containing the crc.
4687  * @param [in]val       Register containing the byte to fold into the CRC.
4688  * @param [in]table     Register containing the table of crc constants.
4689  *
4690  * uint32_t crc;
4691  * val = crc_table[(val ^ crc) & 0xFF];
4692  * crc = val ^ (crc >> 8);
4693  */
4694 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
4695   xor3(val, crc, val);
4696   and3(val, 0xFF, val);
4697   sllx(val, 2, val);
4698   lduw(table, val, val);
4699   srlx(crc, 8, crc);
4700   xor3(val, crc, crc);
4701 }
4702 
4703 // Reverse byte order of lower 32 bits, assuming upper 32 bits all zeros
4704 void MacroAssembler::reverse_bytes_32(Register src, Register dst, Register tmp) {
4705     srlx(src, 24, dst);
4706 
4707     sllx(src, 32+8, tmp);
4708     srlx(tmp, 32+24, tmp);
4709     sllx(tmp, 8, tmp);
4710     or3(dst, tmp, dst);
4711 
4712     sllx(src, 32+16, tmp);
4713     srlx(tmp, 32+24, tmp);
4714     sllx(tmp, 16, tmp);
4715     or3(dst, tmp, dst);
4716 
4717     sllx(src, 32+24, tmp);
4718     srlx(tmp, 32, tmp);
4719     or3(dst, tmp, dst);
4720 }
4721 
4722 void MacroAssembler::movitof_revbytes(Register src, FloatRegister dst, Register tmp1, Register tmp2) {
4723   reverse_bytes_32(src, tmp1, tmp2);
4724   movxtod(tmp1, dst);
4725 }
4726 
4727 void MacroAssembler::movftoi_revbytes(FloatRegister src, Register dst, Register tmp1, Register tmp2) {
4728   movdtox(src, tmp1);
4729   reverse_bytes_32(tmp1, dst, tmp2);
4730 }
4731 
4732 void MacroAssembler::fold_128bit_crc32(Register xcrc_hi, Register xcrc_lo, Register xK_hi, Register xK_lo, Register xtmp_hi, Register xtmp_lo, Register buf, int offset) {
4733   xmulx(xcrc_hi, xK_hi, xtmp_lo);
4734   xmulxhi(xcrc_hi, xK_hi, xtmp_hi);
4735   xmulxhi(xcrc_lo, xK_lo, xcrc_hi);
4736   xmulx(xcrc_lo, xK_lo, xcrc_lo);
4737   xor3(xcrc_lo, xtmp_lo, xcrc_lo);
4738   xor3(xcrc_hi, xtmp_hi, xcrc_hi);
4739   ldxl(buf, G0, xtmp_lo);
4740   inc(buf, 8);
4741   ldxl(buf, G0, xtmp_hi);
4742   inc(buf, 8);
4743   xor3(xcrc_lo, xtmp_lo, xcrc_lo);
4744   xor3(xcrc_hi, xtmp_hi, xcrc_hi);
4745 }
4746 
4747 void MacroAssembler::fold_128bit_crc32(Register xcrc_hi, Register xcrc_lo, Register xK_hi, Register xK_lo, Register xtmp_hi, Register xtmp_lo, Register xbuf_hi, Register xbuf_lo) {
4748   mov(xcrc_lo, xtmp_lo);
4749   mov(xcrc_hi, xtmp_hi);
4750   xmulx(xtmp_hi, xK_hi, xtmp_lo);
4751   xmulxhi(xtmp_hi, xK_hi, xtmp_hi);
4752   xmulxhi(xcrc_lo, xK_lo, xcrc_hi);
4753   xmulx(xcrc_lo, xK_lo, xcrc_lo);
4754   xor3(xcrc_lo, xbuf_lo, xcrc_lo);
4755   xor3(xcrc_hi, xbuf_hi, xcrc_hi);
4756   xor3(xcrc_lo, xtmp_lo, xcrc_lo);
4757   xor3(xcrc_hi, xtmp_hi, xcrc_hi);
4758 }
4759 
4760 void MacroAssembler::fold_8bit_crc32(Register xcrc, Register table, Register xtmp, Register tmp) {
4761   and3(xcrc, 0xFF, tmp);
4762   sllx(tmp, 2, tmp);
4763   lduw(table, tmp, xtmp);
4764   srlx(xcrc, 8, xcrc);
4765   xor3(xtmp, xcrc, xcrc);
4766 }
4767 
4768 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
4769   and3(crc, 0xFF, tmp);
4770   srlx(crc, 8, crc);
4771   sllx(tmp, 2, tmp);
4772   lduw(table, tmp, tmp);
4773   xor3(tmp, crc, crc);
4774 }
4775 
4776 #define CRC32_TMP_REG_NUM 18
4777 
4778 #define CRC32_CONST_64  0x163cd6124
4779 #define CRC32_CONST_96  0x0ccaa009e
4780 #define CRC32_CONST_160 0x1751997d0
4781 #define CRC32_CONST_480 0x1c6e41596
4782 #define CRC32_CONST_544 0x154442bd4
4783 
4784 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table) {
4785 
4786   Label L_cleanup_loop, L_cleanup_check, L_align_loop, L_align_check;
4787   Label L_main_loop_prologue;
4788   Label L_fold_512b, L_fold_512b_loop, L_fold_128b;
4789   Label L_fold_tail, L_fold_tail_loop;
4790   Label L_8byte_fold_loop, L_8byte_fold_check;
4791 
4792   const Register tmp[CRC32_TMP_REG_NUM] = {L0, L1, L2, L3, L4, L5, L6, G1, I0, I1, I2, I3, I4, I5, I7, O4, O5, G3};
4793 
4794   Register const_64  = tmp[CRC32_TMP_REG_NUM-1];
4795   Register const_96  = tmp[CRC32_TMP_REG_NUM-1];
4796   Register const_160 = tmp[CRC32_TMP_REG_NUM-2];
4797   Register const_480 = tmp[CRC32_TMP_REG_NUM-1];
4798   Register const_544 = tmp[CRC32_TMP_REG_NUM-2];
4799 
4800   set(ExternalAddress(StubRoutines::crc_table_addr()), table);
4801 
4802   not1(crc); // ~c
4803   clruwu(crc); // clear upper 32 bits of crc
4804 
4805   // Check if below cutoff, proceed directly to cleanup code
4806   mov(31, G4);
4807   cmp_and_br_short(len, G4, Assembler::lessEqualUnsigned, Assembler::pt, L_cleanup_check);
4808 
4809   // Align buffer to 8 byte boundry
4810   mov(8, O5);
4811   and3(buf, 0x7, O4);
4812   sub(O5, O4, O5);
4813   and3(O5, 0x7, O5);
4814   sub(len, O5, len);
4815   ba(L_align_check);
4816   delayed()->nop();
4817 
4818   // Alignment loop, table look up method for up to 7 bytes
4819   bind(L_align_loop);
4820   ldub(buf, 0, O4);
4821   inc(buf);
4822   dec(O5);
4823   xor3(O4, crc, O4);
4824   and3(O4, 0xFF, O4);
4825   sllx(O4, 2, O4);
4826   lduw(table, O4, O4);
4827   srlx(crc, 8, crc);
4828   xor3(O4, crc, crc);
4829   bind(L_align_check);
4830   nop();
4831   cmp_and_br_short(O5, 0, Assembler::notEqual, Assembler::pt, L_align_loop);
4832 
4833   // Aligned on 64-bit (8-byte) boundry at this point
4834   // Check if still above cutoff (31-bytes)
4835   mov(31, G4);
4836   cmp_and_br_short(len, G4, Assembler::lessEqualUnsigned, Assembler::pt, L_cleanup_check);
4837   // At least 32 bytes left to process
4838 
4839   // Free up registers by storing them to FP registers
4840   for (int i = 0; i < CRC32_TMP_REG_NUM; i++) {
4841     movxtod(tmp[i], as_FloatRegister(2*i));
4842   }
4843 
4844   // Determine which loop to enter
4845   // Shared prologue
4846   ldxl(buf, G0, tmp[0]);
4847   inc(buf, 8);
4848   ldxl(buf, G0, tmp[1]);
4849   inc(buf, 8);
4850   xor3(tmp[0], crc, tmp[0]); // Fold CRC into first few bytes
4851   and3(crc, 0, crc); // Clear out the crc register
4852   // Main loop needs 128-bytes at least
4853   mov(128, G4);
4854   mov(64, tmp[2]);
4855   cmp_and_br_short(len, G4, Assembler::greaterEqualUnsigned, Assembler::pt, L_main_loop_prologue);
4856   // Less than 64 bytes
4857   nop();
4858   cmp_and_br_short(len, tmp[2], Assembler::lessUnsigned, Assembler::pt, L_fold_tail);
4859   // Between 64 and 127 bytes
4860   set64(CRC32_CONST_96,  const_96,  tmp[8]);
4861   set64(CRC32_CONST_160, const_160, tmp[9]);
4862   fold_128bit_crc32(tmp[1], tmp[0], const_96, const_160, tmp[2], tmp[3], buf, 0);
4863   fold_128bit_crc32(tmp[1], tmp[0], const_96, const_160, tmp[4], tmp[5], buf, 16);
4864   fold_128bit_crc32(tmp[1], tmp[0], const_96, const_160, tmp[6], tmp[7], buf, 32);
4865   dec(len, 48);
4866   ba(L_fold_tail);
4867   delayed()->nop();
4868 
4869   bind(L_main_loop_prologue);
4870   for (int i = 2; i < 8; i++) {
4871     ldxl(buf, G0, tmp[i]);
4872     inc(buf, 8);
4873   }
4874 
4875   // Fold total 512 bits of polynomial on each iteration,
4876   // 128 bits per each of 4 parallel streams
4877   set64(CRC32_CONST_480, const_480, tmp[8]);
4878   set64(CRC32_CONST_544, const_544, tmp[9]);
4879 
4880   mov(128, G4);
4881   bind(L_fold_512b_loop);
4882   fold_128bit_crc32(tmp[1], tmp[0], const_480, const_544, tmp[9],  tmp[8],  buf,  0);
4883   fold_128bit_crc32(tmp[3], tmp[2], const_480, const_544, tmp[11], tmp[10], buf, 16);
4884   fold_128bit_crc32(tmp[5], tmp[4], const_480, const_544, tmp[13], tmp[12], buf, 32);
4885   fold_128bit_crc32(tmp[7], tmp[6], const_480, const_544, tmp[15], tmp[14], buf, 64);
4886   dec(len, 64);
4887   cmp_and_br_short(len, G4, Assembler::greaterEqualUnsigned, Assembler::pt, L_fold_512b_loop);
4888 
4889   // Fold 512 bits to 128 bits
4890   bind(L_fold_512b);
4891   set64(CRC32_CONST_96,  const_96,  tmp[8]);
4892   set64(CRC32_CONST_160, const_160, tmp[9]);
4893 
4894   fold_128bit_crc32(tmp[1], tmp[0], const_96, const_160, tmp[8], tmp[9], tmp[3], tmp[2]);
4895   fold_128bit_crc32(tmp[1], tmp[0], const_96, const_160, tmp[8], tmp[9], tmp[5], tmp[4]);
4896   fold_128bit_crc32(tmp[1], tmp[0], const_96, const_160, tmp[8], tmp[9], tmp[7], tmp[6]);
4897   dec(len, 48);
4898 
4899   // Fold the rest of 128 bits data chunks
4900   bind(L_fold_tail);
4901   mov(32, G4);
4902   cmp_and_br_short(len, G4, Assembler::lessEqualUnsigned, Assembler::pt, L_fold_128b);
4903 
4904   set64(CRC32_CONST_96,  const_96,  tmp[8]);
4905   set64(CRC32_CONST_160, const_160, tmp[9]);
4906 
4907   bind(L_fold_tail_loop);
4908   fold_128bit_crc32(tmp[1], tmp[0], const_96, const_160, tmp[2], tmp[3], buf, 0);
4909   sub(len, 16, len);
4910   cmp_and_br_short(len, G4, Assembler::greaterEqualUnsigned, Assembler::pt, L_fold_tail_loop);
4911 
4912   // Fold the 128 bits in tmps 0 - 1 into tmp 1
4913   bind(L_fold_128b);
4914 
4915   set64(CRC32_CONST_64, const_64, tmp[4]);
4916 
4917   xmulx(const_64, tmp[0], tmp[2]);
4918   xmulxhi(const_64, tmp[0], tmp[3]);
4919 
4920   srl(tmp[2], G0, tmp[4]);
4921   xmulx(const_64, tmp[4], tmp[4]);
4922 
4923   srlx(tmp[2], 32, tmp[2]);
4924   sllx(tmp[3], 32, tmp[3]);
4925   or3(tmp[2], tmp[3], tmp[2]);
4926 
4927   xor3(tmp[4], tmp[1], tmp[4]);
4928   xor3(tmp[4], tmp[2], tmp[1]);
4929   dec(len, 8);
4930 
4931   // Use table lookup for the 8 bytes left in tmp[1]
4932   dec(len, 8);
4933 
4934   // 8 8-bit folds to compute 32-bit CRC.
4935   for (int j = 0; j < 4; j++) {
4936     fold_8bit_crc32(tmp[1], table, tmp[2], tmp[3]);
4937   }
4938   srl(tmp[1], G0, crc); // move 32 bits to general register
4939   for (int j = 0; j < 4; j++) {
4940     fold_8bit_crc32(crc, table, tmp[3]);
4941   }
4942 
4943   bind(L_8byte_fold_check);
4944 
4945   // Restore int registers saved in FP registers
4946   for (int i = 0; i < CRC32_TMP_REG_NUM; i++) {
4947     movdtox(as_FloatRegister(2*i), tmp[i]);
4948   }
4949 
4950   ba(L_cleanup_check);
4951   delayed()->nop();
4952 
4953   // Table look-up method for the remaining few bytes
4954   bind(L_cleanup_loop);
4955   ldub(buf, 0, O4);
4956   inc(buf);
4957   dec(len);
4958   xor3(O4, crc, O4);
4959   and3(O4, 0xFF, O4);
4960   sllx(O4, 2, O4);
4961   lduw(table, O4, O4);
4962   srlx(crc, 8, crc);
4963   xor3(O4, crc, crc);
4964   bind(L_cleanup_check);
4965   nop();
4966   cmp_and_br_short(len, 0, Assembler::greaterUnsigned, Assembler::pt, L_cleanup_loop);
4967 
4968   not1(crc);
4969 }
4970 
4971 #define CHUNK_LEN   128          /* 128 x 8B = 1KB */
4972 #define CHUNK_K1    0x1307a0206  /* reverseBits(pow(x, CHUNK_LEN*8*8*3 - 32) mod P(x)) << 1 */
4973 #define CHUNK_K2    0x1a0f717c4  /* reverseBits(pow(x, CHUNK_LEN*8*8*2 - 32) mod P(x)) << 1 */
4974 #define CHUNK_K3    0x0170076fa  /* reverseBits(pow(x, CHUNK_LEN*8*8*1 - 32) mod P(x)) << 1 */
4975 
4976 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len, Register table) {
4977 
4978   Label L_crc32c_head, L_crc32c_aligned;
4979   Label L_crc32c_parallel, L_crc32c_parallel_loop;
4980   Label L_crc32c_serial, L_crc32c_x32_loop, L_crc32c_x8, L_crc32c_x8_loop;
4981   Label L_crc32c_done, L_crc32c_tail, L_crc32c_return;
4982 
4983   set(ExternalAddress(StubRoutines::crc32c_table_addr()), table);
4984 
4985   cmp_and_br_short(len, 0, Assembler::lessEqual, Assembler::pn, L_crc32c_return);
4986 
4987   // clear upper 32 bits of crc
4988   clruwu(crc);
4989 
4990   and3(buf, 7, G4);
4991   cmp_and_brx_short(G4, 0, Assembler::equal, Assembler::pt, L_crc32c_aligned);
4992 
4993   mov(8, G1);
4994   sub(G1, G4, G4);
4995 
4996   // ------ process the misaligned head (7 bytes or less) ------
4997   bind(L_crc32c_head);
4998 
4999   // crc = (crc >>> 8) ^ byteTable[(crc ^ b) & 0xFF];
5000   ldub(buf, 0, G1);
5001   update_byte_crc32(crc, G1, table);
5002 
5003   inc(buf);
5004   dec(len);
5005   cmp_and_br_short(len, 0, Assembler::equal, Assembler::pn, L_crc32c_return);
5006   dec(G4);
5007   cmp_and_br_short(G4, 0, Assembler::greater, Assembler::pt, L_crc32c_head);
5008 
5009   // ------ process the 8-byte-aligned body ------
5010   bind(L_crc32c_aligned);
5011   nop();
5012   cmp_and_br_short(len, 8, Assembler::less, Assembler::pn, L_crc32c_tail);
5013 
5014   // reverse the byte order of lower 32 bits to big endian, and move to FP side
5015   movitof_revbytes(crc, F0, G1, G3);
5016 
5017   set(CHUNK_LEN*8*4, G4);
5018   cmp_and_br_short(len, G4, Assembler::less, Assembler::pt, L_crc32c_serial);
5019 
5020   // ------ process four 1KB chunks in parallel ------
5021   bind(L_crc32c_parallel);
5022 
5023   fzero(FloatRegisterImpl::D, F2);
5024   fzero(FloatRegisterImpl::D, F4);
5025   fzero(FloatRegisterImpl::D, F6);
5026 
5027   mov(CHUNK_LEN - 1, G4);
5028   bind(L_crc32c_parallel_loop);
5029   // schedule ldf's ahead of crc32c's to hide the load-use latency
5030   ldf(FloatRegisterImpl::D, buf, 0,            F8);
5031   ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*8,  F10);
5032   ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*16, F12);
5033   ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*24, F14);
5034   crc32c(F0, F8,  F0);
5035   crc32c(F2, F10, F2);
5036   crc32c(F4, F12, F4);
5037   crc32c(F6, F14, F6);
5038   inc(buf, 8);
5039   dec(G4);
5040   cmp_and_br_short(G4, 0, Assembler::greater, Assembler::pt, L_crc32c_parallel_loop);
5041 
5042   ldf(FloatRegisterImpl::D, buf, 0,            F8);
5043   ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*8,  F10);
5044   ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*16, F12);
5045   crc32c(F0, F8,  F0);
5046   crc32c(F2, F10, F2);
5047   crc32c(F4, F12, F4);
5048 
5049   inc(buf, CHUNK_LEN*24);
5050   ldfl(FloatRegisterImpl::D, buf, G0, F14);  // load in little endian
5051   inc(buf, 8);
5052 
5053   prefetch(buf, 0,            Assembler::severalReads);
5054   prefetch(buf, CHUNK_LEN*8,  Assembler::severalReads);
5055   prefetch(buf, CHUNK_LEN*16, Assembler::severalReads);
5056   prefetch(buf, CHUNK_LEN*24, Assembler::severalReads);
5057 
5058   // move to INT side, and reverse the byte order of lower 32 bits to little endian
5059   movftoi_revbytes(F0, O4, G1, G4);
5060   movftoi_revbytes(F2, O5, G1, G4);
5061   movftoi_revbytes(F4, G5, G1, G4);
5062 
5063   // combine the results of 4 chunks
5064   set64(CHUNK_K1, G3, G1);
5065   xmulx(O4, G3, O4);
5066   set64(CHUNK_K2, G3, G1);
5067   xmulx(O5, G3, O5);
5068   set64(CHUNK_K3, G3, G1);
5069   xmulx(G5, G3, G5);
5070 
5071   movdtox(F14, G4);
5072   xor3(O4, O5, O5);
5073   xor3(G5, O5, O5);
5074   xor3(G4, O5, O5);
5075 
5076   // reverse the byte order to big endian, via stack, and move to FP side
5077   // TODO: use new revb instruction
5078   add(SP, -8, G1);
5079   srlx(G1, 3, G1);
5080   sllx(G1, 3, G1);
5081   stx(O5, G1, G0);
5082   ldfl(FloatRegisterImpl::D, G1, G0, F2);  // load in little endian
5083 
5084   crc32c(F6, F2, F0);
5085 
5086   set(CHUNK_LEN*8*4, G4);
5087   sub(len, G4, len);
5088   cmp_and_br_short(len, G4, Assembler::greaterEqual, Assembler::pt, L_crc32c_parallel);
5089   nop();
5090   cmp_and_br_short(len, 0, Assembler::equal, Assembler::pt, L_crc32c_done);
5091 
5092   bind(L_crc32c_serial);
5093 
5094   mov(32, G4);
5095   cmp_and_br_short(len, G4, Assembler::less, Assembler::pn, L_crc32c_x8);
5096 
5097   // ------ process 32B chunks ------
5098   bind(L_crc32c_x32_loop);
5099   ldf(FloatRegisterImpl::D, buf, 0, F2);
5100   crc32c(F0, F2, F0);
5101   ldf(FloatRegisterImpl::D, buf, 8, F2);
5102   crc32c(F0, F2, F0);
5103   ldf(FloatRegisterImpl::D, buf, 16, F2);
5104   crc32c(F0, F2, F0);
5105   ldf(FloatRegisterImpl::D, buf, 24, F2);
5106   inc(buf, 32);
5107   crc32c(F0, F2, F0);
5108   dec(len, 32);
5109   cmp_and_br_short(len, G4, Assembler::greaterEqual, Assembler::pt, L_crc32c_x32_loop);
5110 
5111   bind(L_crc32c_x8);
5112   nop();
5113   cmp_and_br_short(len, 8, Assembler::less, Assembler::pt, L_crc32c_done);
5114 
5115   // ------ process 8B chunks ------
5116   bind(L_crc32c_x8_loop);
5117   ldf(FloatRegisterImpl::D, buf, 0, F2);
5118   inc(buf, 8);
5119   crc32c(F0, F2, F0);
5120   dec(len, 8);
5121   cmp_and_br_short(len, 8, Assembler::greaterEqual, Assembler::pt, L_crc32c_x8_loop);
5122 
5123   bind(L_crc32c_done);
5124 
5125   // move to INT side, and reverse the byte order of lower 32 bits to little endian
5126   movftoi_revbytes(F0, crc, G1, G3);
5127 
5128   cmp_and_br_short(len, 0, Assembler::equal, Assembler::pt, L_crc32c_return);
5129 
5130   // ------ process the misaligned tail (7 bytes or less) ------
5131   bind(L_crc32c_tail);
5132 
5133   // crc = (crc >>> 8) ^ byteTable[(crc ^ b) & 0xFF];
5134   ldub(buf, 0, G1);
5135   update_byte_crc32(crc, G1, table);
5136 
5137   inc(buf);
5138   dec(len);
5139   cmp_and_br_short(len, 0, Assembler::greater, Assembler::pt, L_crc32c_tail);
5140 
5141   bind(L_crc32c_return);
5142   nop();
5143 }