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