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