1 /*
   2  * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright 2012, 2014 SAP AG. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "asm/macroAssembler.inline.hpp"
  28 #include "compiler/disassembler.hpp"
  29 #include "gc_interface/collectedHeap.inline.hpp"
  30 #include "interpreter/interpreter.hpp"
  31 #include "memory/cardTableModRefBS.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "prims/methodHandles.hpp"
  34 #include "runtime/biasedLocking.hpp"
  35 #include "runtime/interfaceSupport.hpp"
  36 #include "runtime/objectMonitor.hpp"
  37 #include "runtime/os.hpp"
  38 #include "runtime/sharedRuntime.hpp"
  39 #include "runtime/stubRoutines.hpp"
  40 #include "utilities/macros.hpp"
  41 #if INCLUDE_ALL_GCS
  42 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
  43 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
  44 #include "gc_implementation/g1/heapRegion.hpp"
  45 #endif // INCLUDE_ALL_GCS
  46 
  47 #ifdef PRODUCT
  48 #define BLOCK_COMMENT(str) // nothing
  49 #else
  50 #define BLOCK_COMMENT(str) block_comment(str)
  51 #endif
  52 
  53 #ifdef ASSERT
  54 // On RISC, there's no benefit to verifying instruction boundaries.
  55 bool AbstractAssembler::pd_check_instruction_mark() { return false; }
  56 #endif
  57 
  58 void MacroAssembler::ld_largeoffset_unchecked(Register d, int si31, Register a, int emit_filler_nop) {
  59   assert(Assembler::is_simm(si31, 31) && si31 >= 0, "si31 out of range");
  60   if (Assembler::is_simm(si31, 16)) {
  61     ld(d, si31, a);
  62     if (emit_filler_nop) nop();
  63   } else {
  64     const int hi = MacroAssembler::largeoffset_si16_si16_hi(si31);
  65     const int lo = MacroAssembler::largeoffset_si16_si16_lo(si31);
  66     addis(d, a, hi);
  67     ld(d, lo, d);
  68   }
  69 }
  70 
  71 void MacroAssembler::ld_largeoffset(Register d, int si31, Register a, int emit_filler_nop) {
  72   assert_different_registers(d, a);
  73   ld_largeoffset_unchecked(d, si31, a, emit_filler_nop);
  74 }
  75 
  76 void MacroAssembler::load_sized_value(Register dst, RegisterOrConstant offs, Register base,
  77                                       size_t size_in_bytes, bool is_signed) {
  78   switch (size_in_bytes) {
  79   case  8:              ld(dst, offs, base);                         break;
  80   case  4:  is_signed ? lwa(dst, offs, base) : lwz(dst, offs, base); break;
  81   case  2:  is_signed ? lha(dst, offs, base) : lhz(dst, offs, base); break;
  82   case  1:  lbz(dst, offs, base); if (is_signed) extsb(dst, dst);    break; // lba doesn't exist :(
  83   default:  ShouldNotReachHere();
  84   }
  85 }
  86 
  87 void MacroAssembler::store_sized_value(Register dst, RegisterOrConstant offs, Register base,
  88                                        size_t size_in_bytes) {
  89   switch (size_in_bytes) {
  90   case  8:  std(dst, offs, base); break;
  91   case  4:  stw(dst, offs, base); break;
  92   case  2:  sth(dst, offs, base); break;
  93   case  1:  stb(dst, offs, base); break;
  94   default:  ShouldNotReachHere();
  95   }
  96 }
  97 
  98 void MacroAssembler::align(int modulus, int max, int rem) {
  99   int padding = (rem + modulus - (offset() % modulus)) % modulus;
 100   if (padding > max) return;
 101   for (int c = (padding >> 2); c > 0; --c) { nop(); }
 102 }
 103 
 104 // Issue instructions that calculate given TOC from global TOC.
 105 void MacroAssembler::calculate_address_from_global_toc(Register dst, address addr, bool hi16, bool lo16,
 106                                                        bool add_relocation, bool emit_dummy_addr) {
 107   int offset = -1;
 108   if (emit_dummy_addr) {
 109     offset = -128; // dummy address
 110   } else if (addr != (address)(intptr_t)-1) {
 111     offset = MacroAssembler::offset_to_global_toc(addr);
 112   }
 113 
 114   if (hi16) {
 115     addis(dst, R29, MacroAssembler::largeoffset_si16_si16_hi(offset));
 116   }
 117   if (lo16) {
 118     if (add_relocation) {
 119       // Relocate at the addi to avoid confusion with a load from the method's TOC.
 120       relocate(internal_word_Relocation::spec(addr));
 121     }
 122     addi(dst, dst, MacroAssembler::largeoffset_si16_si16_lo(offset));
 123   }
 124 }
 125 
 126 int MacroAssembler::patch_calculate_address_from_global_toc_at(address a, address bound, address addr) {
 127   const int offset = MacroAssembler::offset_to_global_toc(addr);
 128 
 129   const address inst2_addr = a;
 130   const int inst2 = *(int *)inst2_addr;
 131 
 132   // The relocation points to the second instruction, the addi,
 133   // and the addi reads and writes the same register dst.
 134   const int dst = inv_rt_field(inst2);
 135   assert(is_addi(inst2) && inv_ra_field(inst2) == dst, "must be addi reading and writing dst");
 136 
 137   // Now, find the preceding addis which writes to dst.
 138   int inst1 = 0;
 139   address inst1_addr = inst2_addr - BytesPerInstWord;
 140   while (inst1_addr >= bound) {
 141     inst1 = *(int *) inst1_addr;
 142     if (is_addis(inst1) && inv_rt_field(inst1) == dst) {
 143       // Stop, found the addis which writes dst.
 144       break;
 145     }
 146     inst1_addr -= BytesPerInstWord;
 147   }
 148 
 149   assert(is_addis(inst1) && inv_ra_field(inst1) == 29 /* R29 */, "source must be global TOC");
 150   set_imm((int *)inst1_addr, MacroAssembler::largeoffset_si16_si16_hi(offset));
 151   set_imm((int *)inst2_addr, MacroAssembler::largeoffset_si16_si16_lo(offset));
 152   return (int)((intptr_t)addr - (intptr_t)inst1_addr);
 153 }
 154 
 155 address MacroAssembler::get_address_of_calculate_address_from_global_toc_at(address a, address bound) {
 156   const address inst2_addr = a;
 157   const int inst2 = *(int *)inst2_addr;
 158 
 159   // The relocation points to the second instruction, the addi,
 160   // and the addi reads and writes the same register dst.
 161   const int dst = inv_rt_field(inst2);
 162   assert(is_addi(inst2) && inv_ra_field(inst2) == dst, "must be addi reading and writing dst");
 163 
 164   // Now, find the preceding addis which writes to dst.
 165   int inst1 = 0;
 166   address inst1_addr = inst2_addr - BytesPerInstWord;
 167   while (inst1_addr >= bound) {
 168     inst1 = *(int *) inst1_addr;
 169     if (is_addis(inst1) && inv_rt_field(inst1) == dst) {
 170       // stop, found the addis which writes dst
 171       break;
 172     }
 173     inst1_addr -= BytesPerInstWord;
 174   }
 175 
 176   assert(is_addis(inst1) && inv_ra_field(inst1) == 29 /* R29 */, "source must be global TOC");
 177 
 178   int offset = (get_imm(inst1_addr, 0) << 16) + get_imm(inst2_addr, 0);
 179   // -1 is a special case
 180   if (offset == -1) {
 181     return (address)(intptr_t)-1;
 182   } else {
 183     return global_toc() + offset;
 184   }
 185 }
 186 
 187 #ifdef _LP64
 188 // Patch compressed oops or klass constants.
 189 // Assembler sequence is
 190 // 1) compressed oops:
 191 //    lis  rx = const.hi
 192 //    ori rx = rx | const.lo
 193 // 2) compressed klass:
 194 //    lis  rx = const.hi
 195 //    clrldi rx = rx & 0xFFFFffff // clearMS32b, optional
 196 //    ori rx = rx | const.lo
 197 // Clrldi will be passed by.
 198 int MacroAssembler::patch_set_narrow_oop(address a, address bound, narrowOop data) {
 199   assert(UseCompressedOops, "Should only patch compressed oops");
 200 
 201   const address inst2_addr = a;
 202   const int inst2 = *(int *)inst2_addr;
 203 
 204   // The relocation points to the second instruction, the ori,
 205   // and the ori reads and writes the same register dst.
 206   const int dst = inv_rta_field(inst2);
 207   assert(is_ori(inst2) && inv_rs_field(inst2) == dst, "must be ori reading and writing dst");
 208   // Now, find the preceding addis which writes to dst.
 209   int inst1 = 0;
 210   address inst1_addr = inst2_addr - BytesPerInstWord;
 211   bool inst1_found = false;
 212   while (inst1_addr >= bound) {
 213     inst1 = *(int *)inst1_addr;
 214     if (is_lis(inst1) && inv_rs_field(inst1) == dst) { inst1_found = true; break; }
 215     inst1_addr -= BytesPerInstWord;
 216   }
 217   assert(inst1_found, "inst is not lis");
 218 
 219   int xc = (data >> 16) & 0xffff;
 220   int xd = (data >>  0) & 0xffff;
 221 
 222   set_imm((int *)inst1_addr, (short)(xc)); // see enc_load_con_narrow_hi/_lo
 223   set_imm((int *)inst2_addr,        (xd)); // unsigned int
 224   return (int)((intptr_t)inst2_addr - (intptr_t)inst1_addr);
 225 }
 226 
 227 // Get compressed oop or klass constant.
 228 narrowOop MacroAssembler::get_narrow_oop(address a, address bound) {
 229   assert(UseCompressedOops, "Should only patch compressed oops");
 230 
 231   const address inst2_addr = a;
 232   const int inst2 = *(int *)inst2_addr;
 233 
 234   // The relocation points to the second instruction, the ori,
 235   // and the ori reads and writes the same register dst.
 236   const int dst = inv_rta_field(inst2);
 237   assert(is_ori(inst2) && inv_rs_field(inst2) == dst, "must be ori reading and writing dst");
 238   // Now, find the preceding lis which writes to dst.
 239   int inst1 = 0;
 240   address inst1_addr = inst2_addr - BytesPerInstWord;
 241   bool inst1_found = false;
 242 
 243   while (inst1_addr >= bound) {
 244     inst1 = *(int *) inst1_addr;
 245     if (is_lis(inst1) && inv_rs_field(inst1) == dst) { inst1_found = true; break;}
 246     inst1_addr -= BytesPerInstWord;
 247   }
 248   assert(inst1_found, "inst is not lis");
 249 
 250   uint xl = ((unsigned int) (get_imm(inst2_addr, 0) & 0xffff));
 251   uint xh = (((get_imm(inst1_addr, 0)) & 0xffff) << 16);
 252 
 253   return (int) (xl | xh);
 254 }
 255 #endif // _LP64
 256 
 257 void MacroAssembler::load_const_from_method_toc(Register dst, AddressLiteral& a, Register toc) {
 258   int toc_offset = 0;
 259   // Use RelocationHolder::none for the constant pool entry, otherwise
 260   // we will end up with a failing NativeCall::verify(x) where x is
 261   // the address of the constant pool entry.
 262   // FIXME: We should insert relocation information for oops at the constant
 263   // pool entries instead of inserting it at the loads; patching of a constant
 264   // pool entry should be less expensive.
 265   address oop_address = address_constant((address)a.value(), RelocationHolder::none);
 266   // Relocate at the pc of the load.
 267   relocate(a.rspec());
 268   toc_offset = (int)(oop_address - code()->consts()->start());
 269   ld_largeoffset_unchecked(dst, toc_offset, toc, true);
 270 }
 271 
 272 bool MacroAssembler::is_load_const_from_method_toc_at(address a) {
 273   const address inst1_addr = a;
 274   const int inst1 = *(int *)inst1_addr;
 275 
 276    // The relocation points to the ld or the addis.
 277    return (is_ld(inst1)) ||
 278           (is_addis(inst1) && inv_ra_field(inst1) != 0);
 279 }
 280 
 281 int MacroAssembler::get_offset_of_load_const_from_method_toc_at(address a) {
 282   assert(is_load_const_from_method_toc_at(a), "must be load_const_from_method_toc");
 283 
 284   const address inst1_addr = a;
 285   const int inst1 = *(int *)inst1_addr;
 286 
 287   if (is_ld(inst1)) {
 288     return inv_d1_field(inst1);
 289   } else if (is_addis(inst1)) {
 290     const int dst = inv_rt_field(inst1);
 291 
 292     // Now, find the succeeding ld which reads and writes to dst.
 293     address inst2_addr = inst1_addr + BytesPerInstWord;
 294     int inst2 = 0;
 295     while (true) {
 296       inst2 = *(int *) inst2_addr;
 297       if (is_ld(inst2) && inv_ra_field(inst2) == dst && inv_rt_field(inst2) == dst) {
 298         // Stop, found the ld which reads and writes dst.
 299         break;
 300       }
 301       inst2_addr += BytesPerInstWord;
 302     }
 303     return (inv_d1_field(inst1) << 16) + inv_d1_field(inst2);
 304   }
 305   ShouldNotReachHere();
 306   return 0;
 307 }
 308 
 309 // Get the constant from a `load_const' sequence.
 310 long MacroAssembler::get_const(address a) {
 311   assert(is_load_const_at(a), "not a load of a constant");
 312   const int *p = (const int*) a;
 313   unsigned long x = (((unsigned long) (get_imm(a,0) & 0xffff)) << 48);
 314   if (is_ori(*(p+1))) {
 315     x |= (((unsigned long) (get_imm(a,1) & 0xffff)) << 32);
 316     x |= (((unsigned long) (get_imm(a,3) & 0xffff)) << 16);
 317     x |= (((unsigned long) (get_imm(a,4) & 0xffff)));
 318   } else if (is_lis(*(p+1))) {
 319     x |= (((unsigned long) (get_imm(a,2) & 0xffff)) << 32);
 320     x |= (((unsigned long) (get_imm(a,1) & 0xffff)) << 16);
 321     x |= (((unsigned long) (get_imm(a,3) & 0xffff)));
 322   } else {
 323     ShouldNotReachHere();
 324     return (long) 0;
 325   }
 326   return (long) x;
 327 }
 328 
 329 // Patch the 64 bit constant of a `load_const' sequence. This is a low
 330 // level procedure. It neither flushes the instruction cache nor is it
 331 // mt safe.
 332 void MacroAssembler::patch_const(address a, long x) {
 333   assert(is_load_const_at(a), "not a load of a constant");
 334   int *p = (int*) a;
 335   if (is_ori(*(p+1))) {
 336     set_imm(0 + p, (x >> 48) & 0xffff);
 337     set_imm(1 + p, (x >> 32) & 0xffff);
 338     set_imm(3 + p, (x >> 16) & 0xffff);
 339     set_imm(4 + p, x & 0xffff);
 340   } else if (is_lis(*(p+1))) {
 341     set_imm(0 + p, (x >> 48) & 0xffff);
 342     set_imm(2 + p, (x >> 32) & 0xffff);
 343     set_imm(1 + p, (x >> 16) & 0xffff);
 344     set_imm(3 + p, x & 0xffff);
 345   } else {
 346     ShouldNotReachHere();
 347   }
 348 }
 349 
 350 AddressLiteral MacroAssembler::allocate_metadata_address(Metadata* obj) {
 351   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
 352   int index = oop_recorder()->allocate_metadata_index(obj);
 353   RelocationHolder rspec = metadata_Relocation::spec(index);
 354   return AddressLiteral((address)obj, rspec);
 355 }
 356 
 357 AddressLiteral MacroAssembler::constant_metadata_address(Metadata* obj) {
 358   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
 359   int index = oop_recorder()->find_index(obj);
 360   RelocationHolder rspec = metadata_Relocation::spec(index);
 361   return AddressLiteral((address)obj, rspec);
 362 }
 363 
 364 AddressLiteral MacroAssembler::allocate_oop_address(jobject obj) {
 365   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
 366   int oop_index = oop_recorder()->allocate_oop_index(obj);
 367   return AddressLiteral(address(obj), oop_Relocation::spec(oop_index));
 368 }
 369 
 370 AddressLiteral MacroAssembler::constant_oop_address(jobject obj) {
 371   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
 372   int oop_index = oop_recorder()->find_index(obj);
 373   return AddressLiteral(address(obj), oop_Relocation::spec(oop_index));
 374 }
 375 
 376 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
 377                                                       Register tmp, int offset) {
 378   intptr_t value = *delayed_value_addr;
 379   if (value != 0) {
 380     return RegisterOrConstant(value + offset);
 381   }
 382 
 383   // Load indirectly to solve generation ordering problem.
 384   // static address, no relocation
 385   int simm16_offset = load_const_optimized(tmp, delayed_value_addr, noreg, true);
 386   ld(tmp, simm16_offset, tmp); // must be aligned ((xa & 3) == 0)
 387 
 388   if (offset != 0) {
 389     addi(tmp, tmp, offset);
 390   }
 391 
 392   return RegisterOrConstant(tmp);
 393 }
 394 
 395 #ifndef PRODUCT
 396 void MacroAssembler::pd_print_patched_instruction(address branch) {
 397   Unimplemented(); // TODO: PPC port
 398 }
 399 #endif // ndef PRODUCT
 400 
 401 // Conditional far branch for destinations encodable in 24+2 bits.
 402 void MacroAssembler::bc_far(int boint, int biint, Label& dest, int optimize) {
 403 
 404   // If requested by flag optimize, relocate the bc_far as a
 405   // runtime_call and prepare for optimizing it when the code gets
 406   // relocated.
 407   if (optimize == bc_far_optimize_on_relocate) {
 408     relocate(relocInfo::runtime_call_type);
 409   }
 410 
 411   // variant 2:
 412   //
 413   //    b!cxx SKIP
 414   //    bxx   DEST
 415   //  SKIP:
 416   //
 417 
 418   const int opposite_boint = add_bhint_to_boint(opposite_bhint(inv_boint_bhint(boint)),
 419                                                 opposite_bcond(inv_boint_bcond(boint)));
 420 
 421   // We emit two branches.
 422   // First, a conditional branch which jumps around the far branch.
 423   const address not_taken_pc = pc() + 2 * BytesPerInstWord;
 424   const address bc_pc        = pc();
 425   bc(opposite_boint, biint, not_taken_pc);
 426 
 427   const int bc_instr = *(int*)bc_pc;
 428   assert(not_taken_pc == (address)inv_bd_field(bc_instr, (intptr_t)bc_pc), "postcondition");
 429   assert(opposite_boint == inv_bo_field(bc_instr), "postcondition");
 430   assert(boint == add_bhint_to_boint(opposite_bhint(inv_boint_bhint(inv_bo_field(bc_instr))),
 431                                      opposite_bcond(inv_boint_bcond(inv_bo_field(bc_instr)))),
 432          "postcondition");
 433   assert(biint == inv_bi_field(bc_instr), "postcondition");
 434 
 435   // Second, an unconditional far branch which jumps to dest.
 436   // Note: target(dest) remembers the current pc (see CodeSection::target)
 437   //       and returns the current pc if the label is not bound yet; when
 438   //       the label gets bound, the unconditional far branch will be patched.
 439   const address target_pc = target(dest);
 440   const address b_pc  = pc();
 441   b(target_pc);
 442 
 443   assert(not_taken_pc == pc(),                     "postcondition");
 444   assert(dest.is_bound() || target_pc == b_pc, "postcondition");
 445 }
 446 
 447 bool MacroAssembler::is_bc_far_at(address instruction_addr) {
 448   return is_bc_far_variant1_at(instruction_addr) ||
 449          is_bc_far_variant2_at(instruction_addr) ||
 450          is_bc_far_variant3_at(instruction_addr);
 451 }
 452 
 453 address MacroAssembler::get_dest_of_bc_far_at(address instruction_addr) {
 454   if (is_bc_far_variant1_at(instruction_addr)) {
 455     const address instruction_1_addr = instruction_addr;
 456     const int instruction_1 = *(int*)instruction_1_addr;
 457     return (address)inv_bd_field(instruction_1, (intptr_t)instruction_1_addr);
 458   } else if (is_bc_far_variant2_at(instruction_addr)) {
 459     const address instruction_2_addr = instruction_addr + 4;
 460     return bxx_destination(instruction_2_addr);
 461   } else if (is_bc_far_variant3_at(instruction_addr)) {
 462     return instruction_addr + 8;
 463   }
 464   // variant 4 ???
 465   ShouldNotReachHere();
 466   return NULL;
 467 }
 468 void MacroAssembler::set_dest_of_bc_far_at(address instruction_addr, address dest) {
 469 
 470   if (is_bc_far_variant3_at(instruction_addr)) {
 471     // variant 3, far cond branch to the next instruction, already patched to nops:
 472     //
 473     //    nop
 474     //    endgroup
 475     //  SKIP/DEST:
 476     //
 477     return;
 478   }
 479 
 480   // first, extract boint and biint from the current branch
 481   int boint = 0;
 482   int biint = 0;
 483 
 484   ResourceMark rm;
 485   const int code_size = 2 * BytesPerInstWord;
 486   CodeBuffer buf(instruction_addr, code_size);
 487   MacroAssembler masm(&buf);
 488   if (is_bc_far_variant2_at(instruction_addr) && dest == instruction_addr + 8) {
 489     // Far branch to next instruction: Optimize it by patching nops (produce variant 3).
 490     masm.nop();
 491     masm.endgroup();
 492   } else {
 493     if (is_bc_far_variant1_at(instruction_addr)) {
 494       // variant 1, the 1st instruction contains the destination address:
 495       //
 496       //    bcxx  DEST
 497       //    endgroup
 498       //
 499       const int instruction_1 = *(int*)(instruction_addr);
 500       boint = inv_bo_field(instruction_1);
 501       biint = inv_bi_field(instruction_1);
 502     } else if (is_bc_far_variant2_at(instruction_addr)) {
 503       // variant 2, the 2nd instruction contains the destination address:
 504       //
 505       //    b!cxx SKIP
 506       //    bxx   DEST
 507       //  SKIP:
 508       //
 509       const int instruction_1 = *(int*)(instruction_addr);
 510       boint = add_bhint_to_boint(opposite_bhint(inv_boint_bhint(inv_bo_field(instruction_1))),
 511           opposite_bcond(inv_boint_bcond(inv_bo_field(instruction_1))));
 512       biint = inv_bi_field(instruction_1);
 513     } else {
 514       // variant 4???
 515       ShouldNotReachHere();
 516     }
 517 
 518     // second, set the new branch destination and optimize the code
 519     if (dest != instruction_addr + 4 && // the bc_far is still unbound!
 520         masm.is_within_range_of_bcxx(dest, instruction_addr)) {
 521       // variant 1:
 522       //
 523       //    bcxx  DEST
 524       //    endgroup
 525       //
 526       masm.bc(boint, biint, dest);
 527       masm.endgroup();
 528     } else {
 529       // variant 2:
 530       //
 531       //    b!cxx SKIP
 532       //    bxx   DEST
 533       //  SKIP:
 534       //
 535       const int opposite_boint = add_bhint_to_boint(opposite_bhint(inv_boint_bhint(boint)),
 536                                                     opposite_bcond(inv_boint_bcond(boint)));
 537       const address not_taken_pc = masm.pc() + 2 * BytesPerInstWord;
 538       masm.bc(opposite_boint, biint, not_taken_pc);
 539       masm.b(dest);
 540     }
 541   }
 542   ICache::ppc64_flush_icache_bytes(instruction_addr, code_size);
 543 }
 544 
 545 // Emit a NOT mt-safe patchable 64 bit absolute call/jump.
 546 void MacroAssembler::bxx64_patchable(address dest, relocInfo::relocType rt, bool link) {
 547   // get current pc
 548   uint64_t start_pc = (uint64_t) pc();
 549 
 550   const address pc_of_bl = (address) (start_pc + (6*BytesPerInstWord)); // bl is last
 551   const address pc_of_b  = (address) (start_pc + (0*BytesPerInstWord)); // b is first
 552 
 553   // relocate here
 554   if (rt != relocInfo::none) {
 555     relocate(rt);
 556   }
 557 
 558   if ( ReoptimizeCallSequences &&
 559        (( link && is_within_range_of_b(dest, pc_of_bl)) ||
 560         (!link && is_within_range_of_b(dest, pc_of_b)))) {
 561     // variant 2:
 562     // Emit an optimized, pc-relative call/jump.
 563 
 564     if (link) {
 565       // some padding
 566       nop();
 567       nop();
 568       nop();
 569       nop();
 570       nop();
 571       nop();
 572 
 573       // do the call
 574       assert(pc() == pc_of_bl, "just checking");
 575       bl(dest, relocInfo::none);
 576     } else {
 577       // do the jump
 578       assert(pc() == pc_of_b, "just checking");
 579       b(dest, relocInfo::none);
 580 
 581       // some padding
 582       nop();
 583       nop();
 584       nop();
 585       nop();
 586       nop();
 587       nop();
 588     }
 589 
 590     // Assert that we can identify the emitted call/jump.
 591     assert(is_bxx64_patchable_variant2_at((address)start_pc, link),
 592            "can't identify emitted call");
 593   } else {
 594     // variant 1:
 595 #if defined(ABI_ELFv2)
 596     nop();
 597     calculate_address_from_global_toc(R12, dest, true, true, false);
 598     mtctr(R12);
 599     nop();
 600     nop();
 601 #else
 602     mr(R0, R11);  // spill R11 -> R0.
 603 
 604     // Load the destination address into CTR,
 605     // calculate destination relative to global toc.
 606     calculate_address_from_global_toc(R11, dest, true, true, false);
 607 
 608     mtctr(R11);
 609     mr(R11, R0);  // spill R11 <- R0.
 610     nop();
 611 #endif
 612 
 613     // do the call/jump
 614     if (link) {
 615       bctrl();
 616     } else{
 617       bctr();
 618     }
 619     // Assert that we can identify the emitted call/jump.
 620     assert(is_bxx64_patchable_variant1b_at((address)start_pc, link),
 621            "can't identify emitted call");
 622   }
 623 
 624   // Assert that we can identify the emitted call/jump.
 625   assert(is_bxx64_patchable_at((address)start_pc, link),
 626          "can't identify emitted call");
 627   assert(get_dest_of_bxx64_patchable_at((address)start_pc, link) == dest,
 628          "wrong encoding of dest address");
 629 }
 630 
 631 // Identify a bxx64_patchable instruction.
 632 bool MacroAssembler::is_bxx64_patchable_at(address instruction_addr, bool link) {
 633   return is_bxx64_patchable_variant1b_at(instruction_addr, link)
 634     //|| is_bxx64_patchable_variant1_at(instruction_addr, link)
 635       || is_bxx64_patchable_variant2_at(instruction_addr, link);
 636 }
 637 
 638 // Does the call64_patchable instruction use a pc-relative encoding of
 639 // the call destination?
 640 bool MacroAssembler::is_bxx64_patchable_pcrelative_at(address instruction_addr, bool link) {
 641   // variant 2 is pc-relative
 642   return is_bxx64_patchable_variant2_at(instruction_addr, link);
 643 }
 644 
 645 // Identify variant 1.
 646 bool MacroAssembler::is_bxx64_patchable_variant1_at(address instruction_addr, bool link) {
 647   unsigned int* instr = (unsigned int*) instruction_addr;
 648   return (link ? is_bctrl(instr[6]) : is_bctr(instr[6])) // bctr[l]
 649       && is_mtctr(instr[5]) // mtctr
 650     && is_load_const_at(instruction_addr);
 651 }
 652 
 653 // Identify variant 1b: load destination relative to global toc.
 654 bool MacroAssembler::is_bxx64_patchable_variant1b_at(address instruction_addr, bool link) {
 655   unsigned int* instr = (unsigned int*) instruction_addr;
 656   return (link ? is_bctrl(instr[6]) : is_bctr(instr[6])) // bctr[l]
 657     && is_mtctr(instr[3]) // mtctr
 658     && is_calculate_address_from_global_toc_at(instruction_addr + 2*BytesPerInstWord, instruction_addr);
 659 }
 660 
 661 // Identify variant 2.
 662 bool MacroAssembler::is_bxx64_patchable_variant2_at(address instruction_addr, bool link) {
 663   unsigned int* instr = (unsigned int*) instruction_addr;
 664   if (link) {
 665     return is_bl (instr[6])  // bl dest is last
 666       && is_nop(instr[0])  // nop
 667       && is_nop(instr[1])  // nop
 668       && is_nop(instr[2])  // nop
 669       && is_nop(instr[3])  // nop
 670       && is_nop(instr[4])  // nop
 671       && is_nop(instr[5]); // nop
 672   } else {
 673     return is_b  (instr[0])  // b  dest is first
 674       && is_nop(instr[1])  // nop
 675       && is_nop(instr[2])  // nop
 676       && is_nop(instr[3])  // nop
 677       && is_nop(instr[4])  // nop
 678       && is_nop(instr[5])  // nop
 679       && is_nop(instr[6]); // nop
 680   }
 681 }
 682 
 683 // Set dest address of a bxx64_patchable instruction.
 684 void MacroAssembler::set_dest_of_bxx64_patchable_at(address instruction_addr, address dest, bool link) {
 685   ResourceMark rm;
 686   int code_size = MacroAssembler::bxx64_patchable_size;
 687   CodeBuffer buf(instruction_addr, code_size);
 688   MacroAssembler masm(&buf);
 689   masm.bxx64_patchable(dest, relocInfo::none, link);
 690   ICache::ppc64_flush_icache_bytes(instruction_addr, code_size);
 691 }
 692 
 693 // Get dest address of a bxx64_patchable instruction.
 694 address MacroAssembler::get_dest_of_bxx64_patchable_at(address instruction_addr, bool link) {
 695   if (is_bxx64_patchable_variant1_at(instruction_addr, link)) {
 696     return (address) (unsigned long) get_const(instruction_addr);
 697   } else if (is_bxx64_patchable_variant2_at(instruction_addr, link)) {
 698     unsigned int* instr = (unsigned int*) instruction_addr;
 699     if (link) {
 700       const int instr_idx = 6; // bl is last
 701       int branchoffset = branch_destination(instr[instr_idx], 0);
 702       return instruction_addr + branchoffset + instr_idx*BytesPerInstWord;
 703     } else {
 704       const int instr_idx = 0; // b is first
 705       int branchoffset = branch_destination(instr[instr_idx], 0);
 706       return instruction_addr + branchoffset + instr_idx*BytesPerInstWord;
 707     }
 708   // Load dest relative to global toc.
 709   } else if (is_bxx64_patchable_variant1b_at(instruction_addr, link)) {
 710     return get_address_of_calculate_address_from_global_toc_at(instruction_addr + 2*BytesPerInstWord,
 711                                                                instruction_addr);
 712   } else {
 713     ShouldNotReachHere();
 714     return NULL;
 715   }
 716 }
 717 
 718 // Uses ordering which corresponds to ABI:
 719 //    _savegpr0_14:  std  r14,-144(r1)
 720 //    _savegpr0_15:  std  r15,-136(r1)
 721 //    _savegpr0_16:  std  r16,-128(r1)
 722 void MacroAssembler::save_nonvolatile_gprs(Register dst, int offset) {
 723   std(R14, offset, dst);   offset += 8;
 724   std(R15, offset, dst);   offset += 8;
 725   std(R16, offset, dst);   offset += 8;
 726   std(R17, offset, dst);   offset += 8;
 727   std(R18, offset, dst);   offset += 8;
 728   std(R19, offset, dst);   offset += 8;
 729   std(R20, offset, dst);   offset += 8;
 730   std(R21, offset, dst);   offset += 8;
 731   std(R22, offset, dst);   offset += 8;
 732   std(R23, offset, dst);   offset += 8;
 733   std(R24, offset, dst);   offset += 8;
 734   std(R25, offset, dst);   offset += 8;
 735   std(R26, offset, dst);   offset += 8;
 736   std(R27, offset, dst);   offset += 8;
 737   std(R28, offset, dst);   offset += 8;
 738   std(R29, offset, dst);   offset += 8;
 739   std(R30, offset, dst);   offset += 8;
 740   std(R31, offset, dst);   offset += 8;
 741 
 742   stfd(F14, offset, dst);   offset += 8;
 743   stfd(F15, offset, dst);   offset += 8;
 744   stfd(F16, offset, dst);   offset += 8;
 745   stfd(F17, offset, dst);   offset += 8;
 746   stfd(F18, offset, dst);   offset += 8;
 747   stfd(F19, offset, dst);   offset += 8;
 748   stfd(F20, offset, dst);   offset += 8;
 749   stfd(F21, offset, dst);   offset += 8;
 750   stfd(F22, offset, dst);   offset += 8;
 751   stfd(F23, offset, dst);   offset += 8;
 752   stfd(F24, offset, dst);   offset += 8;
 753   stfd(F25, offset, dst);   offset += 8;
 754   stfd(F26, offset, dst);   offset += 8;
 755   stfd(F27, offset, dst);   offset += 8;
 756   stfd(F28, offset, dst);   offset += 8;
 757   stfd(F29, offset, dst);   offset += 8;
 758   stfd(F30, offset, dst);   offset += 8;
 759   stfd(F31, offset, dst);
 760 }
 761 
 762 // Uses ordering which corresponds to ABI:
 763 //    _restgpr0_14:  ld   r14,-144(r1)
 764 //    _restgpr0_15:  ld   r15,-136(r1)
 765 //    _restgpr0_16:  ld   r16,-128(r1)
 766 void MacroAssembler::restore_nonvolatile_gprs(Register src, int offset) {
 767   ld(R14, offset, src);   offset += 8;
 768   ld(R15, offset, src);   offset += 8;
 769   ld(R16, offset, src);   offset += 8;
 770   ld(R17, offset, src);   offset += 8;
 771   ld(R18, offset, src);   offset += 8;
 772   ld(R19, offset, src);   offset += 8;
 773   ld(R20, offset, src);   offset += 8;
 774   ld(R21, offset, src);   offset += 8;
 775   ld(R22, offset, src);   offset += 8;
 776   ld(R23, offset, src);   offset += 8;
 777   ld(R24, offset, src);   offset += 8;
 778   ld(R25, offset, src);   offset += 8;
 779   ld(R26, offset, src);   offset += 8;
 780   ld(R27, offset, src);   offset += 8;
 781   ld(R28, offset, src);   offset += 8;
 782   ld(R29, offset, src);   offset += 8;
 783   ld(R30, offset, src);   offset += 8;
 784   ld(R31, offset, src);   offset += 8;
 785 
 786   // FP registers
 787   lfd(F14, offset, src);   offset += 8;
 788   lfd(F15, offset, src);   offset += 8;
 789   lfd(F16, offset, src);   offset += 8;
 790   lfd(F17, offset, src);   offset += 8;
 791   lfd(F18, offset, src);   offset += 8;
 792   lfd(F19, offset, src);   offset += 8;
 793   lfd(F20, offset, src);   offset += 8;
 794   lfd(F21, offset, src);   offset += 8;
 795   lfd(F22, offset, src);   offset += 8;
 796   lfd(F23, offset, src);   offset += 8;
 797   lfd(F24, offset, src);   offset += 8;
 798   lfd(F25, offset, src);   offset += 8;
 799   lfd(F26, offset, src);   offset += 8;
 800   lfd(F27, offset, src);   offset += 8;
 801   lfd(F28, offset, src);   offset += 8;
 802   lfd(F29, offset, src);   offset += 8;
 803   lfd(F30, offset, src);   offset += 8;
 804   lfd(F31, offset, src);
 805 }
 806 
 807 // For verify_oops.
 808 void MacroAssembler::save_volatile_gprs(Register dst, int offset) {
 809   std(R3,  offset, dst);   offset += 8;
 810   std(R4,  offset, dst);   offset += 8;
 811   std(R5,  offset, dst);   offset += 8;
 812   std(R6,  offset, dst);   offset += 8;
 813   std(R7,  offset, dst);   offset += 8;
 814   std(R8,  offset, dst);   offset += 8;
 815   std(R9,  offset, dst);   offset += 8;
 816   std(R10, offset, dst);   offset += 8;
 817   std(R11, offset, dst);   offset += 8;
 818   std(R12, offset, dst);
 819 }
 820 
 821 // For verify_oops.
 822 void MacroAssembler::restore_volatile_gprs(Register src, int offset) {
 823   ld(R3,  offset, src);   offset += 8;
 824   ld(R4,  offset, src);   offset += 8;
 825   ld(R5,  offset, src);   offset += 8;
 826   ld(R6,  offset, src);   offset += 8;
 827   ld(R7,  offset, src);   offset += 8;
 828   ld(R8,  offset, src);   offset += 8;
 829   ld(R9,  offset, src);   offset += 8;
 830   ld(R10, offset, src);   offset += 8;
 831   ld(R11, offset, src);   offset += 8;
 832   ld(R12, offset, src);
 833 }
 834 
 835 void MacroAssembler::save_LR_CR(Register tmp) {
 836   mfcr(tmp);
 837   std(tmp, _abi(cr), R1_SP);
 838   mflr(tmp);
 839   std(tmp, _abi(lr), R1_SP);
 840   // Tmp must contain lr on exit! (see return_addr and prolog in ppc64.ad)
 841 }
 842 
 843 void MacroAssembler::restore_LR_CR(Register tmp) {
 844   assert(tmp != R1_SP, "must be distinct");
 845   ld(tmp, _abi(lr), R1_SP);
 846   mtlr(tmp);
 847   ld(tmp, _abi(cr), R1_SP);
 848   mtcr(tmp);
 849 }
 850 
 851 address MacroAssembler::get_PC_trash_LR(Register result) {
 852   Label L;
 853   bl(L);
 854   bind(L);
 855   address lr_pc = pc();
 856   mflr(result);
 857   return lr_pc;
 858 }
 859 
 860 void MacroAssembler::resize_frame(Register offset, Register tmp) {
 861 #ifdef ASSERT
 862   assert_different_registers(offset, tmp, R1_SP);
 863   andi_(tmp, offset, frame::alignment_in_bytes-1);
 864   asm_assert_eq("resize_frame: unaligned", 0x204);
 865 #endif
 866 
 867   // tmp <- *(SP)
 868   ld(tmp, _abi(callers_sp), R1_SP);
 869   // addr <- SP + offset;
 870   // *(addr) <- tmp;
 871   // SP <- addr
 872   stdux(tmp, R1_SP, offset);
 873 }
 874 
 875 void MacroAssembler::resize_frame(int offset, Register tmp) {
 876   assert(is_simm(offset, 16), "too big an offset");
 877   assert_different_registers(tmp, R1_SP);
 878   assert((offset & (frame::alignment_in_bytes-1))==0, "resize_frame: unaligned");
 879   // tmp <- *(SP)
 880   ld(tmp, _abi(callers_sp), R1_SP);
 881   // addr <- SP + offset;
 882   // *(addr) <- tmp;
 883   // SP <- addr
 884   stdu(tmp, offset, R1_SP);
 885 }
 886 
 887 void MacroAssembler::resize_frame_absolute(Register addr, Register tmp1, Register tmp2) {
 888   // (addr == tmp1) || (addr == tmp2) is allowed here!
 889   assert(tmp1 != tmp2, "must be distinct");
 890 
 891   // compute offset w.r.t. current stack pointer
 892   // tmp_1 <- addr - SP (!)
 893   subf(tmp1, R1_SP, addr);
 894 
 895   // atomically update SP keeping back link.
 896   resize_frame(tmp1/* offset */, tmp2/* tmp */);
 897 }
 898 
 899 void MacroAssembler::push_frame(Register bytes, Register tmp) {
 900 #ifdef ASSERT
 901   assert(bytes != R0, "r0 not allowed here");
 902   andi_(R0, bytes, frame::alignment_in_bytes-1);
 903   asm_assert_eq("push_frame(Reg, Reg): unaligned", 0x203);
 904 #endif
 905   neg(tmp, bytes);
 906   stdux(R1_SP, R1_SP, tmp);
 907 }
 908 
 909 // Push a frame of size `bytes'.
 910 void MacroAssembler::push_frame(unsigned int bytes, Register tmp) {
 911   long offset = align_addr(bytes, frame::alignment_in_bytes);
 912   if (is_simm(-offset, 16)) {
 913     stdu(R1_SP, -offset, R1_SP);
 914   } else {
 915     load_const(tmp, -offset);
 916     stdux(R1_SP, R1_SP, tmp);
 917   }
 918 }
 919 
 920 // Push a frame of size `bytes' plus abi_reg_args on top.
 921 void MacroAssembler::push_frame_reg_args(unsigned int bytes, Register tmp) {
 922   push_frame(bytes + frame::abi_reg_args_size, tmp);
 923 }
 924 
 925 // Setup up a new C frame with a spill area for non-volatile GPRs and
 926 // additional space for local variables.
 927 void MacroAssembler::push_frame_reg_args_nonvolatiles(unsigned int bytes,
 928                                                       Register tmp) {
 929   push_frame(bytes + frame::abi_reg_args_size + frame::spill_nonvolatiles_size, tmp);
 930 }
 931 
 932 // Pop current C frame.
 933 void MacroAssembler::pop_frame() {
 934   ld(R1_SP, _abi(callers_sp), R1_SP);
 935 }
 936 
 937 #if defined(ABI_ELFv2)
 938 address MacroAssembler::branch_to(Register r_function_entry, bool and_link) {
 939   // TODO(asmundak): make sure the caller uses R12 as function descriptor
 940   // most of the times.
 941   if (R12 != r_function_entry) {
 942     mr(R12, r_function_entry);
 943   }
 944   mtctr(R12);
 945   // Do a call or a branch.
 946   if (and_link) {
 947     bctrl();
 948   } else {
 949     bctr();
 950   }
 951   _last_calls_return_pc = pc();
 952 
 953   return _last_calls_return_pc;
 954 }
 955 
 956 // Call a C function via a function descriptor and use full C
 957 // calling conventions. Updates and returns _last_calls_return_pc.
 958 address MacroAssembler::call_c(Register r_function_entry) {
 959   return branch_to(r_function_entry, /*and_link=*/true);
 960 }
 961 
 962 // For tail calls: only branch, don't link, so callee returns to caller of this function.
 963 address MacroAssembler::call_c_and_return_to_caller(Register r_function_entry) {
 964   return branch_to(r_function_entry, /*and_link=*/false);
 965 }
 966 
 967 address MacroAssembler::call_c(address function_entry, relocInfo::relocType rt) {
 968   load_const(R12, function_entry, R0);
 969   return branch_to(R12,  /*and_link=*/true);
 970 }
 971 
 972 #else
 973 // Generic version of a call to C function via a function descriptor
 974 // with variable support for C calling conventions (TOC, ENV, etc.).
 975 // Updates and returns _last_calls_return_pc.
 976 address MacroAssembler::branch_to(Register function_descriptor, bool and_link, bool save_toc_before_call,
 977                                   bool restore_toc_after_call, bool load_toc_of_callee, bool load_env_of_callee) {
 978   // we emit standard ptrgl glue code here
 979   assert((function_descriptor != R0), "function_descriptor cannot be R0");
 980 
 981   // retrieve necessary entries from the function descriptor
 982   ld(R0, in_bytes(FunctionDescriptor::entry_offset()), function_descriptor);
 983   mtctr(R0);
 984 
 985   if (load_toc_of_callee) {
 986     ld(R2_TOC, in_bytes(FunctionDescriptor::toc_offset()), function_descriptor);
 987   }
 988   if (load_env_of_callee) {
 989     ld(R11, in_bytes(FunctionDescriptor::env_offset()), function_descriptor);
 990   } else if (load_toc_of_callee) {
 991     li(R11, 0);
 992   }
 993 
 994   // do a call or a branch
 995   if (and_link) {
 996     bctrl();
 997   } else {
 998     bctr();
 999   }
1000   _last_calls_return_pc = pc();
1001 
1002   return _last_calls_return_pc;
1003 }
1004 
1005 // Call a C function via a function descriptor and use full C calling
1006 // conventions.
1007 // We don't use the TOC in generated code, so there is no need to save
1008 // and restore its value.
1009 address MacroAssembler::call_c(Register fd) {
1010   return branch_to(fd, /*and_link=*/true,
1011                        /*save toc=*/false,
1012                        /*restore toc=*/false,
1013                        /*load toc=*/true,
1014                        /*load env=*/true);
1015 }
1016 
1017 address MacroAssembler::call_c_and_return_to_caller(Register fd) {
1018   return branch_to(fd, /*and_link=*/false,
1019                        /*save toc=*/false,
1020                        /*restore toc=*/false,
1021                        /*load toc=*/true,
1022                        /*load env=*/true);
1023 }
1024 
1025 address MacroAssembler::call_c(const FunctionDescriptor* fd, relocInfo::relocType rt) {
1026   if (rt != relocInfo::none) {
1027     // this call needs to be relocatable
1028     if (!ReoptimizeCallSequences
1029         || (rt != relocInfo::runtime_call_type && rt != relocInfo::none)
1030         || fd == NULL   // support code-size estimation
1031         || !fd->is_friend_function()
1032         || fd->entry() == NULL) {
1033       // it's not a friend function as defined by class FunctionDescriptor,
1034       // so do a full call-c here.
1035       load_const(R11, (address)fd, R0);
1036 
1037       bool has_env = (fd != NULL && fd->env() != NULL);
1038       return branch_to(R11, /*and_link=*/true,
1039                             /*save toc=*/false,
1040                             /*restore toc=*/false,
1041                             /*load toc=*/true,
1042                             /*load env=*/has_env);
1043     } else {
1044       // It's a friend function. Load the entry point and don't care about
1045       // toc and env. Use an optimizable call instruction, but ensure the
1046       // same code-size as in the case of a non-friend function.
1047       nop();
1048       nop();
1049       nop();
1050       bl64_patchable(fd->entry(), rt);
1051       _last_calls_return_pc = pc();
1052       return _last_calls_return_pc;
1053     }
1054   } else {
1055     // This call does not need to be relocatable, do more aggressive
1056     // optimizations.
1057     if (!ReoptimizeCallSequences
1058       || !fd->is_friend_function()) {
1059       // It's not a friend function as defined by class FunctionDescriptor,
1060       // so do a full call-c here.
1061       load_const(R11, (address)fd, R0);
1062       return branch_to(R11, /*and_link=*/true,
1063                             /*save toc=*/false,
1064                             /*restore toc=*/false,
1065                             /*load toc=*/true,
1066                             /*load env=*/true);
1067     } else {
1068       // it's a friend function, load the entry point and don't care about
1069       // toc and env.
1070       address dest = fd->entry();
1071       if (is_within_range_of_b(dest, pc())) {
1072         bl(dest);
1073       } else {
1074         bl64_patchable(dest, rt);
1075       }
1076       _last_calls_return_pc = pc();
1077       return _last_calls_return_pc;
1078     }
1079   }
1080 }
1081 
1082 // Call a C function.  All constants needed reside in TOC.
1083 //
1084 // Read the address to call from the TOC.
1085 // Read env from TOC, if fd specifies an env.
1086 // Read new TOC from TOC.
1087 address MacroAssembler::call_c_using_toc(const FunctionDescriptor* fd,
1088                                          relocInfo::relocType rt, Register toc) {
1089   if (!ReoptimizeCallSequences
1090     || (rt != relocInfo::runtime_call_type && rt != relocInfo::none)
1091     || !fd->is_friend_function()) {
1092     // It's not a friend function as defined by class FunctionDescriptor,
1093     // so do a full call-c here.
1094     assert(fd->entry() != NULL, "function must be linked");
1095 
1096     AddressLiteral fd_entry(fd->entry());
1097     load_const_from_method_toc(R11, fd_entry, toc);
1098     mtctr(R11);
1099     if (fd->env() == NULL) {
1100       li(R11, 0);
1101       nop();
1102     } else {
1103       AddressLiteral fd_env(fd->env());
1104       load_const_from_method_toc(R11, fd_env, toc);
1105     }
1106     AddressLiteral fd_toc(fd->toc());
1107     load_toc_from_toc(R2_TOC, fd_toc, toc);
1108     // R2_TOC is killed.
1109     bctrl();
1110     _last_calls_return_pc = pc();
1111   } else {
1112     // It's a friend function, load the entry point and don't care about
1113     // toc and env. Use an optimizable call instruction, but ensure the
1114     // same code-size as in the case of a non-friend function.
1115     nop();
1116     bl64_patchable(fd->entry(), rt);
1117     _last_calls_return_pc = pc();
1118   }
1119   return _last_calls_return_pc;
1120 }
1121 #endif // ABI_ELFv2
1122 
1123 void MacroAssembler::call_VM_base(Register oop_result,
1124                                   Register last_java_sp,
1125                                   address  entry_point,
1126                                   bool     check_exceptions) {
1127   BLOCK_COMMENT("call_VM {");
1128   // Determine last_java_sp register.
1129   if (!last_java_sp->is_valid()) {
1130     last_java_sp = R1_SP;
1131   }
1132   set_top_ijava_frame_at_SP_as_last_Java_frame(last_java_sp, R11_scratch1);
1133 
1134   // ARG1 must hold thread address.
1135   mr(R3_ARG1, R16_thread);
1136 #if defined(ABI_ELFv2)
1137   address return_pc = call_c(entry_point, relocInfo::none);
1138 #else
1139   address return_pc = call_c((FunctionDescriptor*)entry_point, relocInfo::none);
1140 #endif
1141 
1142   reset_last_Java_frame();
1143 
1144   // Check for pending exceptions.
1145   if (check_exceptions) {
1146     // We don't check for exceptions here.
1147     ShouldNotReachHere();
1148   }
1149 
1150   // Get oop result if there is one and reset the value in the thread.
1151   if (oop_result->is_valid()) {
1152     get_vm_result(oop_result);
1153   }
1154 
1155   _last_calls_return_pc = return_pc;
1156   BLOCK_COMMENT("} call_VM");
1157 }
1158 
1159 void MacroAssembler::call_VM_leaf_base(address entry_point) {
1160   BLOCK_COMMENT("call_VM_leaf {");
1161 #if defined(ABI_ELFv2)
1162   call_c(entry_point, relocInfo::none);
1163 #else
1164   call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, entry_point), relocInfo::none);
1165 #endif
1166   BLOCK_COMMENT("} call_VM_leaf");
1167 }
1168 
1169 void MacroAssembler::call_VM(Register oop_result, address entry_point, bool check_exceptions) {
1170   call_VM_base(oop_result, noreg, entry_point, check_exceptions);
1171 }
1172 
1173 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1,
1174                              bool check_exceptions) {
1175   // R3_ARG1 is reserved for the thread.
1176   mr_if_needed(R4_ARG2, arg_1);
1177   call_VM(oop_result, entry_point, check_exceptions);
1178 }
1179 
1180 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2,
1181                              bool check_exceptions) {
1182   // R3_ARG1 is reserved for the thread
1183   mr_if_needed(R4_ARG2, arg_1);
1184   assert(arg_2 != R4_ARG2, "smashed argument");
1185   mr_if_needed(R5_ARG3, arg_2);
1186   call_VM(oop_result, entry_point, check_exceptions);
1187 }
1188 
1189 void MacroAssembler::call_VM_leaf(address entry_point) {
1190   call_VM_leaf_base(entry_point);
1191 }
1192 
1193 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1) {
1194   mr_if_needed(R3_ARG1, arg_1);
1195   call_VM_leaf(entry_point);
1196 }
1197 
1198 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1, Register arg_2) {
1199   mr_if_needed(R3_ARG1, arg_1);
1200   assert(arg_2 != R3_ARG1, "smashed argument");
1201   mr_if_needed(R4_ARG2, arg_2);
1202   call_VM_leaf(entry_point);
1203 }
1204 
1205 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1, Register arg_2, Register arg_3) {
1206   mr_if_needed(R3_ARG1, arg_1);
1207   assert(arg_2 != R3_ARG1, "smashed argument");
1208   mr_if_needed(R4_ARG2, arg_2);
1209   assert(arg_3 != R3_ARG1 && arg_3 != R4_ARG2, "smashed argument");
1210   mr_if_needed(R5_ARG3, arg_3);
1211   call_VM_leaf(entry_point);
1212 }
1213 
1214 // Check whether instruction is a read access to the polling page
1215 // which was emitted by load_from_polling_page(..).
1216 bool MacroAssembler::is_load_from_polling_page(int instruction, void* ucontext,
1217                                                address* polling_address_ptr) {
1218   if (!is_ld(instruction))
1219     return false; // It's not a ld. Fail.
1220 
1221   int rt = inv_rt_field(instruction);
1222   int ra = inv_ra_field(instruction);
1223   int ds = inv_ds_field(instruction);
1224   if (!(ds == 0 && ra != 0 && rt == 0)) {
1225     return false; // It's not a ld(r0, X, ra). Fail.
1226   }
1227 
1228   if (!ucontext) {
1229     // Set polling address.
1230     if (polling_address_ptr != NULL) {
1231       *polling_address_ptr = NULL;
1232     }
1233     return true; // No ucontext given. Can't check value of ra. Assume true.
1234   }
1235 
1236 #ifdef LINUX
1237   // Ucontext given. Check that register ra contains the address of
1238   // the safepoing polling page.
1239   ucontext_t* uc = (ucontext_t*) ucontext;
1240   // Set polling address.
1241   address addr = (address)uc->uc_mcontext.regs->gpr[ra] + (ssize_t)ds;
1242   if (polling_address_ptr != NULL) {
1243     *polling_address_ptr = addr;
1244   }
1245   return os::is_poll_address(addr);
1246 #else
1247   // Not on Linux, ucontext must be NULL.
1248   ShouldNotReachHere();
1249   return false;
1250 #endif
1251 }
1252 
1253 bool MacroAssembler::is_memory_serialization(int instruction, JavaThread* thread, void* ucontext) {
1254 #ifdef LINUX
1255   ucontext_t* uc = (ucontext_t*) ucontext;
1256 
1257   if (is_stwx(instruction) || is_stwux(instruction)) {
1258     int ra = inv_ra_field(instruction);
1259     int rb = inv_rb_field(instruction);
1260 
1261     // look up content of ra and rb in ucontext
1262     address ra_val=(address)uc->uc_mcontext.regs->gpr[ra];
1263     long rb_val=(long)uc->uc_mcontext.regs->gpr[rb];
1264     return os::is_memory_serialize_page(thread, ra_val+rb_val);
1265   } else if (is_stw(instruction) || is_stwu(instruction)) {
1266     int ra = inv_ra_field(instruction);
1267     int d1 = inv_d1_field(instruction);
1268 
1269     // look up content of ra in ucontext
1270     address ra_val=(address)uc->uc_mcontext.regs->gpr[ra];
1271     return os::is_memory_serialize_page(thread, ra_val+d1);
1272   } else {
1273     return false;
1274   }
1275 #else
1276   // workaround not needed on !LINUX :-)
1277   ShouldNotCallThis();
1278   return false;
1279 #endif
1280 }
1281 
1282 void MacroAssembler::bang_stack_with_offset(int offset) {
1283   // When increasing the stack, the old stack pointer will be written
1284   // to the new top of stack according to the PPC64 abi.
1285   // Therefore, stack banging is not necessary when increasing
1286   // the stack by <= os::vm_page_size() bytes.
1287   // When increasing the stack by a larger amount, this method is
1288   // called repeatedly to bang the intermediate pages.
1289 
1290   // Stack grows down, caller passes positive offset.
1291   assert(offset > 0, "must bang with positive offset");
1292 
1293   long stdoffset = -offset;
1294 
1295   if (is_simm(stdoffset, 16)) {
1296     // Signed 16 bit offset, a simple std is ok.
1297     if (UseLoadInstructionsForStackBangingPPC64) {
1298       ld(R0, (int)(signed short)stdoffset, R1_SP);
1299     } else {
1300       std(R0,(int)(signed short)stdoffset, R1_SP);
1301     }
1302   } else if (is_simm(stdoffset, 31)) {
1303     const int hi = MacroAssembler::largeoffset_si16_si16_hi(stdoffset);
1304     const int lo = MacroAssembler::largeoffset_si16_si16_lo(stdoffset);
1305 
1306     Register tmp = R11;
1307     addis(tmp, R1_SP, hi);
1308     if (UseLoadInstructionsForStackBangingPPC64) {
1309       ld(R0,  lo, tmp);
1310     } else {
1311       std(R0, lo, tmp);
1312     }
1313   } else {
1314     ShouldNotReachHere();
1315   }
1316 }
1317 
1318 // If instruction is a stack bang of the form
1319 //    std    R0,    x(Ry),       (see bang_stack_with_offset())
1320 //    stdu   R1_SP, x(R1_SP),    (see push_frame(), resize_frame())
1321 // or stdux  R1_SP, Rx, R1_SP    (see push_frame(), resize_frame())
1322 // return the banged address. Otherwise, return 0.
1323 address MacroAssembler::get_stack_bang_address(int instruction, void *ucontext) {
1324 #ifdef LINUX
1325   ucontext_t* uc = (ucontext_t*) ucontext;
1326   int rs = inv_rs_field(instruction);
1327   int ra = inv_ra_field(instruction);
1328   if (   (is_ld(instruction)   && rs == 0 &&  UseLoadInstructionsForStackBangingPPC64)
1329       || (is_std(instruction)  && rs == 0 && !UseLoadInstructionsForStackBangingPPC64)
1330       || (is_stdu(instruction) && rs == 1)) {
1331     int ds = inv_ds_field(instruction);
1332     // return banged address
1333     return ds+(address)uc->uc_mcontext.regs->gpr[ra];
1334   } else if (is_stdux(instruction) && rs == 1) {
1335     int rb = inv_rb_field(instruction);
1336     address sp = (address)uc->uc_mcontext.regs->gpr[1];
1337     long rb_val = (long)uc->uc_mcontext.regs->gpr[rb];
1338     return ra != 1 || rb_val >= 0 ? NULL         // not a stack bang
1339                                   : sp + rb_val; // banged address
1340   }
1341   return NULL; // not a stack bang
1342 #else
1343   // workaround not needed on !LINUX :-)
1344   ShouldNotCallThis();
1345   return NULL;
1346 #endif
1347 }
1348 
1349 // CmpxchgX sets condition register to cmpX(current, compare).
1350 void MacroAssembler::cmpxchgw(ConditionRegister flag, Register dest_current_value,
1351                               Register compare_value, Register exchange_value,
1352                               Register addr_base, int semantics, bool cmpxchgx_hint,
1353                               Register int_flag_success, bool contention_hint) {
1354   Label retry;
1355   Label failed;
1356   Label done;
1357 
1358   // Save one branch if result is returned via register and
1359   // result register is different from the other ones.
1360   bool use_result_reg    = (int_flag_success != noreg);
1361   bool preset_result_reg = (int_flag_success != dest_current_value && int_flag_success != compare_value &&
1362                             int_flag_success != exchange_value && int_flag_success != addr_base);
1363 
1364   // release/fence semantics
1365   if (semantics & MemBarRel) {
1366     release();
1367   }
1368 
1369   if (use_result_reg && preset_result_reg) {
1370     li(int_flag_success, 0); // preset (assume cas failed)
1371   }
1372 
1373   // Add simple guard in order to reduce risk of starving under high contention (recommended by IBM).
1374   if (contention_hint) { // Don't try to reserve if cmp fails.
1375     lwz(dest_current_value, 0, addr_base);
1376     cmpw(flag, dest_current_value, compare_value);
1377     bne(flag, failed);
1378   }
1379 
1380   // atomic emulation loop
1381   bind(retry);
1382 
1383   lwarx(dest_current_value, addr_base, cmpxchgx_hint);
1384   cmpw(flag, dest_current_value, compare_value);
1385   if (UseStaticBranchPredictionInCompareAndSwapPPC64) {
1386     bne_predict_not_taken(flag, failed);
1387   } else {
1388     bne(                  flag, failed);
1389   }
1390   // branch to done  => (flag == ne), (dest_current_value != compare_value)
1391   // fall through    => (flag == eq), (dest_current_value == compare_value)
1392 
1393   stwcx_(exchange_value, addr_base);
1394   if (UseStaticBranchPredictionInCompareAndSwapPPC64) {
1395     bne_predict_not_taken(CCR0, retry); // StXcx_ sets CCR0.
1396   } else {
1397     bne(                  CCR0, retry); // StXcx_ sets CCR0.
1398   }
1399   // fall through    => (flag == eq), (dest_current_value == compare_value), (swapped)
1400 
1401   // Result in register (must do this at the end because int_flag_success can be the
1402   // same register as one above).
1403   if (use_result_reg) {
1404     li(int_flag_success, 1);
1405   }
1406 
1407   if (semantics & MemBarFenceAfter) {
1408     fence();
1409   } else if (semantics & MemBarAcq) {
1410     isync();
1411   }
1412 
1413   if (use_result_reg && !preset_result_reg) {
1414     b(done);
1415   }
1416 
1417   bind(failed);
1418   if (use_result_reg && !preset_result_reg) {
1419     li(int_flag_success, 0);
1420   }
1421 
1422   bind(done);
1423   // (flag == ne) => (dest_current_value != compare_value), (!swapped)
1424   // (flag == eq) => (dest_current_value == compare_value), ( swapped)
1425 }
1426 
1427 // Preforms atomic compare exchange:
1428 //   if (compare_value == *addr_base)
1429 //     *addr_base = exchange_value
1430 //     int_flag_success = 1;
1431 //   else
1432 //     int_flag_success = 0;
1433 //
1434 // ConditionRegister flag       = cmp(compare_value, *addr_base)
1435 // Register dest_current_value  = *addr_base
1436 // Register compare_value       Used to compare with value in memory
1437 // Register exchange_value      Written to memory if compare_value == *addr_base
1438 // Register addr_base           The memory location to compareXChange
1439 // Register int_flag_success    Set to 1 if exchange_value was written to *addr_base
1440 //
1441 // To avoid the costly compare exchange the value is tested beforehand.
1442 // Several special cases exist to avoid that unnecessary information is generated.
1443 //
1444 void MacroAssembler::cmpxchgd(ConditionRegister flag,
1445                               Register dest_current_value, Register compare_value, Register exchange_value,
1446                               Register addr_base, int semantics, bool cmpxchgx_hint,
1447                               Register int_flag_success, Label* failed_ext, bool contention_hint) {
1448   Label retry;
1449   Label failed_int;
1450   Label& failed = (failed_ext != NULL) ? *failed_ext : failed_int;
1451   Label done;
1452 
1453   // Save one branch if result is returned via register and result register is different from the other ones.
1454   bool use_result_reg    = (int_flag_success!=noreg);
1455   bool preset_result_reg = (int_flag_success!=dest_current_value && int_flag_success!=compare_value &&
1456                             int_flag_success!=exchange_value && int_flag_success!=addr_base);
1457   assert(int_flag_success == noreg || failed_ext == NULL, "cannot have both");
1458 
1459   // release/fence semantics
1460   if (semantics & MemBarRel) {
1461     release();
1462   }
1463 
1464   if (use_result_reg && preset_result_reg) {
1465     li(int_flag_success, 0); // preset (assume cas failed)
1466   }
1467 
1468   // Add simple guard in order to reduce risk of starving under high contention (recommended by IBM).
1469   if (contention_hint) { // Don't try to reserve if cmp fails.
1470     ld(dest_current_value, 0, addr_base);
1471     cmpd(flag, dest_current_value, compare_value);
1472     bne(flag, failed);
1473   }
1474 
1475   // atomic emulation loop
1476   bind(retry);
1477 
1478   ldarx(dest_current_value, addr_base, cmpxchgx_hint);
1479   cmpd(flag, dest_current_value, compare_value);
1480   if (UseStaticBranchPredictionInCompareAndSwapPPC64) {
1481     bne_predict_not_taken(flag, failed);
1482   } else {
1483     bne(                  flag, failed);
1484   }
1485 
1486   stdcx_(exchange_value, addr_base);
1487   if (UseStaticBranchPredictionInCompareAndSwapPPC64) {
1488     bne_predict_not_taken(CCR0, retry); // stXcx_ sets CCR0
1489   } else {
1490     bne(                  CCR0, retry); // stXcx_ sets CCR0
1491   }
1492 
1493   // result in register (must do this at the end because int_flag_success can be the same register as one above)
1494   if (use_result_reg) {
1495     li(int_flag_success, 1);
1496   }
1497 
1498   // POWER6 doesn't need isync in CAS.
1499   // Always emit isync to be on the safe side.
1500   if (semantics & MemBarFenceAfter) {
1501     fence();
1502   } else if (semantics & MemBarAcq) {
1503     isync();
1504   }
1505 
1506   if (use_result_reg && !preset_result_reg) {
1507     b(done);
1508   }
1509 
1510   bind(failed_int);
1511   if (use_result_reg && !preset_result_reg) {
1512     li(int_flag_success, 0);
1513   }
1514 
1515   bind(done);
1516   // (flag == ne) => (dest_current_value != compare_value), (!swapped)
1517   // (flag == eq) => (dest_current_value == compare_value), ( swapped)
1518 }
1519 
1520 // Look up the method for a megamorphic invokeinterface call.
1521 // The target method is determined by <intf_klass, itable_index>.
1522 // The receiver klass is in recv_klass.
1523 // On success, the result will be in method_result, and execution falls through.
1524 // On failure, execution transfers to the given label.
1525 void MacroAssembler::lookup_interface_method(Register recv_klass,
1526                                              Register intf_klass,
1527                                              RegisterOrConstant itable_index,
1528                                              Register method_result,
1529                                              Register scan_temp,
1530                                              Register sethi_temp,
1531                                              Label& L_no_such_interface) {
1532   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
1533   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
1534          "caller must use same register for non-constant itable index as for method");
1535 
1536   // Compute start of first itableOffsetEntry (which is at the end of the vtable).
1537   int vtable_base = InstanceKlass::vtable_start_offset() * wordSize;
1538   int itentry_off = itableMethodEntry::method_offset_in_bytes();
1539   int logMEsize   = exact_log2(itableMethodEntry::size() * wordSize);
1540   int scan_step   = itableOffsetEntry::size() * wordSize;
1541   int log_vte_size= exact_log2(vtableEntry::size() * wordSize);
1542 
1543   lwz(scan_temp, InstanceKlass::vtable_length_offset() * wordSize, recv_klass);
1544   // %%% We should store the aligned, prescaled offset in the klassoop.
1545   // Then the next several instructions would fold away.
1546 
1547   sldi(scan_temp, scan_temp, log_vte_size);
1548   addi(scan_temp, scan_temp, vtable_base);
1549   add(scan_temp, recv_klass, scan_temp);
1550 
1551   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
1552   if (itable_index.is_register()) {
1553     Register itable_offset = itable_index.as_register();
1554     sldi(itable_offset, itable_offset, logMEsize);
1555     if (itentry_off) addi(itable_offset, itable_offset, itentry_off);
1556     add(recv_klass, itable_offset, recv_klass);
1557   } else {
1558     long itable_offset = (long)itable_index.as_constant();
1559     load_const_optimized(sethi_temp, (itable_offset<<logMEsize)+itentry_off); // static address, no relocation
1560     add(recv_klass, sethi_temp, recv_klass);
1561   }
1562 
1563   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
1564   //   if (scan->interface() == intf) {
1565   //     result = (klass + scan->offset() + itable_index);
1566   //   }
1567   // }
1568   Label search, found_method;
1569 
1570   for (int peel = 1; peel >= 0; peel--) {
1571     // %%%% Could load both offset and interface in one ldx, if they were
1572     // in the opposite order. This would save a load.
1573     ld(method_result, itableOffsetEntry::interface_offset_in_bytes(), scan_temp);
1574 
1575     // Check that this entry is non-null. A null entry means that
1576     // the receiver class doesn't implement the interface, and wasn't the
1577     // same as when the caller was compiled.
1578     cmpd(CCR0, method_result, intf_klass);
1579 
1580     if (peel) {
1581       beq(CCR0, found_method);
1582     } else {
1583       bne(CCR0, search);
1584       // (invert the test to fall through to found_method...)
1585     }
1586 
1587     if (!peel) break;
1588 
1589     bind(search);
1590 
1591     cmpdi(CCR0, method_result, 0);
1592     beq(CCR0, L_no_such_interface);
1593     addi(scan_temp, scan_temp, scan_step);
1594   }
1595 
1596   bind(found_method);
1597 
1598   // Got a hit.
1599   int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
1600   lwz(scan_temp, ito_offset, scan_temp);
1601   ldx(method_result, scan_temp, recv_klass);
1602 }
1603 
1604 // virtual method calling
1605 void MacroAssembler::lookup_virtual_method(Register recv_klass,
1606                                            RegisterOrConstant vtable_index,
1607                                            Register method_result) {
1608 
1609   assert_different_registers(recv_klass, method_result, vtable_index.register_or_noreg());
1610 
1611   const int base = InstanceKlass::vtable_start_offset() * wordSize;
1612   assert(vtableEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
1613 
1614   if (vtable_index.is_register()) {
1615     sldi(vtable_index.as_register(), vtable_index.as_register(), LogBytesPerWord);
1616     add(recv_klass, vtable_index.as_register(), recv_klass);
1617   } else {
1618     addi(recv_klass, recv_klass, vtable_index.as_constant() << LogBytesPerWord);
1619   }
1620   ld(R19_method, base + vtableEntry::method_offset_in_bytes(), recv_klass);
1621 }
1622 
1623 /////////////////////////////////////////// subtype checking ////////////////////////////////////////////
1624 
1625 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
1626                                                    Register super_klass,
1627                                                    Register temp1_reg,
1628                                                    Register temp2_reg,
1629                                                    Label& L_success,
1630                                                    Label& L_failure) {
1631 
1632   const Register check_cache_offset = temp1_reg;
1633   const Register cached_super       = temp2_reg;
1634 
1635   assert_different_registers(sub_klass, super_klass, check_cache_offset, cached_super);
1636 
1637   int sco_offset = in_bytes(Klass::super_check_offset_offset());
1638   int sc_offset  = in_bytes(Klass::secondary_super_cache_offset());
1639 
1640   // If the pointers are equal, we are done (e.g., String[] elements).
1641   // This self-check enables sharing of secondary supertype arrays among
1642   // non-primary types such as array-of-interface. Otherwise, each such
1643   // type would need its own customized SSA.
1644   // We move this check to the front of the fast path because many
1645   // type checks are in fact trivially successful in this manner,
1646   // so we get a nicely predicted branch right at the start of the check.
1647   cmpd(CCR0, sub_klass, super_klass);
1648   beq(CCR0, L_success);
1649 
1650   // Check the supertype display:
1651   lwz(check_cache_offset, sco_offset, super_klass);
1652   // The loaded value is the offset from KlassOopDesc.
1653 
1654   ldx(cached_super, check_cache_offset, sub_klass);
1655   cmpd(CCR0, cached_super, super_klass);
1656   beq(CCR0, L_success);
1657 
1658   // This check has worked decisively for primary supers.
1659   // Secondary supers are sought in the super_cache ('super_cache_addr').
1660   // (Secondary supers are interfaces and very deeply nested subtypes.)
1661   // This works in the same check above because of a tricky aliasing
1662   // between the super_cache and the primary super display elements.
1663   // (The 'super_check_addr' can address either, as the case requires.)
1664   // Note that the cache is updated below if it does not help us find
1665   // what we need immediately.
1666   // So if it was a primary super, we can just fail immediately.
1667   // Otherwise, it's the slow path for us (no success at this point).
1668 
1669   cmpwi(CCR0, check_cache_offset, sc_offset);
1670   bne(CCR0, L_failure);
1671   // bind(slow_path); // fallthru
1672 }
1673 
1674 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
1675                                                    Register super_klass,
1676                                                    Register temp1_reg,
1677                                                    Register temp2_reg,
1678                                                    Label* L_success,
1679                                                    Register result_reg) {
1680   const Register array_ptr = temp1_reg; // current value from cache array
1681   const Register temp      = temp2_reg;
1682 
1683   assert_different_registers(sub_klass, super_klass, array_ptr, temp);
1684 
1685   int source_offset = in_bytes(Klass::secondary_supers_offset());
1686   int target_offset = in_bytes(Klass::secondary_super_cache_offset());
1687 
1688   int length_offset = Array<Klass*>::length_offset_in_bytes();
1689   int base_offset   = Array<Klass*>::base_offset_in_bytes();
1690 
1691   Label hit, loop, failure, fallthru;
1692 
1693   ld(array_ptr, source_offset, sub_klass);
1694 
1695   //assert(4 == arrayOopDesc::length_length_in_bytes(), "precondition violated.");
1696   lwz(temp, length_offset, array_ptr);
1697   cmpwi(CCR0, temp, 0);
1698   beq(CCR0, result_reg!=noreg ? failure : fallthru); // length 0
1699 
1700   mtctr(temp); // load ctr
1701 
1702   bind(loop);
1703   // Oops in table are NO MORE compressed.
1704   ld(temp, base_offset, array_ptr);
1705   cmpd(CCR0, temp, super_klass);
1706   beq(CCR0, hit);
1707   addi(array_ptr, array_ptr, BytesPerWord);
1708   bdnz(loop);
1709 
1710   bind(failure);
1711   if (result_reg!=noreg) li(result_reg, 1); // load non-zero result (indicates a miss)
1712   b(fallthru);
1713 
1714   bind(hit);
1715   std(super_klass, target_offset, sub_klass); // save result to cache
1716   if (result_reg != noreg) li(result_reg, 0); // load zero result (indicates a hit)
1717   if (L_success != NULL) b(*L_success);
1718 
1719   bind(fallthru);
1720 }
1721 
1722 // Try fast path, then go to slow one if not successful
1723 void MacroAssembler::check_klass_subtype(Register sub_klass,
1724                          Register super_klass,
1725                          Register temp1_reg,
1726                          Register temp2_reg,
1727                          Label& L_success) {
1728   Label L_failure;
1729   check_klass_subtype_fast_path(sub_klass, super_klass, temp1_reg, temp2_reg, L_success, L_failure);
1730   check_klass_subtype_slow_path(sub_klass, super_klass, temp1_reg, temp2_reg, &L_success);
1731   bind(L_failure); // Fallthru if not successful.
1732 }
1733 
1734 void MacroAssembler::check_method_handle_type(Register mtype_reg, Register mh_reg,
1735                                               Register temp_reg,
1736                                               Label& wrong_method_type) {
1737   assert_different_registers(mtype_reg, mh_reg, temp_reg);
1738   // Compare method type against that of the receiver.
1739   load_heap_oop_not_null(temp_reg, delayed_value(java_lang_invoke_MethodHandle::type_offset_in_bytes, temp_reg), mh_reg);
1740   cmpd(CCR0, temp_reg, mtype_reg);
1741   bne(CCR0, wrong_method_type);
1742 }
1743 
1744 RegisterOrConstant MacroAssembler::argument_offset(RegisterOrConstant arg_slot,
1745                                                    Register temp_reg,
1746                                                    int extra_slot_offset) {
1747   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
1748   int stackElementSize = Interpreter::stackElementSize;
1749   int offset = extra_slot_offset * stackElementSize;
1750   if (arg_slot.is_constant()) {
1751     offset += arg_slot.as_constant() * stackElementSize;
1752     return offset;
1753   } else {
1754     assert(temp_reg != noreg, "must specify");
1755     sldi(temp_reg, arg_slot.as_register(), exact_log2(stackElementSize));
1756     if (offset != 0)
1757       addi(temp_reg, temp_reg, offset);
1758     return temp_reg;
1759   }
1760 }
1761 
1762 void MacroAssembler::biased_locking_enter(ConditionRegister cr_reg, Register obj_reg,
1763                                           Register mark_reg, Register temp_reg,
1764                                           Register temp2_reg, Label& done, Label* slow_case) {
1765   assert(UseBiasedLocking, "why call this otherwise?");
1766 
1767 #ifdef ASSERT
1768   assert_different_registers(obj_reg, mark_reg, temp_reg, temp2_reg);
1769 #endif
1770 
1771   Label cas_label;
1772 
1773   // Branch to done if fast path fails and no slow_case provided.
1774   Label *slow_case_int = (slow_case != NULL) ? slow_case : &done;
1775 
1776   // Biased locking
1777   // See whether the lock is currently biased toward our thread and
1778   // whether the epoch is still valid
1779   // Note that the runtime guarantees sufficient alignment of JavaThread
1780   // pointers to allow age to be placed into low bits
1781   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits,
1782          "biased locking makes assumptions about bit layout");
1783 
1784   if (PrintBiasedLockingStatistics) {
1785     load_const(temp_reg, (address) BiasedLocking::total_entry_count_addr(), temp2_reg);
1786     lwz(temp2_reg, 0, temp_reg);
1787     addi(temp2_reg, temp2_reg, 1);
1788     stw(temp2_reg, 0, temp_reg);
1789   }
1790 
1791   andi(temp_reg, mark_reg, markOopDesc::biased_lock_mask_in_place);
1792   cmpwi(cr_reg, temp_reg, markOopDesc::biased_lock_pattern);
1793   bne(cr_reg, cas_label);
1794 
1795   load_klass(temp_reg, obj_reg);
1796 
1797   load_const_optimized(temp2_reg, ~((int) markOopDesc::age_mask_in_place));
1798   ld(temp_reg, in_bytes(Klass::prototype_header_offset()), temp_reg);
1799   orr(temp_reg, R16_thread, temp_reg);
1800   xorr(temp_reg, mark_reg, temp_reg);
1801   andr(temp_reg, temp_reg, temp2_reg);
1802   cmpdi(cr_reg, temp_reg, 0);
1803   if (PrintBiasedLockingStatistics) {
1804     Label l;
1805     bne(cr_reg, l);
1806     load_const(mark_reg, (address) BiasedLocking::biased_lock_entry_count_addr());
1807     lwz(temp2_reg, 0, mark_reg);
1808     addi(temp2_reg, temp2_reg, 1);
1809     stw(temp2_reg, 0, mark_reg);
1810     // restore mark_reg
1811     ld(mark_reg, oopDesc::mark_offset_in_bytes(), obj_reg);
1812     bind(l);
1813   }
1814   beq(cr_reg, done);
1815 
1816   Label try_revoke_bias;
1817   Label try_rebias;
1818 
1819   // At this point we know that the header has the bias pattern and
1820   // that we are not the bias owner in the current epoch. We need to
1821   // figure out more details about the state of the header in order to
1822   // know what operations can be legally performed on the object's
1823   // header.
1824 
1825   // If the low three bits in the xor result aren't clear, that means
1826   // the prototype header is no longer biased and we have to revoke
1827   // the bias on this object.
1828   andi(temp2_reg, temp_reg, markOopDesc::biased_lock_mask_in_place);
1829   cmpwi(cr_reg, temp2_reg, 0);
1830   bne(cr_reg, try_revoke_bias);
1831 
1832   // Biasing is still enabled for this data type. See whether the
1833   // epoch of the current bias is still valid, meaning that the epoch
1834   // bits of the mark word are equal to the epoch bits of the
1835   // prototype header. (Note that the prototype header's epoch bits
1836   // only change at a safepoint.) If not, attempt to rebias the object
1837   // toward the current thread. Note that we must be absolutely sure
1838   // that the current epoch is invalid in order to do this because
1839   // otherwise the manipulations it performs on the mark word are
1840   // illegal.
1841 
1842   int shift_amount = 64 - markOopDesc::epoch_shift;
1843   // rotate epoch bits to right (little) end and set other bits to 0
1844   // [ big part | epoch | little part ] -> [ 0..0 | epoch ]
1845   rldicl_(temp2_reg, temp_reg, shift_amount, 64 - markOopDesc::epoch_bits);
1846   // branch if epoch bits are != 0, i.e. they differ, because the epoch has been incremented
1847   bne(CCR0, try_rebias);
1848 
1849   // The epoch of the current bias is still valid but we know nothing
1850   // about the owner; it might be set or it might be clear. Try to
1851   // acquire the bias of the object using an atomic operation. If this
1852   // fails we will go in to the runtime to revoke the object's bias.
1853   // Note that we first construct the presumed unbiased header so we
1854   // don't accidentally blow away another thread's valid bias.
1855   andi(mark_reg, mark_reg, (markOopDesc::biased_lock_mask_in_place |
1856                                 markOopDesc::age_mask_in_place |
1857                                 markOopDesc::epoch_mask_in_place));
1858   orr(temp_reg, R16_thread, mark_reg);
1859 
1860   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
1861 
1862   // CmpxchgX sets cr_reg to cmpX(temp2_reg, mark_reg).
1863   fence(); // TODO: replace by MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq ?
1864   cmpxchgd(/*flag=*/cr_reg, /*current_value=*/temp2_reg,
1865            /*compare_value=*/mark_reg, /*exchange_value=*/temp_reg,
1866            /*where=*/obj_reg,
1867            MacroAssembler::MemBarAcq,
1868            MacroAssembler::cmpxchgx_hint_acquire_lock(),
1869            noreg, slow_case_int); // bail out if failed
1870 
1871   // If the biasing toward our thread failed, this means that
1872   // another thread succeeded in biasing it toward itself and we
1873   // need to revoke that bias. The revocation will occur in the
1874   // interpreter runtime in the slow case.
1875   if (PrintBiasedLockingStatistics) {
1876     load_const(temp_reg, (address) BiasedLocking::anonymously_biased_lock_entry_count_addr(), temp2_reg);
1877     lwz(temp2_reg, 0, temp_reg);
1878     addi(temp2_reg, temp2_reg, 1);
1879     stw(temp2_reg, 0, temp_reg);
1880   }
1881   b(done);
1882 
1883   bind(try_rebias);
1884   // At this point we know the epoch has expired, meaning that the
1885   // current "bias owner", if any, is actually invalid. Under these
1886   // circumstances _only_, we are allowed to use the current header's
1887   // value as the comparison value when doing the cas to acquire the
1888   // bias in the current epoch. In other words, we allow transfer of
1889   // the bias from one thread to another directly in this situation.
1890   andi(temp_reg, mark_reg, markOopDesc::age_mask_in_place);
1891   orr(temp_reg, R16_thread, temp_reg);
1892   load_klass(temp2_reg, obj_reg);
1893   ld(temp2_reg, in_bytes(Klass::prototype_header_offset()), temp2_reg);
1894   orr(temp_reg, temp_reg, temp2_reg);
1895 
1896   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
1897 
1898   // CmpxchgX sets cr_reg to cmpX(temp2_reg, mark_reg).
1899   fence(); // TODO: replace by MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq ?
1900   cmpxchgd(/*flag=*/cr_reg, /*current_value=*/temp2_reg,
1901                  /*compare_value=*/mark_reg, /*exchange_value=*/temp_reg,
1902                  /*where=*/obj_reg,
1903                  MacroAssembler::MemBarAcq,
1904                  MacroAssembler::cmpxchgx_hint_acquire_lock(),
1905                  noreg, slow_case_int); // bail out if failed
1906 
1907   // If the biasing toward our thread failed, this means that
1908   // another thread succeeded in biasing it toward itself and we
1909   // need to revoke that bias. The revocation will occur in the
1910   // interpreter runtime in the slow case.
1911   if (PrintBiasedLockingStatistics) {
1912     load_const(temp_reg, (address) BiasedLocking::rebiased_lock_entry_count_addr(), temp2_reg);
1913     lwz(temp2_reg, 0, temp_reg);
1914     addi(temp2_reg, temp2_reg, 1);
1915     stw(temp2_reg, 0, temp_reg);
1916   }
1917   b(done);
1918 
1919   bind(try_revoke_bias);
1920   // The prototype mark in the klass doesn't have the bias bit set any
1921   // more, indicating that objects of this data type are not supposed
1922   // to be biased any more. We are going to try to reset the mark of
1923   // this object to the prototype value and fall through to the
1924   // CAS-based locking scheme. Note that if our CAS fails, it means
1925   // that another thread raced us for the privilege of revoking the
1926   // bias of this particular object, so it's okay to continue in the
1927   // normal locking code.
1928   load_klass(temp_reg, obj_reg);
1929   ld(temp_reg, in_bytes(Klass::prototype_header_offset()), temp_reg);
1930   andi(temp2_reg, mark_reg, markOopDesc::age_mask_in_place);
1931   orr(temp_reg, temp_reg, temp2_reg);
1932 
1933   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
1934 
1935   // CmpxchgX sets cr_reg to cmpX(temp2_reg, mark_reg).
1936   fence(); // TODO: replace by MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq ?
1937   cmpxchgd(/*flag=*/cr_reg, /*current_value=*/temp2_reg,
1938                  /*compare_value=*/mark_reg, /*exchange_value=*/temp_reg,
1939                  /*where=*/obj_reg,
1940                  MacroAssembler::MemBarAcq,
1941                  MacroAssembler::cmpxchgx_hint_acquire_lock());
1942 
1943   // reload markOop in mark_reg before continuing with lightweight locking
1944   ld(mark_reg, oopDesc::mark_offset_in_bytes(), obj_reg);
1945 
1946   // Fall through to the normal CAS-based lock, because no matter what
1947   // the result of the above CAS, some thread must have succeeded in
1948   // removing the bias bit from the object's header.
1949   if (PrintBiasedLockingStatistics) {
1950     Label l;
1951     bne(cr_reg, l);
1952     load_const(temp_reg, (address) BiasedLocking::revoked_lock_entry_count_addr(), temp2_reg);
1953     lwz(temp2_reg, 0, temp_reg);
1954     addi(temp2_reg, temp2_reg, 1);
1955     stw(temp2_reg, 0, temp_reg);
1956     bind(l);
1957   }
1958 
1959   bind(cas_label);
1960 }
1961 
1962 void MacroAssembler::biased_locking_exit (ConditionRegister cr_reg, Register mark_addr, Register temp_reg, Label& done) {
1963   // Check for biased locking unlock case, which is a no-op
1964   // Note: we do not have to check the thread ID for two reasons.
1965   // First, the interpreter checks for IllegalMonitorStateException at
1966   // a higher level. Second, if the bias was revoked while we held the
1967   // lock, the object could not be rebiased toward another thread, so
1968   // the bias bit would be clear.
1969 
1970   ld(temp_reg, 0, mark_addr);
1971   andi(temp_reg, temp_reg, markOopDesc::biased_lock_mask_in_place);
1972 
1973   cmpwi(cr_reg, temp_reg, markOopDesc::biased_lock_pattern);
1974   beq(cr_reg, done);
1975 }
1976 
1977 // "The box" is the space on the stack where we copy the object mark.
1978 void MacroAssembler::compiler_fast_lock_object(ConditionRegister flag, Register oop, Register box,
1979                                                Register temp, Register displaced_header, Register current_header) {
1980   assert_different_registers(oop, box, temp, displaced_header, current_header);
1981   assert(flag != CCR0, "bad condition register");
1982   Label cont;
1983   Label object_has_monitor;
1984   Label cas_failed;
1985 
1986   // Load markOop from object into displaced_header.
1987   ld(displaced_header, oopDesc::mark_offset_in_bytes(), oop);
1988 
1989 
1990   // Always do locking in runtime.
1991   if (EmitSync & 0x01) {
1992     cmpdi(flag, oop, 0); // Oop can't be 0 here => always false.
1993     return;
1994   }
1995 
1996   if (UseBiasedLocking) {
1997     biased_locking_enter(flag, oop, displaced_header, temp, current_header, cont);
1998   }
1999 
2000   // Handle existing monitor.
2001   if ((EmitSync & 0x02) == 0) {
2002     // The object has an existing monitor iff (mark & monitor_value) != 0.
2003     andi_(temp, displaced_header, markOopDesc::monitor_value);
2004     bne(CCR0, object_has_monitor);
2005   }
2006 
2007   // Set displaced_header to be (markOop of object | UNLOCK_VALUE).
2008   ori(displaced_header, displaced_header, markOopDesc::unlocked_value);
2009 
2010   // Load Compare Value application register.
2011 
2012   // Initialize the box. (Must happen before we update the object mark!)
2013   std(displaced_header, BasicLock::displaced_header_offset_in_bytes(), box);
2014 
2015   // Must fence, otherwise, preceding store(s) may float below cmpxchg.
2016   // Compare object markOop with mark and if equal exchange scratch1 with object markOop.
2017   // CmpxchgX sets cr_reg to cmpX(current, displaced).
2018   membar(Assembler::StoreStore);
2019   cmpxchgd(/*flag=*/flag,
2020            /*current_value=*/current_header,
2021            /*compare_value=*/displaced_header,
2022            /*exchange_value=*/box,
2023            /*where=*/oop,
2024            MacroAssembler::MemBarAcq,
2025            MacroAssembler::cmpxchgx_hint_acquire_lock(),
2026            noreg,
2027            &cas_failed);
2028   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
2029 
2030   // If the compare-and-exchange succeeded, then we found an unlocked
2031   // object and we have now locked it.
2032   b(cont);
2033 
2034   bind(cas_failed);
2035   // We did not see an unlocked object so try the fast recursive case.
2036 
2037   // Check if the owner is self by comparing the value in the markOop of object
2038   // (current_header) with the stack pointer.
2039   sub(current_header, current_header, R1_SP);
2040   load_const_optimized(temp, (address) (~(os::vm_page_size()-1) |
2041                                         markOopDesc::lock_mask_in_place));
2042 
2043   and_(R0/*==0?*/, current_header, temp);
2044   // If condition is true we are cont and hence we can store 0 as the
2045   // displaced header in the box, which indicates that it is a recursive lock.
2046   mcrf(flag,CCR0);
2047   std(R0/*==0, perhaps*/, BasicLock::displaced_header_offset_in_bytes(), box);
2048 
2049   // Handle existing monitor.
2050   if ((EmitSync & 0x02) == 0) {
2051     b(cont);
2052 
2053     bind(object_has_monitor);
2054     // The object's monitor m is unlocked iff m->owner == NULL,
2055     // otherwise m->owner may contain a thread or a stack address.
2056     //
2057     // Try to CAS m->owner from NULL to current thread.
2058     addi(temp, displaced_header, ObjectMonitor::owner_offset_in_bytes()-markOopDesc::monitor_value);
2059     li(displaced_header, 0);
2060     // CmpxchgX sets flag to cmpX(current, displaced).
2061     cmpxchgd(/*flag=*/flag,
2062              /*current_value=*/current_header,
2063              /*compare_value=*/displaced_header,
2064              /*exchange_value=*/R16_thread,
2065              /*where=*/temp,
2066              MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq,
2067              MacroAssembler::cmpxchgx_hint_acquire_lock());
2068 
2069     // Store a non-null value into the box.
2070     std(box, BasicLock::displaced_header_offset_in_bytes(), box);
2071 
2072 #   ifdef ASSERT
2073     bne(flag, cont);
2074     // We have acquired the monitor, check some invariants.
2075     addi(/*monitor=*/temp, temp, -ObjectMonitor::owner_offset_in_bytes());
2076     // Invariant 1: _recursions should be 0.
2077     //assert(ObjectMonitor::recursions_size_in_bytes() == 8, "unexpected size");
2078     asm_assert_mem8_is_zero(ObjectMonitor::recursions_offset_in_bytes(), temp,
2079                             "monitor->_recursions should be 0", -1);
2080     // Invariant 2: OwnerIsThread shouldn't be 0.
2081     //assert(ObjectMonitor::OwnerIsThread_size_in_bytes() == 4, "unexpected size");
2082     //asm_assert_mem4_isnot_zero(ObjectMonitor::OwnerIsThread_offset_in_bytes(), temp,
2083     //                           "monitor->OwnerIsThread shouldn't be 0", -1);
2084 #   endif
2085   }
2086 
2087   bind(cont);
2088   // flag == EQ indicates success
2089   // flag == NE indicates failure
2090 }
2091 
2092 void MacroAssembler::compiler_fast_unlock_object(ConditionRegister flag, Register oop, Register box,
2093                                                  Register temp, Register displaced_header, Register current_header) {
2094   assert_different_registers(oop, box, temp, displaced_header, current_header);
2095   assert(flag != CCR0, "bad condition register");
2096   Label cont;
2097   Label object_has_monitor;
2098 
2099   // Always do locking in runtime.
2100   if (EmitSync & 0x01) {
2101     cmpdi(flag, oop, 0); // Oop can't be 0 here => always false.
2102     return;
2103   }
2104 
2105   if (UseBiasedLocking) {
2106     biased_locking_exit(flag, oop, current_header, cont);
2107   }
2108 
2109   // Find the lock address and load the displaced header from the stack.
2110   ld(displaced_header, BasicLock::displaced_header_offset_in_bytes(), box);
2111 
2112   // If the displaced header is 0, we have a recursive unlock.
2113   cmpdi(flag, displaced_header, 0);
2114   beq(flag, cont);
2115 
2116   // Handle existing monitor.
2117   if ((EmitSync & 0x02) == 0) {
2118     // The object has an existing monitor iff (mark & monitor_value) != 0.
2119     ld(current_header, oopDesc::mark_offset_in_bytes(), oop);
2120     andi(temp, current_header, markOopDesc::monitor_value);
2121     cmpdi(flag, temp, 0);
2122     bne(flag, object_has_monitor);
2123   }
2124 
2125 
2126   // Check if it is still a light weight lock, this is is true if we see
2127   // the stack address of the basicLock in the markOop of the object.
2128   // Cmpxchg sets flag to cmpd(current_header, box).
2129   cmpxchgd(/*flag=*/flag,
2130            /*current_value=*/current_header,
2131            /*compare_value=*/box,
2132            /*exchange_value=*/displaced_header,
2133            /*where=*/oop,
2134            MacroAssembler::MemBarRel,
2135            MacroAssembler::cmpxchgx_hint_release_lock(),
2136            noreg,
2137            &cont);
2138 
2139   assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
2140 
2141   // Handle existing monitor.
2142   if ((EmitSync & 0x02) == 0) {
2143     b(cont);
2144 
2145     bind(object_has_monitor);
2146     addi(current_header, current_header, -markOopDesc::monitor_value); // monitor
2147     ld(temp,             ObjectMonitor::owner_offset_in_bytes(), current_header);
2148     ld(displaced_header, ObjectMonitor::recursions_offset_in_bytes(), current_header);
2149     xorr(temp, R16_thread, temp);      // Will be 0 if we are the owner.
2150     orr(temp, temp, displaced_header); // Will be 0 if there are 0 recursions.
2151     cmpdi(flag, temp, 0);
2152     bne(flag, cont);
2153 
2154     ld(temp,             ObjectMonitor::EntryList_offset_in_bytes(), current_header);
2155     ld(displaced_header, ObjectMonitor::cxq_offset_in_bytes(), current_header);
2156     orr(temp, temp, displaced_header); // Will be 0 if both are 0.
2157     cmpdi(flag, temp, 0);
2158     bne(flag, cont);
2159     release();
2160     std(temp, ObjectMonitor::owner_offset_in_bytes(), current_header);
2161   }
2162 
2163   bind(cont);
2164   // flag == EQ indicates success
2165   // flag == NE indicates failure
2166 }
2167 
2168 // Write serialization page so VM thread can do a pseudo remote membar.
2169 // We use the current thread pointer to calculate a thread specific
2170 // offset to write to within the page. This minimizes bus traffic
2171 // due to cache line collision.
2172 void MacroAssembler::serialize_memory(Register thread, Register tmp1, Register tmp2) {
2173   srdi(tmp2, thread, os::get_serialize_page_shift_count());
2174 
2175   int mask = os::vm_page_size() - sizeof(int);
2176   if (Assembler::is_simm(mask, 16)) {
2177     andi(tmp2, tmp2, mask);
2178   } else {
2179     lis(tmp1, (int)((signed short) (mask >> 16)));
2180     ori(tmp1, tmp1, mask & 0x0000ffff);
2181     andr(tmp2, tmp2, tmp1);
2182   }
2183 
2184   load_const(tmp1, (long) os::get_memory_serialize_page());
2185   release();
2186   stwx(R0, tmp1, tmp2);
2187 }
2188 
2189 
2190 // GC barrier helper macros
2191 
2192 // Write the card table byte if needed.
2193 void MacroAssembler::card_write_barrier_post(Register Rstore_addr, Register Rnew_val, Register Rtmp) {
2194   CardTableModRefBS* bs = (CardTableModRefBS*) Universe::heap()->barrier_set();
2195   assert(bs->kind() == BarrierSet::CardTableModRef ||
2196          bs->kind() == BarrierSet::CardTableExtension, "wrong barrier");
2197 #ifdef ASSERT
2198   cmpdi(CCR0, Rnew_val, 0);
2199   asm_assert_ne("null oop not allowed", 0x321);
2200 #endif
2201   card_table_write(bs->byte_map_base, Rtmp, Rstore_addr);
2202 }
2203 
2204 // Write the card table byte.
2205 void MacroAssembler::card_table_write(jbyte* byte_map_base, Register Rtmp, Register Robj) {
2206   assert_different_registers(Robj, Rtmp, R0);
2207   load_const_optimized(Rtmp, (address)byte_map_base, R0);
2208   srdi(Robj, Robj, CardTableModRefBS::card_shift);
2209   li(R0, 0); // dirty
2210   if (UseConcMarkSweepGC) membar(Assembler::StoreStore);
2211   stbx(R0, Rtmp, Robj);
2212 }
2213 
2214 #if INCLUDE_ALL_GCS
2215 // General G1 pre-barrier generator.
2216 // Goal: record the previous value if it is not null.
2217 void MacroAssembler::g1_write_barrier_pre(Register Robj, RegisterOrConstant offset, Register Rpre_val,
2218                                           Register Rtmp1, Register Rtmp2, bool needs_frame) {
2219   Label runtime, filtered;
2220 
2221   // Is marking active?
2222   if (in_bytes(PtrQueue::byte_width_of_active()) == 4) {
2223     lwz(Rtmp1, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_active()), R16_thread);
2224   } else {
2225     guarantee(in_bytes(PtrQueue::byte_width_of_active()) == 1, "Assumption");
2226     lbz(Rtmp1, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_active()), R16_thread);
2227   }
2228   cmpdi(CCR0, Rtmp1, 0);
2229   beq(CCR0, filtered);
2230 
2231   // Do we need to load the previous value?
2232   if (Robj != noreg) {
2233     // Load the previous value...
2234     if (UseCompressedOops) {
2235       lwz(Rpre_val, offset, Robj);
2236     } else {
2237       ld(Rpre_val, offset, Robj);
2238     }
2239     // Previous value has been loaded into Rpre_val.
2240   }
2241   assert(Rpre_val != noreg, "must have a real register");
2242 
2243   // Is the previous value null?
2244   cmpdi(CCR0, Rpre_val, 0);
2245   beq(CCR0, filtered);
2246 
2247   if (Robj != noreg && UseCompressedOops) {
2248     decode_heap_oop_not_null(Rpre_val);
2249   }
2250 
2251   // OK, it's not filtered, so we'll need to call enqueue. In the normal
2252   // case, pre_val will be a scratch G-reg, but there are some cases in
2253   // which it's an O-reg. In the first case, do a normal call. In the
2254   // latter, do a save here and call the frameless version.
2255 
2256   // Can we store original value in the thread's buffer?
2257   // Is index == 0?
2258   // (The index field is typed as size_t.)
2259   const Register Rbuffer = Rtmp1, Rindex = Rtmp2;
2260 
2261   ld(Rindex, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_index()), R16_thread);
2262   cmpdi(CCR0, Rindex, 0);
2263   beq(CCR0, runtime); // If index == 0, goto runtime.
2264   ld(Rbuffer, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_buf()), R16_thread);
2265 
2266   addi(Rindex, Rindex, -wordSize); // Decrement index.
2267   std(Rindex, in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_index()), R16_thread);
2268 
2269   // Record the previous value.
2270   stdx(Rpre_val, Rbuffer, Rindex);
2271   b(filtered);
2272 
2273   bind(runtime);
2274 
2275   // VM call need frame to access(write) O register.
2276   if (needs_frame) {
2277     save_LR_CR(Rtmp1);
2278     push_frame_reg_args(0, Rtmp2);
2279   }
2280 
2281   if (Rpre_val->is_volatile() && Robj == noreg) mr(R31, Rpre_val); // Save pre_val across C call if it was preloaded.
2282   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), Rpre_val, R16_thread);
2283   if (Rpre_val->is_volatile() && Robj == noreg) mr(Rpre_val, R31); // restore
2284 
2285   if (needs_frame) {
2286     pop_frame();
2287     restore_LR_CR(Rtmp1);
2288   }
2289 
2290   bind(filtered);
2291 }
2292 
2293 // General G1 post-barrier generator
2294 // Store cross-region card.
2295 void MacroAssembler::g1_write_barrier_post(Register Rstore_addr, Register Rnew_val, Register Rtmp1, Register Rtmp2, Register Rtmp3, Label *filtered_ext) {
2296   Label runtime, filtered_int;
2297   Label& filtered = (filtered_ext != NULL) ? *filtered_ext : filtered_int;
2298   assert_different_registers(Rstore_addr, Rnew_val, Rtmp1, Rtmp2);
2299 
2300   G1SATBCardTableModRefBS* bs = (G1SATBCardTableModRefBS*) Universe::heap()->barrier_set();
2301   assert(bs->kind() == BarrierSet::G1SATBCT ||
2302          bs->kind() == BarrierSet::G1SATBCTLogging, "wrong barrier");
2303 
2304   // Does store cross heap regions?
2305   if (G1RSBarrierRegionFilter) {
2306     xorr(Rtmp1, Rstore_addr, Rnew_val);
2307     srdi_(Rtmp1, Rtmp1, HeapRegion::LogOfHRGrainBytes);
2308     beq(CCR0, filtered);
2309   }
2310 
2311   // Crosses regions, storing NULL?
2312 #ifdef ASSERT
2313   cmpdi(CCR0, Rnew_val, 0);
2314   asm_assert_ne("null oop not allowed (G1)", 0x322); // Checked by caller on PPC64, so following branch is obsolete:
2315   //beq(CCR0, filtered);
2316 #endif
2317 
2318   // Storing region crossing non-NULL, is card already dirty?
2319   assert(sizeof(*bs->byte_map_base) == sizeof(jbyte), "adjust this code");
2320   const Register Rcard_addr = Rtmp1;
2321   Register Rbase = Rtmp2;
2322   load_const_optimized(Rbase, (address)bs->byte_map_base, /*temp*/ Rtmp3);
2323 
2324   srdi(Rcard_addr, Rstore_addr, CardTableModRefBS::card_shift);
2325 
2326   // Get the address of the card.
2327   lbzx(/*card value*/ Rtmp3, Rbase, Rcard_addr);
2328   cmpwi(CCR0, Rtmp3, (int)G1SATBCardTableModRefBS::g1_young_card_val());
2329   beq(CCR0, filtered);
2330 
2331   membar(Assembler::StoreLoad);
2332   lbzx(/*card value*/ Rtmp3, Rbase, Rcard_addr);  // Reload after membar.
2333   cmpwi(CCR0, Rtmp3 /* card value */, CardTableModRefBS::dirty_card_val());
2334   beq(CCR0, filtered);
2335 
2336   // Storing a region crossing, non-NULL oop, card is clean.
2337   // Dirty card and log.
2338   li(Rtmp3, CardTableModRefBS::dirty_card_val());
2339   //release(); // G1: oops are allowed to get visible after dirty marking.
2340   stbx(Rtmp3, Rbase, Rcard_addr);
2341 
2342   add(Rcard_addr, Rbase, Rcard_addr); // This is the address which needs to get enqueued.
2343   Rbase = noreg; // end of lifetime
2344 
2345   const Register Rqueue_index = Rtmp2,
2346                  Rqueue_buf   = Rtmp3;
2347   ld(Rqueue_index, in_bytes(JavaThread::dirty_card_queue_offset() + PtrQueue::byte_offset_of_index()), R16_thread);
2348   cmpdi(CCR0, Rqueue_index, 0);
2349   beq(CCR0, runtime); // index == 0 then jump to runtime
2350   ld(Rqueue_buf, in_bytes(JavaThread::dirty_card_queue_offset() + PtrQueue::byte_offset_of_buf()), R16_thread);
2351 
2352   addi(Rqueue_index, Rqueue_index, -wordSize); // decrement index
2353   std(Rqueue_index, in_bytes(JavaThread::dirty_card_queue_offset() + PtrQueue::byte_offset_of_index()), R16_thread);
2354 
2355   stdx(Rcard_addr, Rqueue_buf, Rqueue_index); // store card
2356   b(filtered);
2357 
2358   bind(runtime);
2359 
2360   // Save the live input values.
2361   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), Rcard_addr, R16_thread);
2362 
2363   bind(filtered_int);
2364 }
2365 #endif // INCLUDE_ALL_GCS
2366 
2367 // Values for last_Java_pc, and last_Java_sp must comply to the rules
2368 // in frame_ppc64.hpp.
2369 void MacroAssembler::set_last_Java_frame(Register last_Java_sp, Register last_Java_pc) {
2370   // Always set last_Java_pc and flags first because once last_Java_sp
2371   // is visible has_last_Java_frame is true and users will look at the
2372   // rest of the fields. (Note: flags should always be zero before we
2373   // get here so doesn't need to be set.)
2374 
2375   // Verify that last_Java_pc was zeroed on return to Java
2376   asm_assert_mem8_is_zero(in_bytes(JavaThread::last_Java_pc_offset()), R16_thread,
2377                           "last_Java_pc not zeroed before leaving Java", 0x200);
2378 
2379   // When returning from calling out from Java mode the frame anchor's
2380   // last_Java_pc will always be set to NULL. It is set here so that
2381   // if we are doing a call to native (not VM) that we capture the
2382   // known pc and don't have to rely on the native call having a
2383   // standard frame linkage where we can find the pc.
2384   if (last_Java_pc != noreg)
2385     std(last_Java_pc, in_bytes(JavaThread::last_Java_pc_offset()), R16_thread);
2386 
2387   // Set last_Java_sp last.
2388   std(last_Java_sp, in_bytes(JavaThread::last_Java_sp_offset()), R16_thread);
2389 }
2390 
2391 void MacroAssembler::reset_last_Java_frame(void) {
2392   asm_assert_mem8_isnot_zero(in_bytes(JavaThread::last_Java_sp_offset()),
2393                              R16_thread, "SP was not set, still zero", 0x202);
2394 
2395   BLOCK_COMMENT("reset_last_Java_frame {");
2396   li(R0, 0);
2397 
2398   // _last_Java_sp = 0
2399   std(R0, in_bytes(JavaThread::last_Java_sp_offset()), R16_thread);
2400 
2401   // _last_Java_pc = 0
2402   std(R0, in_bytes(JavaThread::last_Java_pc_offset()), R16_thread);
2403   BLOCK_COMMENT("} reset_last_Java_frame");
2404 }
2405 
2406 void MacroAssembler::set_top_ijava_frame_at_SP_as_last_Java_frame(Register sp, Register tmp1) {
2407   assert_different_registers(sp, tmp1);
2408 
2409   // sp points to a TOP_IJAVA_FRAME, retrieve frame's PC via
2410   // TOP_IJAVA_FRAME_ABI.
2411   // FIXME: assert that we really have a TOP_IJAVA_FRAME here!
2412 #ifdef CC_INTERP
2413   ld(tmp1/*pc*/, _top_ijava_frame_abi(frame_manager_lr), sp);
2414 #else
2415   address entry = pc();
2416   load_const_optimized(tmp1, entry);
2417 #endif
2418 
2419   set_last_Java_frame(/*sp=*/sp, /*pc=*/tmp1);
2420 }
2421 
2422 void MacroAssembler::get_vm_result(Register oop_result) {
2423   // Read:
2424   //   R16_thread
2425   //   R16_thread->in_bytes(JavaThread::vm_result_offset())
2426   //
2427   // Updated:
2428   //   oop_result
2429   //   R16_thread->in_bytes(JavaThread::vm_result_offset())
2430 
2431   ld(oop_result, in_bytes(JavaThread::vm_result_offset()), R16_thread);
2432   li(R0, 0);
2433   std(R0, in_bytes(JavaThread::vm_result_offset()), R16_thread);
2434 
2435   verify_oop(oop_result);
2436 }
2437 
2438 void MacroAssembler::get_vm_result_2(Register metadata_result) {
2439   // Read:
2440   //   R16_thread
2441   //   R16_thread->in_bytes(JavaThread::vm_result_2_offset())
2442   //
2443   // Updated:
2444   //   metadata_result
2445   //   R16_thread->in_bytes(JavaThread::vm_result_2_offset())
2446 
2447   ld(metadata_result, in_bytes(JavaThread::vm_result_2_offset()), R16_thread);
2448   li(R0, 0);
2449   std(R0, in_bytes(JavaThread::vm_result_2_offset()), R16_thread);
2450 }
2451 
2452 
2453 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
2454   Register current = (src != noreg) ? src : dst; // Klass is in dst if no src provided.
2455   if (Universe::narrow_klass_base() != 0) {
2456     // Use dst as temp if it is free.
2457     load_const(R0, Universe::narrow_klass_base(), (dst != current && dst != R0) ? dst : noreg);
2458     sub(dst, current, R0);
2459     current = dst;
2460   }
2461   if (Universe::narrow_klass_shift() != 0) {
2462     srdi(dst, current, Universe::narrow_klass_shift());
2463     current = dst;
2464   }
2465   mr_if_needed(dst, current); // Move may be required.
2466 }
2467 
2468 void MacroAssembler::store_klass(Register dst_oop, Register klass, Register ck) {
2469   if (UseCompressedClassPointers) {
2470     encode_klass_not_null(ck, klass);
2471     stw(ck, oopDesc::klass_offset_in_bytes(), dst_oop);
2472   } else {
2473     std(klass, oopDesc::klass_offset_in_bytes(), dst_oop);
2474   }
2475 }
2476 
2477 void MacroAssembler::store_klass_gap(Register dst_oop, Register val) {
2478   if (UseCompressedClassPointers) {
2479     if (val == noreg) {
2480       val = R0;
2481       li(val, 0);
2482     }
2483     stw(val, oopDesc::klass_gap_offset_in_bytes(), dst_oop); // klass gap if compressed
2484   }
2485 }
2486 
2487 int MacroAssembler::instr_size_for_decode_klass_not_null() {
2488   if (!UseCompressedClassPointers) return 0;
2489   int num_instrs = 1;  // shift or move
2490   if (Universe::narrow_klass_base() != 0) num_instrs = 7;  // shift + load const + add
2491   return num_instrs * BytesPerInstWord;
2492 }
2493 
2494 void MacroAssembler::decode_klass_not_null(Register dst, Register src) {
2495   if (src == noreg) src = dst;
2496   Register shifted_src = src;
2497   if (Universe::narrow_klass_shift() != 0 ||
2498       Universe::narrow_klass_base() == 0 && src != dst) {  // Move required.
2499     shifted_src = dst;
2500     sldi(shifted_src, src, Universe::narrow_klass_shift());
2501   }
2502   if (Universe::narrow_klass_base() != 0) {
2503     load_const(R0, Universe::narrow_klass_base());
2504     add(dst, shifted_src, R0);
2505   }
2506 }
2507 
2508 void MacroAssembler::load_klass(Register dst, Register src) {
2509   if (UseCompressedClassPointers) {
2510     lwz(dst, oopDesc::klass_offset_in_bytes(), src);
2511     // Attention: no null check here!
2512     decode_klass_not_null(dst, dst);
2513   } else {
2514     ld(dst, oopDesc::klass_offset_in_bytes(), src);
2515   }
2516 }
2517 
2518 void MacroAssembler::load_klass_with_trap_null_check(Register dst, Register src) {
2519   if (!os::zero_page_read_protected()) {
2520     if (TrapBasedNullChecks) {
2521       trap_null_check(src);
2522     }
2523   }
2524   load_klass(dst, src);
2525 }
2526 
2527 void MacroAssembler::reinit_heapbase(Register d, Register tmp) {
2528   if (Universe::heap() != NULL) {
2529     if (Universe::narrow_oop_base() == NULL) {
2530       Assembler::xorr(R30, R30, R30);
2531     } else {
2532       load_const(R30, Universe::narrow_ptrs_base(), tmp);
2533     }
2534   } else {
2535     load_const(R30, Universe::narrow_ptrs_base_addr(), tmp);
2536     ld(R30, 0, R30);
2537   }
2538 }
2539 
2540 // Clear Array
2541 // Kills both input registers. tmp == R0 is allowed.
2542 void MacroAssembler::clear_memory_doubleword(Register base_ptr, Register cnt_dwords, Register tmp) {
2543   // Procedure for large arrays (uses data cache block zero instruction).
2544     Label startloop, fast, fastloop, small_rest, restloop, done;
2545     const int cl_size         = VM_Version::get_cache_line_size(),
2546               cl_dwords       = cl_size>>3,
2547               cl_dw_addr_bits = exact_log2(cl_dwords),
2548               dcbz_min        = 1;                     // Min count of dcbz executions, needs to be >0.
2549 
2550 //2:
2551     cmpdi(CCR1, cnt_dwords, ((dcbz_min+1)<<cl_dw_addr_bits)-1); // Big enough? (ensure >=dcbz_min lines included).
2552     blt(CCR1, small_rest);                                      // Too small.
2553     rldicl_(tmp, base_ptr, 64-3, 64-cl_dw_addr_bits);           // Extract dword offset within first cache line.
2554     beq(CCR0, fast);                                            // Already 128byte aligned.
2555 
2556     subfic(tmp, tmp, cl_dwords);
2557     mtctr(tmp);                        // Set ctr to hit 128byte boundary (0<ctr<cl_dwords).
2558     subf(cnt_dwords, tmp, cnt_dwords); // rest.
2559     li(tmp, 0);
2560 //10:
2561   bind(startloop);                     // Clear at the beginning to reach 128byte boundary.
2562     std(tmp, 0, base_ptr);             // Clear 8byte aligned block.
2563     addi(base_ptr, base_ptr, 8);
2564     bdnz(startloop);
2565 //13:
2566   bind(fast);                                  // Clear 128byte blocks.
2567     srdi(tmp, cnt_dwords, cl_dw_addr_bits);    // Loop count for 128byte loop (>0).
2568     andi(cnt_dwords, cnt_dwords, cl_dwords-1); // Rest in dwords.
2569     mtctr(tmp);                                // Load counter.
2570 //16:
2571   bind(fastloop);
2572     dcbz(base_ptr);                    // Clear 128byte aligned block.
2573     addi(base_ptr, base_ptr, cl_size);
2574     bdnz(fastloop);
2575     if (InsertEndGroupPPC64) { endgroup(); } else { nop(); }
2576 //20:
2577   bind(small_rest);
2578     cmpdi(CCR0, cnt_dwords, 0);        // size 0?
2579     beq(CCR0, done);                   // rest == 0
2580     li(tmp, 0);
2581     mtctr(cnt_dwords);                 // Load counter.
2582 //24:
2583   bind(restloop);                      // Clear rest.
2584     std(tmp, 0, base_ptr);             // Clear 8byte aligned block.
2585     addi(base_ptr, base_ptr, 8);
2586     bdnz(restloop);
2587 //27:
2588   bind(done);
2589 }
2590 
2591 /////////////////////////////////////////// String intrinsics ////////////////////////////////////////////
2592 
2593 // Search for a single jchar in an jchar[].
2594 //
2595 // Assumes that result differs from all other registers.
2596 //
2597 // Haystack, needle are the addresses of jchar-arrays.
2598 // NeedleChar is needle[0] if it is known at compile time.
2599 // Haycnt is the length of the haystack. We assume haycnt >=1.
2600 //
2601 // Preserves haystack, haycnt, kills all other registers.
2602 //
2603 // If needle == R0, we search for the constant needleChar.
2604 void MacroAssembler::string_indexof_1(Register result, Register haystack, Register haycnt,
2605                                       Register needle, jchar needleChar,
2606                                       Register tmp1, Register tmp2) {
2607 
2608   assert_different_registers(result, haystack, haycnt, needle, tmp1, tmp2);
2609 
2610   Label L_InnerLoop, L_FinalCheck, L_Found1, L_Found2, L_Found3, L_NotFound, L_End;
2611   Register needle0 = needle, // Contains needle[0].
2612            addr = tmp1,
2613            ch1 = tmp2,
2614            ch2 = R0;
2615 
2616 //2 (variable) or 3 (const):
2617    if (needle != R0) lhz(needle0, 0, needle); // Preload needle character, needle has len==1.
2618    dcbtct(haystack, 0x00);                        // Indicate R/O access to haystack.
2619 
2620    srwi_(tmp2, haycnt, 1);   // Shift right by exact_log2(UNROLL_FACTOR).
2621    mr(addr, haystack);
2622    beq(CCR0, L_FinalCheck);
2623    mtctr(tmp2);              // Move to count register.
2624 //8:
2625   bind(L_InnerLoop);             // Main work horse (2x unrolled search loop).
2626    lhz(ch1, 0, addr);        // Load characters from haystack.
2627    lhz(ch2, 2, addr);
2628    (needle != R0) ? cmpw(CCR0, ch1, needle0) : cmplwi(CCR0, ch1, needleChar);
2629    (needle != R0) ? cmpw(CCR1, ch2, needle0) : cmplwi(CCR1, ch2, needleChar);
2630    beq(CCR0, L_Found1);   // Did we find the needle?
2631    beq(CCR1, L_Found2);
2632    addi(addr, addr, 4);
2633    bdnz(L_InnerLoop);
2634 //16:
2635   bind(L_FinalCheck);
2636    andi_(R0, haycnt, 1);
2637    beq(CCR0, L_NotFound);
2638    lhz(ch1, 0, addr);        // One position left at which we have to compare.
2639    (needle != R0) ? cmpw(CCR1, ch1, needle0) : cmplwi(CCR1, ch1, needleChar);
2640    beq(CCR1, L_Found3);
2641 //21:
2642   bind(L_NotFound);
2643    li(result, -1);           // Not found.
2644    b(L_End);
2645 
2646   bind(L_Found2);
2647    addi(addr, addr, 2);
2648 //24:
2649   bind(L_Found1);
2650   bind(L_Found3);                  // Return index ...
2651    subf(addr, haystack, addr); // relative to haystack,
2652    srdi(result, addr, 1);      // in characters.
2653   bind(L_End);
2654 }
2655 
2656 
2657 // Implementation of IndexOf for jchar arrays.
2658 //
2659 // The length of haystack and needle are not constant, i.e. passed in a register.
2660 //
2661 // Preserves registers haystack, needle.
2662 // Kills registers haycnt, needlecnt.
2663 // Assumes that result differs from all other registers.
2664 // Haystack, needle are the addresses of jchar-arrays.
2665 // Haycnt, needlecnt are the lengths of them, respectively.
2666 //
2667 // Needlecntval must be zero or 15-bit unsigned immediate and > 1.
2668 void MacroAssembler::string_indexof(Register result, Register haystack, Register haycnt,
2669                                     Register needle, ciTypeArray* needle_values, Register needlecnt, int needlecntval,
2670                                     Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
2671 
2672   // Ensure 0<needlecnt<=haycnt in ideal graph as prerequisite!
2673   Label L_TooShort, L_Found, L_NotFound, L_End;
2674   Register last_addr = haycnt, // Kill haycnt at the beginning.
2675            addr      = tmp1,
2676            n_start   = tmp2,
2677            ch1       = tmp3,
2678            ch2       = R0;
2679 
2680   // **************************************************************************************************
2681   // Prepare for main loop: optimized for needle count >=2, bail out otherwise.
2682   // **************************************************************************************************
2683 
2684 //1 (variable) or 3 (const):
2685    dcbtct(needle, 0x00);    // Indicate R/O access to str1.
2686    dcbtct(haystack, 0x00);  // Indicate R/O access to str2.
2687 
2688   // Compute last haystack addr to use if no match gets found.
2689   if (needlecntval == 0) { // variable needlecnt
2690 //3:
2691    subf(ch1, needlecnt, haycnt);      // Last character index to compare is haycnt-needlecnt.
2692    addi(addr, haystack, -2);          // Accesses use pre-increment.
2693    cmpwi(CCR6, needlecnt, 2);
2694    blt(CCR6, L_TooShort);          // Variable needlecnt: handle short needle separately.
2695    slwi(ch1, ch1, 1);                 // Scale to number of bytes.
2696    lwz(n_start, 0, needle);           // Load first 2 characters of needle.
2697    add(last_addr, haystack, ch1);     // Point to last address to compare (haystack+2*(haycnt-needlecnt)).
2698    addi(needlecnt, needlecnt, -2);    // Rest of needle.
2699   } else { // constant needlecnt
2700   guarantee(needlecntval != 1, "IndexOf with single-character needle must be handled separately");
2701   assert((needlecntval & 0x7fff) == needlecntval, "wrong immediate");
2702 //5:
2703    addi(ch1, haycnt, -needlecntval);  // Last character index to compare is haycnt-needlecnt.
2704    lwz(n_start, 0, needle);           // Load first 2 characters of needle.
2705    addi(addr, haystack, -2);          // Accesses use pre-increment.
2706    slwi(ch1, ch1, 1);                 // Scale to number of bytes.
2707    add(last_addr, haystack, ch1);     // Point to last address to compare (haystack+2*(haycnt-needlecnt)).
2708    li(needlecnt, needlecntval-2);     // Rest of needle.
2709   }
2710 
2711   // Main Loop (now we have at least 3 characters).
2712 //11:
2713   Label L_OuterLoop, L_InnerLoop, L_FinalCheck, L_Comp1, L_Comp2, L_Comp3;
2714   bind(L_OuterLoop); // Search for 1st 2 characters.
2715   Register addr_diff = tmp4;
2716    subf(addr_diff, addr, last_addr); // Difference between already checked address and last address to check.
2717    addi(addr, addr, 2);              // This is the new address we want to use for comparing.
2718    srdi_(ch2, addr_diff, 2);
2719    beq(CCR0, L_FinalCheck);       // 2 characters left?
2720    mtctr(ch2);                       // addr_diff/4
2721 //16:
2722   bind(L_InnerLoop);                // Main work horse (2x unrolled search loop)
2723    lwz(ch1, 0, addr);           // Load 2 characters of haystack (ignore alignment).
2724    lwz(ch2, 2, addr);
2725    cmpw(CCR0, ch1, n_start); // Compare 2 characters (1 would be sufficient but try to reduce branches to CompLoop).
2726    cmpw(CCR1, ch2, n_start);
2727    beq(CCR0, L_Comp1);       // Did we find the needle start?
2728    beq(CCR1, L_Comp2);
2729    addi(addr, addr, 4);
2730    bdnz(L_InnerLoop);
2731 //24:
2732   bind(L_FinalCheck);
2733    rldicl_(addr_diff, addr_diff, 64-1, 63); // Remaining characters not covered by InnerLoop: (addr_diff>>1)&1.
2734    beq(CCR0, L_NotFound);
2735    lwz(ch1, 0, addr);                       // One position left at which we have to compare.
2736    cmpw(CCR1, ch1, n_start);
2737    beq(CCR1, L_Comp3);
2738 //29:
2739   bind(L_NotFound);
2740    li(result, -1); // not found
2741    b(L_End);
2742 
2743 
2744    // **************************************************************************************************
2745    // Special Case: unfortunately, the variable needle case can be called with needlecnt<2
2746    // **************************************************************************************************
2747 //31:
2748  if ((needlecntval>>1) !=1 ) { // Const needlecnt is 2 or 3? Reduce code size.
2749   int nopcnt = 5;
2750   if (needlecntval !=0 ) ++nopcnt; // Balance alignment (other case: see below).
2751   if (needlecntval == 0) {         // We have to handle these cases separately.
2752   Label L_OneCharLoop;
2753   bind(L_TooShort);
2754    mtctr(haycnt);
2755    lhz(n_start, 0, needle);    // First character of needle
2756   bind(L_OneCharLoop);
2757    lhzu(ch1, 2, addr);
2758    cmpw(CCR1, ch1, n_start);
2759    beq(CCR1, L_Found);      // Did we find the one character needle?
2760    bdnz(L_OneCharLoop);
2761    li(result, -1);             // Not found.
2762    b(L_End);
2763   } // 8 instructions, so no impact on alignment.
2764   for (int x = 0; x < nopcnt; ++x) nop();
2765  }
2766 
2767   // **************************************************************************************************
2768   // Regular Case Part II: compare rest of needle (first 2 characters have been compared already)
2769   // **************************************************************************************************
2770 
2771   // Compare the rest
2772 //36 if needlecntval==0, else 37:
2773   bind(L_Comp2);
2774    addi(addr, addr, 2); // First comparison has failed, 2nd one hit.
2775   bind(L_Comp1);            // Addr points to possible needle start.
2776   bind(L_Comp3);            // Could have created a copy and use a different return address but saving code size here.
2777   if (needlecntval != 2) {  // Const needlecnt==2?
2778    if (needlecntval != 3) {
2779     if (needlecntval == 0) beq(CCR6, L_Found); // Variable needlecnt==2?
2780     Register ind_reg = tmp4;
2781     li(ind_reg, 2*2);   // First 2 characters are already compared, use index 2.
2782     mtctr(needlecnt);   // Decremented by 2, still > 0.
2783 //40:
2784    Label L_CompLoop;
2785    bind(L_CompLoop);
2786     lhzx(ch2, needle, ind_reg);
2787     lhzx(ch1, addr, ind_reg);
2788     cmpw(CCR1, ch1, ch2);
2789     bne(CCR1, L_OuterLoop);
2790     addi(ind_reg, ind_reg, 2);
2791     bdnz(L_CompLoop);
2792    } else { // No loop required if there's only one needle character left.
2793     lhz(ch2, 2*2, needle);
2794     lhz(ch1, 2*2, addr);
2795     cmpw(CCR1, ch1, ch2);
2796     bne(CCR1, L_OuterLoop);
2797    }
2798   }
2799   // Return index ...
2800 //46:
2801   bind(L_Found);
2802    subf(addr, haystack, addr); // relative to haystack, ...
2803    srdi(result, addr, 1);      // in characters.
2804 //48:
2805   bind(L_End);
2806 }
2807 
2808 // Implementation of Compare for jchar arrays.
2809 //
2810 // Kills the registers str1, str2, cnt1, cnt2.
2811 // Kills cr0, ctr.
2812 // Assumes that result differes from the input registers.
2813 void MacroAssembler::string_compare(Register str1_reg, Register str2_reg, Register cnt1_reg, Register cnt2_reg,
2814                                     Register result_reg, Register tmp_reg) {
2815    assert_different_registers(result_reg, str1_reg, str2_reg, cnt1_reg, cnt2_reg, tmp_reg);
2816 
2817    Label Ldone, Lslow_case, Lslow_loop, Lfast_loop;
2818    Register cnt_diff = R0,
2819             limit_reg = cnt1_reg,
2820             chr1_reg = result_reg,
2821             chr2_reg = cnt2_reg,
2822             addr_diff = str2_reg;
2823 
2824    // Offset 0 should be 32 byte aligned.
2825 //-4:
2826     dcbtct(str1_reg, 0x00);  // Indicate R/O access to str1.
2827     dcbtct(str2_reg, 0x00);  // Indicate R/O access to str2.
2828 //-2:
2829    // Compute min(cnt1, cnt2) and check if 0 (bail out if we don't need to compare characters).
2830     subf(result_reg, cnt2_reg, cnt1_reg);  // difference between cnt1/2
2831     subf_(addr_diff, str1_reg, str2_reg);  // alias?
2832     beq(CCR0, Ldone);                   // return cnt difference if both ones are identical
2833     srawi(limit_reg, result_reg, 31);      // generate signmask (cnt1/2 must be non-negative so cnt_diff can't overflow)
2834     mr(cnt_diff, result_reg);
2835     andr(limit_reg, result_reg, limit_reg); // difference or zero (negative): cnt1<cnt2 ? cnt1-cnt2 : 0
2836     add_(limit_reg, cnt2_reg, limit_reg);  // min(cnt1, cnt2)==0?
2837     beq(CCR0, Ldone);                   // return cnt difference if one has 0 length
2838 
2839     lhz(chr1_reg, 0, str1_reg);            // optional: early out if first characters mismatch
2840     lhzx(chr2_reg, str1_reg, addr_diff);   // optional: early out if first characters mismatch
2841     addi(tmp_reg, limit_reg, -1);          // min(cnt1, cnt2)-1
2842     subf_(result_reg, chr2_reg, chr1_reg); // optional: early out if first characters mismatch
2843     bne(CCR0, Ldone);                   // optional: early out if first characters mismatch
2844 
2845    // Set loop counter by scaling down tmp_reg
2846     srawi_(chr2_reg, tmp_reg, exact_log2(4)); // (min(cnt1, cnt2)-1)/4
2847     ble(CCR0, Lslow_case);                 // need >4 characters for fast loop
2848     andi(limit_reg, tmp_reg, 4-1);            // remaining characters
2849 
2850    // Adapt str1_reg str2_reg for the first loop iteration
2851     mtctr(chr2_reg);                 // (min(cnt1, cnt2)-1)/4
2852     addi(limit_reg, limit_reg, 4+1); // compare last 5-8 characters in slow_case if mismatch found in fast_loop
2853 //16:
2854    // Compare the rest of the characters
2855    bind(Lfast_loop);
2856     ld(chr1_reg, 0, str1_reg);
2857     ldx(chr2_reg, str1_reg, addr_diff);
2858     cmpd(CCR0, chr2_reg, chr1_reg);
2859     bne(CCR0, Lslow_case); // return chr1_reg
2860     addi(str1_reg, str1_reg, 4*2);
2861     bdnz(Lfast_loop);
2862     addi(limit_reg, limit_reg, -4); // no mismatch found in fast_loop, only 1-4 characters missing
2863 //23:
2864    bind(Lslow_case);
2865     mtctr(limit_reg);
2866 //24:
2867    bind(Lslow_loop);
2868     lhz(chr1_reg, 0, str1_reg);
2869     lhzx(chr2_reg, str1_reg, addr_diff);
2870     subf_(result_reg, chr2_reg, chr1_reg);
2871     bne(CCR0, Ldone); // return chr1_reg
2872     addi(str1_reg, str1_reg, 1*2);
2873     bdnz(Lslow_loop);
2874 //30:
2875    // If strings are equal up to min length, return the length difference.
2876     mr(result_reg, cnt_diff);
2877     nop(); // alignment
2878 //32:
2879    // Otherwise, return the difference between the first mismatched chars.
2880    bind(Ldone);
2881 }
2882 
2883 
2884 // Compare char[] arrays.
2885 //
2886 // str1_reg   USE only
2887 // str2_reg   USE only
2888 // cnt_reg    USE_DEF, due to tmp reg shortage
2889 // result_reg DEF only, might compromise USE only registers
2890 void MacroAssembler::char_arrays_equals(Register str1_reg, Register str2_reg, Register cnt_reg, Register result_reg,
2891                                         Register tmp1_reg, Register tmp2_reg, Register tmp3_reg, Register tmp4_reg,
2892                                         Register tmp5_reg) {
2893 
2894   // Str1 may be the same register as str2 which can occur e.g. after scalar replacement.
2895   assert_different_registers(result_reg, str1_reg, cnt_reg, tmp1_reg, tmp2_reg, tmp3_reg, tmp4_reg, tmp5_reg);
2896   assert_different_registers(result_reg, str2_reg, cnt_reg, tmp1_reg, tmp2_reg, tmp3_reg, tmp4_reg, tmp5_reg);
2897 
2898   // Offset 0 should be 32 byte aligned.
2899   Label Linit_cbc, Lcbc, Lloop, Ldone_true, Ldone_false;
2900   Register index_reg = tmp5_reg;
2901   Register cbc_iter  = tmp4_reg;
2902 
2903 //-1:
2904   dcbtct(str1_reg, 0x00);  // Indicate R/O access to str1.
2905   dcbtct(str2_reg, 0x00);  // Indicate R/O access to str2.
2906 //1:
2907   andi(cbc_iter, cnt_reg, 4-1);            // Remaining iterations after 4 java characters per iteration loop.
2908   li(index_reg, 0); // init
2909   li(result_reg, 0); // assume false
2910   srwi_(tmp2_reg, cnt_reg, exact_log2(4)); // Div: 4 java characters per iteration (main loop).
2911 
2912   cmpwi(CCR1, cbc_iter, 0);             // CCR1 = (cbc_iter==0)
2913   beq(CCR0, Linit_cbc);                 // too short
2914     mtctr(tmp2_reg);
2915 //8:
2916     bind(Lloop);
2917       ldx(tmp1_reg, str1_reg, index_reg);
2918       ldx(tmp2_reg, str2_reg, index_reg);
2919       cmpd(CCR0, tmp1_reg, tmp2_reg);
2920       bne(CCR0, Ldone_false);  // Unequal char pair found -> done.
2921       addi(index_reg, index_reg, 4*sizeof(jchar));
2922       bdnz(Lloop);
2923 //14:
2924   bind(Linit_cbc);
2925   beq(CCR1, Ldone_true);
2926     mtctr(cbc_iter);
2927 //16:
2928     bind(Lcbc);
2929       lhzx(tmp1_reg, str1_reg, index_reg);
2930       lhzx(tmp2_reg, str2_reg, index_reg);
2931       cmpw(CCR0, tmp1_reg, tmp2_reg);
2932       bne(CCR0, Ldone_false);  // Unequal char pair found -> done.
2933       addi(index_reg, index_reg, 1*sizeof(jchar));
2934       bdnz(Lcbc);
2935     nop();
2936   bind(Ldone_true);
2937   li(result_reg, 1);
2938 //24:
2939   bind(Ldone_false);
2940 }
2941 
2942 
2943 void MacroAssembler::char_arrays_equalsImm(Register str1_reg, Register str2_reg, int cntval, Register result_reg,
2944                                            Register tmp1_reg, Register tmp2_reg) {
2945   // Str1 may be the same register as str2 which can occur e.g. after scalar replacement.
2946   assert_different_registers(result_reg, str1_reg, tmp1_reg, tmp2_reg);
2947   assert_different_registers(result_reg, str2_reg, tmp1_reg, tmp2_reg);
2948   assert(sizeof(jchar) == 2, "must be");
2949   assert(cntval >= 0 && ((cntval & 0x7fff) == cntval), "wrong immediate");
2950 
2951   Label Ldone_false;
2952 
2953   if (cntval < 16) { // short case
2954     if (cntval != 0) li(result_reg, 0); // assume false
2955 
2956     const int num_bytes = cntval*sizeof(jchar);
2957     int index = 0;
2958     for (int next_index; (next_index = index + 8) <= num_bytes; index = next_index) {
2959       ld(tmp1_reg, index, str1_reg);
2960       ld(tmp2_reg, index, str2_reg);
2961       cmpd(CCR0, tmp1_reg, tmp2_reg);
2962       bne(CCR0, Ldone_false);
2963     }
2964     if (cntval & 2) {
2965       lwz(tmp1_reg, index, str1_reg);
2966       lwz(tmp2_reg, index, str2_reg);
2967       cmpw(CCR0, tmp1_reg, tmp2_reg);
2968       bne(CCR0, Ldone_false);
2969       index += 4;
2970     }
2971     if (cntval & 1) {
2972       lhz(tmp1_reg, index, str1_reg);
2973       lhz(tmp2_reg, index, str2_reg);
2974       cmpw(CCR0, tmp1_reg, tmp2_reg);
2975       bne(CCR0, Ldone_false);
2976     }
2977     // fallthrough: true
2978   } else {
2979     Label Lloop;
2980     Register index_reg = tmp1_reg;
2981     const int loopcnt = cntval/4;
2982     assert(loopcnt > 0, "must be");
2983     // Offset 0 should be 32 byte aligned.
2984     //2:
2985     dcbtct(str1_reg, 0x00);  // Indicate R/O access to str1.
2986     dcbtct(str2_reg, 0x00);  // Indicate R/O access to str2.
2987     li(tmp2_reg, loopcnt);
2988     li(index_reg, 0); // init
2989     li(result_reg, 0); // assume false
2990     mtctr(tmp2_reg);
2991     //8:
2992     bind(Lloop);
2993     ldx(R0, str1_reg, index_reg);
2994     ldx(tmp2_reg, str2_reg, index_reg);
2995     cmpd(CCR0, R0, tmp2_reg);
2996     bne(CCR0, Ldone_false);  // Unequal char pair found -> done.
2997     addi(index_reg, index_reg, 4*sizeof(jchar));
2998     bdnz(Lloop);
2999     //14:
3000     if (cntval & 2) {
3001       lwzx(R0, str1_reg, index_reg);
3002       lwzx(tmp2_reg, str2_reg, index_reg);
3003       cmpw(CCR0, R0, tmp2_reg);
3004       bne(CCR0, Ldone_false);
3005       if (cntval & 1) addi(index_reg, index_reg, 2*sizeof(jchar));
3006     }
3007     if (cntval & 1) {
3008       lhzx(R0, str1_reg, index_reg);
3009       lhzx(tmp2_reg, str2_reg, index_reg);
3010       cmpw(CCR0, R0, tmp2_reg);
3011       bne(CCR0, Ldone_false);
3012     }
3013     // fallthru: true
3014   }
3015   li(result_reg, 1);
3016   bind(Ldone_false);
3017 }
3018 
3019 
3020 void MacroAssembler::asm_assert(bool check_equal, const char *msg, int id) {
3021 #ifdef ASSERT
3022   Label ok;
3023   if (check_equal) {
3024     beq(CCR0, ok);
3025   } else {
3026     bne(CCR0, ok);
3027   }
3028   stop(msg, id);
3029   bind(ok);
3030 #endif
3031 }
3032 
3033 void MacroAssembler::asm_assert_mems_zero(bool check_equal, int size, int mem_offset,
3034                                           Register mem_base, const char* msg, int id) {
3035 #ifdef ASSERT
3036   switch (size) {
3037     case 4:
3038       lwz(R0, mem_offset, mem_base);
3039       cmpwi(CCR0, R0, 0);
3040       break;
3041     case 8:
3042       ld(R0, mem_offset, mem_base);
3043       cmpdi(CCR0, R0, 0);
3044       break;
3045     default:
3046       ShouldNotReachHere();
3047   }
3048   asm_assert(check_equal, msg, id);
3049 #endif // ASSERT
3050 }
3051 
3052 void MacroAssembler::verify_thread() {
3053   if (VerifyThread) {
3054     unimplemented("'VerifyThread' currently not implemented on PPC");
3055   }
3056 }
3057 
3058 // READ: oop. KILL: R0. Volatile floats perhaps.
3059 void MacroAssembler::verify_oop(Register oop, const char* msg) {
3060   if (!VerifyOops) {
3061     return;
3062   }
3063   // Will be preserved.
3064   Register tmp = R11;
3065   assert(oop != tmp, "precondition");
3066   unsigned int nbytes_save = 10*8; // 10 volatile gprs
3067   address/* FunctionDescriptor** */fd = StubRoutines::verify_oop_subroutine_entry_address();
3068   // save tmp
3069   mr(R0, tmp);
3070   // kill tmp
3071   save_LR_CR(tmp);
3072   push_frame_reg_args(nbytes_save, tmp);
3073   // restore tmp
3074   mr(tmp, R0);
3075   save_volatile_gprs(R1_SP, 112); // except R0
3076   // load FunctionDescriptor** / entry_address *
3077   load_const(tmp, fd);
3078   // load FunctionDescriptor* / entry_address
3079   ld(tmp, 0, tmp);
3080   mr(R4_ARG2, oop);
3081   load_const(R3_ARG1, (address)msg);
3082   // call destination for its side effect
3083   call_c(tmp);
3084   restore_volatile_gprs(R1_SP, 112); // except R0
3085   pop_frame();
3086   // save tmp
3087   mr(R0, tmp);
3088   // kill tmp
3089   restore_LR_CR(tmp);
3090   // restore tmp
3091   mr(tmp, R0);
3092 }
3093 
3094 const char* stop_types[] = {
3095   "stop",
3096   "untested",
3097   "unimplemented",
3098   "shouldnotreachhere"
3099 };
3100 
3101 static void stop_on_request(int tp, const char* msg) {
3102   tty->print("PPC assembly code requires stop: (%s) %s\n", stop_types[tp%/*stop_end*/4], msg);
3103   guarantee(false, err_msg("PPC assembly code requires stop: %s", msg));
3104 }
3105 
3106 // Call a C-function that prints output.
3107 void MacroAssembler::stop(int type, const char* msg, int id) {
3108 #ifndef PRODUCT
3109   block_comment(err_msg("stop: %s %s {", stop_types[type%stop_end], msg));
3110 #else
3111   block_comment("stop {");
3112 #endif
3113 
3114   // setup arguments
3115   load_const_optimized(R3_ARG1, type);
3116   load_const_optimized(R4_ARG2, (void *)msg, /*tmp=*/R0);
3117   call_VM_leaf(CAST_FROM_FN_PTR(address, stop_on_request), R3_ARG1, R4_ARG2);
3118   illtrap();
3119   emit_int32(id);
3120   block_comment("} stop;");
3121 }
3122 
3123 #ifndef PRODUCT
3124 // Write pattern 0x0101010101010101 in memory region [low-before, high+after].
3125 // Val, addr are temp registers.
3126 // If low == addr, addr is killed.
3127 // High is preserved.
3128 void MacroAssembler::zap_from_to(Register low, int before, Register high, int after, Register val, Register addr) {
3129   if (!ZapMemory) return;
3130 
3131   assert_different_registers(low, val);
3132 
3133   BLOCK_COMMENT("zap memory region {");
3134   load_const_optimized(val, 0x0101010101010101);
3135   int size = before + after;
3136   if (low == high && size < 5 && size > 0) {
3137     int offset = -before*BytesPerWord;
3138     for (int i = 0; i < size; ++i) {
3139       std(val, offset, low);
3140       offset += (1*BytesPerWord);
3141     }
3142   } else {
3143     addi(addr, low, -before*BytesPerWord);
3144     assert_different_registers(high, val);
3145     if (after) addi(high, high, after * BytesPerWord);
3146     Label loop;
3147     bind(loop);
3148     std(val, 0, addr);
3149     addi(addr, addr, 8);
3150     cmpd(CCR6, addr, high);
3151     ble(CCR6, loop);
3152     if (after) addi(high, high, -after * BytesPerWord);  // Correct back to old value.
3153   }
3154   BLOCK_COMMENT("} zap memory region");
3155 }
3156 
3157 #endif // !PRODUCT
3158 
3159 SkipIfEqualZero::SkipIfEqualZero(MacroAssembler* masm, Register temp, const bool* flag_addr) : _masm(masm), _label() {
3160   int simm16_offset = masm->load_const_optimized(temp, (address)flag_addr, R0, true);
3161   assert(sizeof(bool) == 1, "PowerPC ABI");
3162   masm->lbz(temp, simm16_offset, temp);
3163   masm->cmpwi(CCR0, temp, 0);
3164   masm->beq(CCR0, _label);
3165 }
3166 
3167 SkipIfEqualZero::~SkipIfEqualZero() {
3168   _masm->bind(_label);
3169 }