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