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