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