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