1 /*
   2 /*
   3  * Copyright (c) 2013, Red Hat Inc.
   4  * Copyright (c) 1997, 2012, Oracle and/or its affiliates.
   5  * All rights reserved.
   6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   7  *
   8  * This code is free software; you can redistribute it and/or modify it
   9  * under the terms of the GNU General Public License version 2 only, as
  10  * published by the Free Software Foundation.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  23  * or visit www.oracle.com if you need additional information or have any
  24  * questions.
  25  *
  26  */
  27 
  28 #include <sys/types.h>
  29 
  30 #include "precompiled.hpp"
  31 #include "asm/assembler.hpp"
  32 #include "asm/assembler.inline.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 
  35 #include "compiler/disassembler.hpp"
  36 #include "gc_interface/collectedHeap.inline.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "runtime/biasedLocking.hpp"
  39 #include "runtime/interfaceSupport.hpp"
  40 #include "runtime/sharedRuntime.hpp"
  41 
  42 // #include "gc_interface/collectedHeap.inline.hpp"
  43 // #include "interpreter/interpreter.hpp"
  44 // #include "memory/cardTableModRefBS.hpp"
  45 // #include "prims/methodHandles.hpp"
  46 // #include "runtime/biasedLocking.hpp"
  47 // #include "runtime/interfaceSupport.hpp"
  48 // #include "runtime/objectMonitor.hpp"
  49 // #include "runtime/os.hpp"
  50 // #include "runtime/sharedRuntime.hpp"
  51 // #include "runtime/stubRoutines.hpp"
  52 
  53 #if INCLUDE_ALL_GCS
  54 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
  55 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
  56 #include "gc_implementation/g1/heapRegion.hpp"
  57 #include "shenandoahBarrierSetAssembler_aarch64.hpp"
  58 #endif
  59 
  60 #ifdef COMPILER2
  61 #include "opto/node.hpp"
  62 #include "opto/compile.hpp"
  63 #endif
  64 
  65 #ifdef PRODUCT
  66 #define BLOCK_COMMENT(str) /* nothing */
  67 #define STOP(error) stop(error)
  68 #else
  69 #define BLOCK_COMMENT(str) block_comment(str)
  70 #define STOP(error) block_comment(error); stop(error)
  71 #endif
  72 
  73 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  74 
  75 // Patch any kind of instruction; there may be several instructions.
  76 // Return the total length (in bytes) of the instructions.
  77 int MacroAssembler::pd_patch_instruction_size(address branch, address target) {
  78   int instructions = 1;
  79   assert((uint64_t)target < (1ul << 48), "48-bit overflow in address constant");
  80   long offset = (target - branch) >> 2;
  81   unsigned insn = *(unsigned*)branch;
  82   if ((Instruction_aarch64::extract(insn, 29, 24) & 0b111011) == 0b011000) {
  83     // Load register (literal)
  84     Instruction_aarch64::spatch(branch, 23, 5, offset);
  85   } else if (Instruction_aarch64::extract(insn, 30, 26) == 0b00101) {
  86     // Unconditional branch (immediate)
  87     Instruction_aarch64::spatch(branch, 25, 0, offset);
  88   } else if (Instruction_aarch64::extract(insn, 31, 25) == 0b0101010) {
  89     // Conditional branch (immediate)
  90     Instruction_aarch64::spatch(branch, 23, 5, offset);
  91   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011010) {
  92     // Compare & branch (immediate)
  93     Instruction_aarch64::spatch(branch, 23, 5, offset);
  94   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011011) {
  95     // Test & branch (immediate)
  96     Instruction_aarch64::spatch(branch, 18, 5, offset);
  97   } else if (Instruction_aarch64::extract(insn, 28, 24) == 0b10000) {
  98     // PC-rel. addressing
  99     offset = target-branch;
 100     int shift = Instruction_aarch64::extract(insn, 31, 31);
 101     if (shift) {
 102       u_int64_t dest = (u_int64_t)target;
 103       uint64_t pc_page = (uint64_t)branch >> 12;
 104       uint64_t adr_page = (uint64_t)target >> 12;
 105       unsigned offset_lo = dest & 0xfff;
 106       offset = adr_page - pc_page;
 107 
 108       // We handle 4 types of PC relative addressing
 109       //   1 - adrp    Rx, target_page
 110       //       ldr/str Ry, [Rx, #offset_in_page]
 111       //   2 - adrp    Rx, target_page
 112       //       add     Ry, Rx, #offset_in_page
 113       //   3 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 114       //       movk    Rx, #imm16<<32
 115       //   4 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 116       // In the first 3 cases we must check that Rx is the same in the adrp and the
 117       // subsequent ldr/str, add or movk instruction. Otherwise we could accidentally end
 118       // up treating a type 4 relocation as a type 1, 2 or 3 just because it happened
 119       // to be followed by a random unrelated ldr/str, add or movk instruction.
 120       //
 121       unsigned insn2 = ((unsigned*)branch)[1];
 122       if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
 123                 Instruction_aarch64::extract(insn, 4, 0) ==
 124                         Instruction_aarch64::extract(insn2, 9, 5)) {
 125         // Load/store register (unsigned immediate)
 126         unsigned size = Instruction_aarch64::extract(insn2, 31, 30);
 127         Instruction_aarch64::patch(branch + sizeof (unsigned),
 128                                     21, 10, offset_lo >> size);
 129         guarantee(((dest >> size) << size) == dest, "misaligned target");
 130         instructions = 2;
 131       } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
 132                 Instruction_aarch64::extract(insn, 4, 0) ==
 133                         Instruction_aarch64::extract(insn2, 4, 0)) {
 134         // add (immediate)
 135         Instruction_aarch64::patch(branch + sizeof (unsigned),
 136                                    21, 10, offset_lo);
 137         instructions = 2;
 138       } else if (Instruction_aarch64::extract(insn2, 31, 21) == 0b11110010110 &&
 139                    Instruction_aarch64::extract(insn, 4, 0) ==
 140                      Instruction_aarch64::extract(insn2, 4, 0)) {
 141         // movk #imm16<<32
 142         Instruction_aarch64::patch(branch + 4, 20, 5, (uint64_t)target >> 32);
 143         long dest = ((long)target & 0xffffffffL) | ((long)branch & 0xffff00000000L);
 144         long pc_page = (long)branch >> 12;
 145         long adr_page = (long)dest >> 12;
 146         offset = adr_page - pc_page;
 147         instructions = 2;
 148       }
 149     }
 150     int offset_lo = offset & 3;
 151     offset >>= 2;
 152     Instruction_aarch64::spatch(branch, 23, 5, offset);
 153     Instruction_aarch64::patch(branch, 30, 29, offset_lo);
 154   } else if (Instruction_aarch64::extract(insn, 31, 21) == 0b11010010100) {
 155     u_int64_t dest = (u_int64_t)target;
 156     // Move wide constant
 157     assert(nativeInstruction_at(branch+4)->is_movk(), "wrong insns in patch");
 158     assert(nativeInstruction_at(branch+8)->is_movk(), "wrong insns in patch");
 159     Instruction_aarch64::patch(branch, 20, 5, dest & 0xffff);
 160     Instruction_aarch64::patch(branch+4, 20, 5, (dest >>= 16) & 0xffff);
 161     Instruction_aarch64::patch(branch+8, 20, 5, (dest >>= 16) & 0xffff);
 162     assert(target_addr_for_insn(branch) == target, "should be");
 163     instructions = 3;
 164   } else if (Instruction_aarch64::extract(insn, 31, 22) == 0b1011100101 &&
 165              Instruction_aarch64::extract(insn, 4, 0) == 0b11111) {
 166     // nothing to do
 167     assert(target == 0, "did not expect to relocate target for polling page load");
 168   } else {
 169     ShouldNotReachHere();
 170   }
 171   return instructions * NativeInstruction::instruction_size;
 172 }
 173 
 174 int MacroAssembler::patch_oop(address insn_addr, address o) {
 175   int instructions;
 176   unsigned insn = *(unsigned*)insn_addr;
 177   assert(nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 178 
 179   // OOPs are either narrow (32 bits) or wide (48 bits).  We encode
 180   // narrow OOPs by setting the upper 16 bits in the first
 181   // instruction.
 182   if (Instruction_aarch64::extract(insn, 31, 21) == 0b11010010101) {
 183     // Move narrow OOP
 184     narrowOop n = oopDesc::encode_heap_oop((oop)o);
 185     Instruction_aarch64::patch(insn_addr, 20, 5, n >> 16);
 186     Instruction_aarch64::patch(insn_addr+4, 20, 5, n & 0xffff);
 187     instructions = 2;
 188   } else {
 189     // Move wide OOP
 190     assert(nativeInstruction_at(insn_addr+8)->is_movk(), "wrong insns in patch");
 191     uintptr_t dest = (uintptr_t)o;
 192     Instruction_aarch64::patch(insn_addr, 20, 5, dest & 0xffff);
 193     Instruction_aarch64::patch(insn_addr+4, 20, 5, (dest >>= 16) & 0xffff);
 194     Instruction_aarch64::patch(insn_addr+8, 20, 5, (dest >>= 16) & 0xffff);
 195     instructions = 3;
 196   }
 197   return instructions * NativeInstruction::instruction_size;
 198 }
 199 
 200 address MacroAssembler::target_addr_for_insn(address insn_addr, unsigned insn) {
 201   long offset = 0;
 202   if ((Instruction_aarch64::extract(insn, 29, 24) & 0b011011) == 0b00011000) {
 203     // Load register (literal)
 204     offset = Instruction_aarch64::sextract(insn, 23, 5);
 205     return address(((uint64_t)insn_addr + (offset << 2)));
 206   } else if (Instruction_aarch64::extract(insn, 30, 26) == 0b00101) {
 207     // Unconditional branch (immediate)
 208     offset = Instruction_aarch64::sextract(insn, 25, 0);
 209   } else if (Instruction_aarch64::extract(insn, 31, 25) == 0b0101010) {
 210     // Conditional branch (immediate)
 211     offset = Instruction_aarch64::sextract(insn, 23, 5);
 212   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011010) {
 213     // Compare & branch (immediate)
 214     offset = Instruction_aarch64::sextract(insn, 23, 5);
 215    } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011011) {
 216     // Test & branch (immediate)
 217     offset = Instruction_aarch64::sextract(insn, 18, 5);
 218   } else if (Instruction_aarch64::extract(insn, 28, 24) == 0b10000) {
 219     // PC-rel. addressing
 220     offset = Instruction_aarch64::extract(insn, 30, 29);
 221     offset |= Instruction_aarch64::sextract(insn, 23, 5) << 2;
 222     int shift = Instruction_aarch64::extract(insn, 31, 31) ? 12 : 0;
 223     if (shift) {
 224       offset <<= shift;
 225       uint64_t target_page = ((uint64_t)insn_addr) + offset;
 226       target_page &= ((uint64_t)-1) << shift;
 227       // Return the target address for the following sequences
 228       //   1 - adrp    Rx, target_page
 229       //       ldr/str Ry, [Rx, #offset_in_page]
 230       //   2 - adrp    Rx, target_page
 231       //       add     Ry, Rx, #offset_in_page
 232       //   3 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 233       //       movk    Rx, #imm12<<32
 234       //   4 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 235       //
 236       // In the first two cases  we check that the register is the same and
 237       // return the target_page + the offset within the page.
 238       // Otherwise we assume it is a page aligned relocation and return
 239       // the target page only.
 240       //
 241       unsigned insn2 = ((unsigned*)insn_addr)[1];
 242       if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
 243                 Instruction_aarch64::extract(insn, 4, 0) ==
 244                         Instruction_aarch64::extract(insn2, 9, 5)) {
 245         // Load/store register (unsigned immediate)
 246         unsigned int byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 247         unsigned int size = Instruction_aarch64::extract(insn2, 31, 30);
 248         return address(target_page + (byte_offset << size));
 249       } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
 250                 Instruction_aarch64::extract(insn, 4, 0) ==
 251                         Instruction_aarch64::extract(insn2, 4, 0)) {
 252         // add (immediate)
 253         unsigned int byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 254         return address(target_page + byte_offset);
 255       } else {
 256         if (Instruction_aarch64::extract(insn2, 31, 21) == 0b11110010110  &&
 257                Instruction_aarch64::extract(insn, 4, 0) ==
 258                  Instruction_aarch64::extract(insn2, 4, 0)) {
 259           target_page = (target_page & 0xffffffff) |
 260                          ((uint64_t)Instruction_aarch64::extract(insn2, 20, 5) << 32);
 261         }
 262         return (address)target_page;
 263       }
 264     } else {
 265       ShouldNotReachHere();
 266     }
 267   } else if (Instruction_aarch64::extract(insn, 31, 23) == 0b110100101) {
 268     u_int32_t *insns = (u_int32_t *)insn_addr;
 269     // Move wide constant: movz, movk, movk.  See movptr().
 270     assert(nativeInstruction_at(insns+1)->is_movk(), "wrong insns in patch");
 271     assert(nativeInstruction_at(insns+2)->is_movk(), "wrong insns in patch");
 272     return address(u_int64_t(Instruction_aarch64::extract(insns[0], 20, 5))
 273                    + (u_int64_t(Instruction_aarch64::extract(insns[1], 20, 5)) << 16)
 274                    + (u_int64_t(Instruction_aarch64::extract(insns[2], 20, 5)) << 32));
 275   } else if (Instruction_aarch64::extract(insn, 31, 22) == 0b1011100101 &&
 276              Instruction_aarch64::extract(insn, 4, 0) == 0b11111) {
 277     return 0;
 278   } else {
 279     ShouldNotReachHere();
 280   }
 281   return address(((uint64_t)insn_addr + (offset << 2)));
 282 }
 283 
 284 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
 285   dsb(Assembler::SY);
 286 }
 287 
 288 
 289 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 290   // we must set sp to zero to clear frame
 291   str(zr, Address(rthread, JavaThread::last_Java_sp_offset()));
 292 
 293   // must clear fp, so that compiled frames are not confused; it is
 294   // possible that we need it only for debugging
 295   if (clear_fp) {
 296     str(zr, Address(rthread, JavaThread::last_Java_fp_offset()));
 297   }
 298 
 299   // Always clear the pc because it could have been set by make_walkable()
 300   str(zr, Address(rthread, JavaThread::last_Java_pc_offset()));
 301 }
 302 
 303 // Calls to C land
 304 //
 305 // When entering C land, the rfp, & resp of the last Java frame have to be recorded
 306 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
 307 // has to be reset to 0. This is required to allow proper stack traversal.
 308 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 309                                          Register last_java_fp,
 310                                          Register last_java_pc,
 311                                          Register scratch) {
 312 
 313   if (last_java_pc->is_valid()) {
 314       str(last_java_pc, Address(rthread,
 315                                 JavaThread::frame_anchor_offset()
 316                                 + JavaFrameAnchor::last_Java_pc_offset()));
 317     }
 318 
 319   // determine last_java_sp register
 320   if (last_java_sp == sp) {
 321     mov(scratch, sp);
 322     last_java_sp = scratch;
 323   } else if (!last_java_sp->is_valid()) {
 324     last_java_sp = esp;
 325   }
 326 
 327   str(last_java_sp, Address(rthread, JavaThread::last_Java_sp_offset()));
 328 
 329   // last_java_fp is optional
 330   if (last_java_fp->is_valid()) {
 331     str(last_java_fp, Address(rthread, JavaThread::last_Java_fp_offset()));
 332   }
 333 }
 334 
 335 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 336                                          Register last_java_fp,
 337                                          address  last_java_pc,
 338                                          Register scratch) {
 339   if (last_java_pc != NULL) {
 340     adr(scratch, last_java_pc);
 341   } else {
 342     // FIXME: This is almost never correct.  We should delete all
 343     // cases of set_last_Java_frame with last_java_pc=NULL and use the
 344     // correct return address instead.
 345     adr(scratch, pc());
 346   }
 347 
 348   str(scratch, Address(rthread,
 349                        JavaThread::frame_anchor_offset()
 350                        + JavaFrameAnchor::last_Java_pc_offset()));
 351 
 352   set_last_Java_frame(last_java_sp, last_java_fp, noreg, scratch);
 353 }
 354 
 355 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 356                                          Register last_java_fp,
 357                                          Label &L,
 358                                          Register scratch) {
 359   if (L.is_bound()) {
 360     set_last_Java_frame(last_java_sp, last_java_fp, target(L), scratch);
 361   } else {
 362     InstructionMark im(this);
 363     L.add_patch_at(code(), locator());
 364     set_last_Java_frame(last_java_sp, last_java_fp, (address)NULL, scratch);
 365   }
 366 }
 367 
 368 void MacroAssembler::far_call(Address entry, CodeBuffer *cbuf, Register tmp) {
 369   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
 370   assert(CodeCache::find_blob(entry.target()) != NULL,
 371          "destination of far call not found in code cache");
 372   if (far_branches()) {
 373     unsigned long offset;
 374     // We can use ADRP here because we know that the total size of
 375     // the code cache cannot exceed 2Gb.
 376     adrp(tmp, entry, offset);
 377     add(tmp, tmp, offset);
 378     if (cbuf) cbuf->set_insts_mark();
 379     blr(tmp);
 380   } else {
 381     if (cbuf) cbuf->set_insts_mark();
 382     bl(entry);
 383   }
 384 }
 385 
 386 void MacroAssembler::far_jump(Address entry, CodeBuffer *cbuf, Register tmp) {
 387   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
 388   assert(CodeCache::find_blob(entry.target()) != NULL,
 389          "destination of far call not found in code cache");
 390   if (far_branches()) {
 391     unsigned long offset;
 392     // We can use ADRP here because we know that the total size of
 393     // the code cache cannot exceed 2Gb.
 394     adrp(tmp, entry, offset);
 395     add(tmp, tmp, offset);
 396     if (cbuf) cbuf->set_insts_mark();
 397     br(tmp);
 398   } else {
 399     if (cbuf) cbuf->set_insts_mark();
 400     b(entry);
 401   }
 402 }
 403 
 404 int MacroAssembler::biased_locking_enter(Register lock_reg,
 405                                          Register obj_reg,
 406                                          Register swap_reg,
 407                                          Register tmp_reg,
 408                                          bool swap_reg_contains_mark,
 409                                          Label& done,
 410                                          Label* slow_case,
 411                                          BiasedLockingCounters* counters) {
 412   assert(UseBiasedLocking, "why call this otherwise?");
 413   assert_different_registers(lock_reg, obj_reg, swap_reg);
 414 
 415   if (PrintBiasedLockingStatistics && counters == NULL)
 416     counters = BiasedLocking::counters();
 417 
 418   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg, rscratch1, rscratch2, noreg);
 419   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
 420   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
 421   Address klass_addr     (obj_reg, oopDesc::klass_offset_in_bytes());
 422   Address saved_mark_addr(lock_reg, 0);
 423 
 424   // Biased locking
 425   // See whether the lock is currently biased toward our thread and
 426   // whether the epoch is still valid
 427   // Note that the runtime guarantees sufficient alignment of JavaThread
 428   // pointers to allow age to be placed into low bits
 429   // First check to see whether biasing is even enabled for this object
 430   Label cas_label;
 431   int null_check_offset = -1;
 432   if (!swap_reg_contains_mark) {
 433     null_check_offset = offset();
 434     ldr(swap_reg, mark_addr);
 435   }
 436   andr(tmp_reg, swap_reg, markOopDesc::biased_lock_mask_in_place);
 437   cmp(tmp_reg, markOopDesc::biased_lock_pattern);
 438   br(Assembler::NE, cas_label);
 439   // The bias pattern is present in the object's header. Need to check
 440   // whether the bias owner and the epoch are both still current.
 441   load_prototype_header(tmp_reg, obj_reg);
 442   orr(tmp_reg, tmp_reg, rthread);
 443   eor(tmp_reg, swap_reg, tmp_reg);
 444   andr(tmp_reg, tmp_reg, ~((int) markOopDesc::age_mask_in_place));
 445   if (counters != NULL) {
 446     Label around;
 447     cbnz(tmp_reg, around);
 448     atomic_incw(Address((address)counters->biased_lock_entry_count_addr()), tmp_reg, rscratch1, rscratch2);
 449     b(done);
 450     bind(around);
 451   } else {
 452     cbz(tmp_reg, done);
 453   }
 454 
 455   Label try_revoke_bias;
 456   Label try_rebias;
 457 
 458   // At this point we know that the header has the bias pattern and
 459   // that we are not the bias owner in the current epoch. We need to
 460   // figure out more details about the state of the header in order to
 461   // know what operations can be legally performed on the object's
 462   // header.
 463 
 464   // If the low three bits in the xor result aren't clear, that means
 465   // the prototype header is no longer biased and we have to revoke
 466   // the bias on this object.
 467   andr(rscratch1, tmp_reg, markOopDesc::biased_lock_mask_in_place);
 468   cbnz(rscratch1, try_revoke_bias);
 469 
 470   // Biasing is still enabled for this data type. See whether the
 471   // epoch of the current bias is still valid, meaning that the epoch
 472   // bits of the mark word are equal to the epoch bits of the
 473   // prototype header. (Note that the prototype header's epoch bits
 474   // only change at a safepoint.) If not, attempt to rebias the object
 475   // toward the current thread. Note that we must be absolutely sure
 476   // that the current epoch is invalid in order to do this because
 477   // otherwise the manipulations it performs on the mark word are
 478   // illegal.
 479   andr(rscratch1, tmp_reg, markOopDesc::epoch_mask_in_place);
 480   cbnz(rscratch1, try_rebias);
 481 
 482   // The epoch of the current bias is still valid but we know nothing
 483   // about the owner; it might be set or it might be clear. Try to
 484   // acquire the bias of the object using an atomic operation. If this
 485   // fails we will go in to the runtime to revoke the object's bias.
 486   // Note that we first construct the presumed unbiased header so we
 487   // don't accidentally blow away another thread's valid bias.
 488   {
 489     Label here;
 490     mov(rscratch1, markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
 491     andr(swap_reg, swap_reg, rscratch1);
 492     orr(tmp_reg, swap_reg, rthread);
 493     cmpxchgptr(swap_reg, tmp_reg, obj_reg, rscratch1, here, slow_case);
 494     // If the biasing toward our thread failed, this means that
 495     // another thread succeeded in biasing it toward itself and we
 496     // need to revoke that bias. The revocation will occur in the
 497     // interpreter runtime in the slow case.
 498     bind(here);
 499     if (counters != NULL) {
 500       atomic_incw(Address((address)counters->anonymously_biased_lock_entry_count_addr()),
 501                   tmp_reg, rscratch1, rscratch2);
 502     }
 503   }
 504   b(done);
 505 
 506   bind(try_rebias);
 507   // At this point we know the epoch has expired, meaning that the
 508   // current "bias owner", if any, is actually invalid. Under these
 509   // circumstances _only_, we are allowed to use the current header's
 510   // value as the comparison value when doing the cas to acquire the
 511   // bias in the current epoch. In other words, we allow transfer of
 512   // the bias from one thread to another directly in this situation.
 513   //
 514   // FIXME: due to a lack of registers we currently blow away the age
 515   // bits in this situation. Should attempt to preserve them.
 516   {
 517     Label here;
 518     load_prototype_header(tmp_reg, obj_reg);
 519     orr(tmp_reg, rthread, tmp_reg);
 520     cmpxchgptr(swap_reg, tmp_reg, obj_reg, rscratch1, here, slow_case);
 521     // If the biasing toward our thread failed, then another thread
 522     // succeeded in biasing it toward itself and we need to revoke that
 523     // bias. The revocation will occur in the runtime in the slow case.
 524     bind(here);
 525     if (counters != NULL) {
 526       atomic_incw(Address((address)counters->rebiased_lock_entry_count_addr()),
 527                   tmp_reg, rscratch1, rscratch2);
 528     }
 529   }
 530   b(done);
 531 
 532   bind(try_revoke_bias);
 533   // The prototype mark in the klass doesn't have the bias bit set any
 534   // more, indicating that objects of this data type are not supposed
 535   // to be biased any more. We are going to try to reset the mark of
 536   // this object to the prototype value and fall through to the
 537   // CAS-based locking scheme. Note that if our CAS fails, it means
 538   // that another thread raced us for the privilege of revoking the
 539   // bias of this particular object, so it's okay to continue in the
 540   // normal locking code.
 541   //
 542   // FIXME: due to a lack of registers we currently blow away the age
 543   // bits in this situation. Should attempt to preserve them.
 544   {
 545     Label here, nope;
 546     load_prototype_header(tmp_reg, obj_reg);
 547     cmpxchgptr(swap_reg, tmp_reg, obj_reg, rscratch1, here, &nope);
 548     bind(here);
 549 
 550     // Fall through to the normal CAS-based lock, because no matter what
 551     // the result of the above CAS, some thread must have succeeded in
 552     // removing the bias bit from the object's header.
 553     if (counters != NULL) {
 554       atomic_incw(Address((address)counters->revoked_lock_entry_count_addr()), tmp_reg,
 555                   rscratch1, rscratch2);
 556     }
 557     bind(nope);
 558   }
 559 
 560   bind(cas_label);
 561 
 562   return null_check_offset;
 563 }
 564 
 565 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
 566   assert(UseBiasedLocking, "why call this otherwise?");
 567 
 568   // Check for biased locking unlock case, which is a no-op
 569   // Note: we do not have to check the thread ID for two reasons.
 570   // First, the interpreter checks for IllegalMonitorStateException at
 571   // a higher level. Second, if the bias was revoked while we held the
 572   // lock, the object could not be rebiased toward another thread, so
 573   // the bias bit would be clear.
 574   ldr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
 575   andr(temp_reg, temp_reg, markOopDesc::biased_lock_mask_in_place);
 576   cmp(temp_reg, markOopDesc::biased_lock_pattern);
 577   br(Assembler::EQ, done);
 578 }
 579 
 580 
 581 // added to make this compile
 582 
 583 REGISTER_DEFINITION(Register, noreg);
 584 
 585 static void pass_arg0(MacroAssembler* masm, Register arg) {
 586   if (c_rarg0 != arg ) {
 587     masm->mov(c_rarg0, arg);
 588   }
 589 }
 590 
 591 static void pass_arg1(MacroAssembler* masm, Register arg) {
 592   if (c_rarg1 != arg ) {
 593     masm->mov(c_rarg1, arg);
 594   }
 595 }
 596 
 597 static void pass_arg2(MacroAssembler* masm, Register arg) {
 598   if (c_rarg2 != arg ) {
 599     masm->mov(c_rarg2, arg);
 600   }
 601 }
 602 
 603 static void pass_arg3(MacroAssembler* masm, Register arg) {
 604   if (c_rarg3 != arg ) {
 605     masm->mov(c_rarg3, arg);
 606   }
 607 }
 608 
 609 void MacroAssembler::call_VM_base(Register oop_result,
 610                                   Register java_thread,
 611                                   Register last_java_sp,
 612                                   address  entry_point,
 613                                   int      number_of_arguments,
 614                                   bool     check_exceptions) {
 615    // determine java_thread register
 616   if (!java_thread->is_valid()) {
 617     java_thread = rthread;
 618   }
 619 
 620   // determine last_java_sp register
 621   if (!last_java_sp->is_valid()) {
 622     last_java_sp = esp;
 623   }
 624 
 625   // debugging support
 626   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
 627   assert(java_thread == rthread, "unexpected register");
 628 #ifdef ASSERT
 629   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
 630   // if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");
 631 #endif // ASSERT
 632 
 633   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
 634   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
 635 
 636   // push java thread (becomes first argument of C function)
 637 
 638   mov(c_rarg0, java_thread);
 639 
 640   // set last Java frame before call
 641   assert(last_java_sp != rfp, "can't use rfp");
 642 
 643   Label l;
 644   set_last_Java_frame(last_java_sp, rfp, l, rscratch1);
 645 
 646   // do the call, remove parameters
 647   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments, &l);
 648 
 649   // reset last Java frame
 650   // Only interpreter should have to clear fp
 651   reset_last_Java_frame(true);
 652 
 653    // C++ interp handles this in the interpreter
 654   check_and_handle_popframe(java_thread);
 655   check_and_handle_earlyret(java_thread);
 656 
 657   if (check_exceptions) {
 658     // check for pending exceptions (java_thread is set upon return)
 659     ldr(rscratch1, Address(java_thread, in_bytes(Thread::pending_exception_offset())));
 660     Label ok;
 661     cbz(rscratch1, ok);
 662     lea(rscratch1, RuntimeAddress(StubRoutines::forward_exception_entry()));
 663     br(rscratch1);
 664     bind(ok);
 665   }
 666 
 667   // get oop result if there is one and reset the value in the thread
 668   if (oop_result->is_valid()) {
 669     get_vm_result(oop_result, java_thread);
 670   }
 671 }
 672 
 673 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
 674   call_VM_base(oop_result, noreg, noreg, entry_point, number_of_arguments, check_exceptions);
 675 }
 676 
 677 // Maybe emit a call via a trampoline.  If the code cache is small
 678 // trampolines won't be emitted.
 679 
 680 address MacroAssembler::trampoline_call(Address entry, CodeBuffer *cbuf) {
 681   assert(entry.rspec().type() == relocInfo::runtime_call_type
 682          || entry.rspec().type() == relocInfo::opt_virtual_call_type
 683          || entry.rspec().type() == relocInfo::static_call_type
 684          || entry.rspec().type() == relocInfo::virtual_call_type, "wrong reloc type");
 685 
 686   unsigned int start_offset = offset();
 687 #ifdef COMPILER2
 688   // We need a trampoline if branches are far.
 689   if (far_branches()) {
 690     // We don't want to emit a trampoline if C2 is generating dummy
 691     // code during its branch shortening phase.
 692     CompileTask* task = ciEnv::current()->task();
 693     bool in_scratch_emit_size =
 694       ((task != NULL) && is_c2_compile(task->comp_level())
 695        && Compile::current()->in_scratch_emit_size());
 696     if (! in_scratch_emit_size) {
 697       address stub = emit_trampoline_stub(start_offset, entry.target());
 698       if (stub == NULL) {
 699         return NULL; // CodeCache is full
 700       }
 701     }
 702   }
 703 #endif
 704 
 705   if (cbuf) cbuf->set_insts_mark();
 706   relocate(entry.rspec());
 707 #ifdef COMPILER2
 708   if (!far_branches()) {
 709     bl(entry.target());
 710   } else {
 711     bl(pc());
 712   }
 713 #else
 714     bl(entry.target());
 715 #endif
 716   // just need to return a non-null address
 717   return pc();
 718 }
 719 
 720 
 721 // Emit a trampoline stub for a call to a target which is too far away.
 722 //
 723 // code sequences:
 724 //
 725 // call-site:
 726 //   branch-and-link to <destination> or <trampoline stub>
 727 //
 728 // Related trampoline stub for this call site in the stub section:
 729 //   load the call target from the constant pool
 730 //   branch (LR still points to the call site above)
 731 
 732 address MacroAssembler::emit_trampoline_stub(int insts_call_instruction_offset,
 733                                              address dest) {
 734 #ifdef COMPILER2
 735   address stub = start_a_stub(Compile::MAX_stubs_size/2);
 736   if (stub == NULL) {
 737     return NULL;  // CodeBuffer::expand failed
 738   }
 739 
 740   // Create a trampoline stub relocation which relates this trampoline stub
 741   // with the call instruction at insts_call_instruction_offset in the
 742   // instructions code-section.
 743   align(wordSize);
 744   relocate(trampoline_stub_Relocation::spec(code()->insts()->start()
 745                                             + insts_call_instruction_offset));
 746   const int stub_start_offset = offset();
 747 
 748   // Now, create the trampoline stub's code:
 749   // - load the call
 750   // - call
 751   Label target;
 752   ldr(rscratch1, target);
 753   br(rscratch1);
 754   bind(target);
 755   assert(offset() - stub_start_offset == NativeCallTrampolineStub::data_offset,
 756          "should be");
 757   emit_int64((int64_t)dest);
 758 
 759   const address stub_start_addr = addr_at(stub_start_offset);
 760 
 761   assert(is_NativeCallTrampolineStub_at(stub_start_addr), "doesn't look like a trampoline");
 762 
 763   end_a_stub();
 764   return stub;
 765 #else
 766   ShouldNotReachHere();
 767   return NULL;
 768 #endif
 769 }
 770 
 771 void MacroAssembler::c2bool(Register x) {
 772   // implements x == 0 ? 0 : 1
 773   // note: must only look at least-significant byte of x
 774   //       since C-style booleans are stored in one byte
 775   //       only! (was bug)
 776   tst(x, 0xff);
 777   cset(x, Assembler::NE);
 778 }
 779 
 780 address MacroAssembler::ic_call(address entry) {
 781   RelocationHolder rh = virtual_call_Relocation::spec(pc());
 782   // address const_ptr = long_constant((jlong)Universe::non_oop_word());
 783   // unsigned long offset;
 784   // ldr_constant(rscratch2, const_ptr);
 785   movptr(rscratch2, (uintptr_t)Universe::non_oop_word());
 786   return trampoline_call(Address(entry, rh));
 787 }
 788 
 789 // Implementation of call_VM versions
 790 
 791 void MacroAssembler::call_VM(Register oop_result,
 792                              address entry_point,
 793                              bool check_exceptions) {
 794   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
 795 }
 796 
 797 void MacroAssembler::call_VM(Register oop_result,
 798                              address entry_point,
 799                              Register arg_1,
 800                              bool check_exceptions) {
 801   pass_arg1(this, arg_1);
 802   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
 803 }
 804 
 805 void MacroAssembler::call_VM(Register oop_result,
 806                              address entry_point,
 807                              Register arg_1,
 808                              Register arg_2,
 809                              bool check_exceptions) {
 810   assert(arg_1 != c_rarg2, "smashed arg");
 811   pass_arg2(this, arg_2);
 812   pass_arg1(this, arg_1);
 813   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
 814 }
 815 
 816 void MacroAssembler::call_VM(Register oop_result,
 817                              address entry_point,
 818                              Register arg_1,
 819                              Register arg_2,
 820                              Register arg_3,
 821                              bool check_exceptions) {
 822   assert(arg_1 != c_rarg3, "smashed arg");
 823   assert(arg_2 != c_rarg3, "smashed arg");
 824   pass_arg3(this, arg_3);
 825 
 826   assert(arg_1 != c_rarg2, "smashed arg");
 827   pass_arg2(this, arg_2);
 828 
 829   pass_arg1(this, arg_1);
 830   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
 831 }
 832 
 833 void MacroAssembler::call_VM(Register oop_result,
 834                              Register last_java_sp,
 835                              address entry_point,
 836                              int number_of_arguments,
 837                              bool check_exceptions) {
 838   call_VM_base(oop_result, rthread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
 839 }
 840 
 841 void MacroAssembler::call_VM(Register oop_result,
 842                              Register last_java_sp,
 843                              address entry_point,
 844                              Register arg_1,
 845                              bool check_exceptions) {
 846   pass_arg1(this, arg_1);
 847   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
 848 }
 849 
 850 void MacroAssembler::call_VM(Register oop_result,
 851                              Register last_java_sp,
 852                              address entry_point,
 853                              Register arg_1,
 854                              Register arg_2,
 855                              bool check_exceptions) {
 856 
 857   assert(arg_1 != c_rarg2, "smashed arg");
 858   pass_arg2(this, arg_2);
 859   pass_arg1(this, arg_1);
 860   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
 861 }
 862 
 863 void MacroAssembler::call_VM(Register oop_result,
 864                              Register last_java_sp,
 865                              address entry_point,
 866                              Register arg_1,
 867                              Register arg_2,
 868                              Register arg_3,
 869                              bool check_exceptions) {
 870   assert(arg_1 != c_rarg3, "smashed arg");
 871   assert(arg_2 != c_rarg3, "smashed arg");
 872   pass_arg3(this, arg_3);
 873   assert(arg_1 != c_rarg2, "smashed arg");
 874   pass_arg2(this, arg_2);
 875   pass_arg1(this, arg_1);
 876   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
 877 }
 878 
 879 
 880 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
 881   ldr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
 882   str(zr, Address(java_thread, JavaThread::vm_result_offset()));
 883   verify_oop(oop_result, "broken oop in call_VM_base");
 884 }
 885 
 886 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
 887   ldr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
 888   str(zr, Address(java_thread, JavaThread::vm_result_2_offset()));
 889 }
 890 
 891 void MacroAssembler::align(int modulus) {
 892   while (offset() % modulus != 0) nop();
 893 }
 894 
 895 // these are no-ops overridden by InterpreterMacroAssembler
 896 
 897 void MacroAssembler::check_and_handle_earlyret(Register java_thread) { }
 898 
 899 void MacroAssembler::check_and_handle_popframe(Register java_thread) { }
 900 
 901 
 902 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
 903                                                       Register tmp,
 904                                                       int offset) {
 905   intptr_t value = *delayed_value_addr;
 906   if (value != 0)
 907     return RegisterOrConstant(value + offset);
 908 
 909   // load indirectly to solve generation ordering problem
 910   ldr(tmp, ExternalAddress((address) delayed_value_addr));
 911 
 912   if (offset != 0)
 913     add(tmp, tmp, offset);
 914 
 915   return RegisterOrConstant(tmp);
 916 }
 917 
 918 // Look up the method for a megamorphic invokeinterface call.
 919 // The target method is determined by <intf_klass, itable_index>.
 920 // The receiver klass is in recv_klass.
 921 // On success, the result will be in method_result, and execution falls through.
 922 // On failure, execution transfers to the given label.
 923 void MacroAssembler::lookup_interface_method(Register recv_klass,
 924                                              Register intf_klass,
 925                                              RegisterOrConstant itable_index,
 926                                              Register method_result,
 927                                              Register scan_temp,
 928                                              Label& L_no_such_interface,
 929                                              bool return_method) {
 930   assert_different_registers(recv_klass, intf_klass, scan_temp);
 931   assert_different_registers(method_result, intf_klass, scan_temp);
 932   assert(recv_klass != method_result || !return_method,
 933          "recv_klass can be destroyed when method isn't needed");
 934 
 935   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
 936          "caller must use same register for non-constant itable index as for method");
 937 
 938   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
 939   int vtable_base = InstanceKlass::vtable_start_offset() * wordSize;
 940   int itentry_off = itableMethodEntry::method_offset_in_bytes();
 941   int scan_step   = itableOffsetEntry::size() * wordSize;
 942   int vte_size    = vtableEntry::size() * wordSize;
 943   assert(vte_size == wordSize, "else adjust times_vte_scale");
 944 
 945   ldrw(scan_temp, Address(recv_klass, InstanceKlass::vtable_length_offset() * wordSize));
 946 
 947   // %%% Could store the aligned, prescaled offset in the klassoop.
 948   // lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
 949   lea(scan_temp, Address(recv_klass, scan_temp, Address::lsl(3)));
 950   add(scan_temp, scan_temp, vtable_base);
 951   if (HeapWordsPerLong > 1) {
 952     // Round up to align_object_offset boundary
 953     // see code for instanceKlass::start_of_itable!
 954     round_to(scan_temp, BytesPerLong);
 955   }
 956 
 957   if (return_method) {
 958     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
 959     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
 960     // lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
 961     lea(recv_klass, Address(recv_klass, itable_index, Address::lsl(3)));
 962     if (itentry_off)
 963       add(recv_klass, recv_klass, itentry_off);
 964   }
 965 
 966   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
 967   //   if (scan->interface() == intf) {
 968   //     result = (klass + scan->offset() + itable_index);
 969   //   }
 970   // }
 971   Label search, found_method;
 972 
 973   for (int peel = 1; peel >= 0; peel--) {
 974     ldr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
 975     cmp(intf_klass, method_result);
 976 
 977     if (peel) {
 978       br(Assembler::EQ, found_method);
 979     } else {
 980       br(Assembler::NE, search);
 981       // (invert the test to fall through to found_method...)
 982     }
 983 
 984     if (!peel)  break;
 985 
 986     bind(search);
 987 
 988     // Check that the previous entry is non-null.  A null entry means that
 989     // the receiver class doesn't implement the interface, and wasn't the
 990     // same as when the caller was compiled.
 991     cbz(method_result, L_no_such_interface);
 992     add(scan_temp, scan_temp, scan_step);
 993   }
 994 
 995   bind(found_method);
 996 
 997   if (return_method) {
 998     // Got a hit.
 999     ldrw(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
1000     ldr(method_result, Address(recv_klass, scan_temp, Address::uxtw(0)));
1001   }
1002 }
1003 
1004 // virtual method calling
1005 void MacroAssembler::lookup_virtual_method(Register recv_klass,
1006                                            RegisterOrConstant vtable_index,
1007                                            Register method_result) {
1008   const int base = InstanceKlass::vtable_start_offset() * wordSize;
1009   assert(vtableEntry::size() * wordSize == 8,
1010          "adjust the scaling in the code below");
1011   int vtable_offset_in_bytes = base + vtableEntry::method_offset_in_bytes();
1012 
1013   if (vtable_index.is_register()) {
1014     lea(method_result, Address(recv_klass,
1015                                vtable_index.as_register(),
1016                                Address::lsl(LogBytesPerWord)));
1017     ldr(method_result, Address(method_result, vtable_offset_in_bytes));
1018   } else {
1019     vtable_offset_in_bytes += vtable_index.as_constant() * wordSize;
1020     ldr(method_result,
1021         form_address(rscratch1, recv_klass, vtable_offset_in_bytes, 0));
1022   }
1023 }
1024 
1025 void MacroAssembler::check_klass_subtype(Register sub_klass,
1026                            Register super_klass,
1027                            Register temp_reg,
1028                            Label& L_success) {
1029   Label L_failure;
1030   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
1031   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
1032   bind(L_failure);
1033 }
1034 
1035 
1036 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
1037                                                    Register super_klass,
1038                                                    Register temp_reg,
1039                                                    Label* L_success,
1040                                                    Label* L_failure,
1041                                                    Label* L_slow_path,
1042                                         RegisterOrConstant super_check_offset) {
1043   assert_different_registers(sub_klass, super_klass, temp_reg);
1044   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
1045   if (super_check_offset.is_register()) {
1046     assert_different_registers(sub_klass, super_klass,
1047                                super_check_offset.as_register());
1048   } else if (must_load_sco) {
1049     assert(temp_reg != noreg, "supply either a temp or a register offset");
1050   }
1051 
1052   Label L_fallthrough;
1053   int label_nulls = 0;
1054   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
1055   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
1056   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
1057   assert(label_nulls <= 1, "at most one NULL in the batch");
1058 
1059   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1060   int sco_offset = in_bytes(Klass::super_check_offset_offset());
1061   Address super_check_offset_addr(super_klass, sco_offset);
1062 
1063   // Hacked jmp, which may only be used just before L_fallthrough.
1064 #define final_jmp(label)                                                \
1065   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
1066   else                            b(label)                /*omit semi*/
1067 
1068   // If the pointers are equal, we are done (e.g., String[] elements).
1069   // This self-check enables sharing of secondary supertype arrays among
1070   // non-primary types such as array-of-interface.  Otherwise, each such
1071   // type would need its own customized SSA.
1072   // We move this check to the front of the fast path because many
1073   // type checks are in fact trivially successful in this manner,
1074   // so we get a nicely predicted branch right at the start of the check.
1075   cmp(sub_klass, super_klass);
1076   br(Assembler::EQ, *L_success);
1077 
1078   // Check the supertype display:
1079   if (must_load_sco) {
1080     // Positive movl does right thing on LP64.
1081     ldrw(temp_reg, super_check_offset_addr);
1082     super_check_offset = RegisterOrConstant(temp_reg);
1083   }
1084   Address super_check_addr(sub_klass, super_check_offset);
1085   ldr(rscratch1, super_check_addr);
1086   cmp(super_klass, rscratch1); // load displayed supertype
1087 
1088   // This check has worked decisively for primary supers.
1089   // Secondary supers are sought in the super_cache ('super_cache_addr').
1090   // (Secondary supers are interfaces and very deeply nested subtypes.)
1091   // This works in the same check above because of a tricky aliasing
1092   // between the super_cache and the primary super display elements.
1093   // (The 'super_check_addr' can address either, as the case requires.)
1094   // Note that the cache is updated below if it does not help us find
1095   // what we need immediately.
1096   // So if it was a primary super, we can just fail immediately.
1097   // Otherwise, it's the slow path for us (no success at this point).
1098 
1099   if (super_check_offset.is_register()) {
1100     br(Assembler::EQ, *L_success);
1101     cmp(super_check_offset.as_register(), sc_offset);
1102     if (L_failure == &L_fallthrough) {
1103       br(Assembler::EQ, *L_slow_path);
1104     } else {
1105       br(Assembler::NE, *L_failure);
1106       final_jmp(*L_slow_path);
1107     }
1108   } else if (super_check_offset.as_constant() == sc_offset) {
1109     // Need a slow path; fast failure is impossible.
1110     if (L_slow_path == &L_fallthrough) {
1111       br(Assembler::EQ, *L_success);
1112     } else {
1113       br(Assembler::NE, *L_slow_path);
1114       final_jmp(*L_success);
1115     }
1116   } else {
1117     // No slow path; it's a fast decision.
1118     if (L_failure == &L_fallthrough) {
1119       br(Assembler::EQ, *L_success);
1120     } else {
1121       br(Assembler::NE, *L_failure);
1122       final_jmp(*L_success);
1123     }
1124   }
1125 
1126   bind(L_fallthrough);
1127 
1128 #undef final_jmp
1129 }
1130 
1131 // These two are taken from x86, but they look generally useful
1132 
1133 // scans count pointer sized words at [addr] for occurence of value,
1134 // generic
1135 void MacroAssembler::repne_scan(Register addr, Register value, Register count,
1136                                 Register scratch) {
1137   Label Lloop, Lexit;
1138   cbz(count, Lexit);
1139   bind(Lloop);
1140   ldr(scratch, post(addr, wordSize));
1141   cmp(value, scratch);
1142   br(EQ, Lexit);
1143   sub(count, count, 1);
1144   cbnz(count, Lloop);
1145   bind(Lexit);
1146 }
1147 
1148 // scans count 4 byte words at [addr] for occurence of value,
1149 // generic
1150 void MacroAssembler::repne_scanw(Register addr, Register value, Register count,
1151                                 Register scratch) {
1152   Label Lloop, Lexit;
1153   cbz(count, Lexit);
1154   bind(Lloop);
1155   ldrw(scratch, post(addr, wordSize));
1156   cmpw(value, scratch);
1157   br(EQ, Lexit);
1158   sub(count, count, 1);
1159   cbnz(count, Lloop);
1160   bind(Lexit);
1161 }
1162 
1163 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
1164                                                    Register super_klass,
1165                                                    Register temp_reg,
1166                                                    Register temp2_reg,
1167                                                    Label* L_success,
1168                                                    Label* L_failure,
1169                                                    bool set_cond_codes) {
1170   assert_different_registers(sub_klass, super_klass, temp_reg);
1171   if (temp2_reg != noreg)
1172     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg, rscratch1);
1173 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
1174 
1175   Label L_fallthrough;
1176   int label_nulls = 0;
1177   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
1178   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
1179   assert(label_nulls <= 1, "at most one NULL in the batch");
1180 
1181   // a couple of useful fields in sub_klass:
1182   int ss_offset = in_bytes(Klass::secondary_supers_offset());
1183   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1184   Address secondary_supers_addr(sub_klass, ss_offset);
1185   Address super_cache_addr(     sub_klass, sc_offset);
1186 
1187   BLOCK_COMMENT("check_klass_subtype_slow_path");
1188 
1189   // Do a linear scan of the secondary super-klass chain.
1190   // This code is rarely used, so simplicity is a virtue here.
1191   // The repne_scan instruction uses fixed registers, which we must spill.
1192   // Don't worry too much about pre-existing connections with the input regs.
1193 
1194   assert(sub_klass != r0, "killed reg"); // killed by mov(r0, super)
1195   assert(sub_klass != r2, "killed reg"); // killed by lea(r2, &pst_counter)
1196 
1197   // Get super_klass value into r0 (even if it was in r5 or r2).
1198   RegSet pushed_registers;
1199   if (!IS_A_TEMP(r2))    pushed_registers += r2;
1200   if (!IS_A_TEMP(r5))    pushed_registers += r5;
1201 
1202   if (super_klass != r0 || UseCompressedOops) {
1203     if (!IS_A_TEMP(r0))   pushed_registers += r0;
1204   }
1205 
1206   push(pushed_registers, sp);
1207 
1208 #ifndef PRODUCT
1209   mov(rscratch2, (address)&SharedRuntime::_partial_subtype_ctr);
1210   Address pst_counter_addr(rscratch2);
1211   ldr(rscratch1, pst_counter_addr);
1212   add(rscratch1, rscratch1, 1);
1213   str(rscratch1, pst_counter_addr);
1214 #endif //PRODUCT
1215 
1216   // We will consult the secondary-super array.
1217   ldr(r5, secondary_supers_addr);
1218   // Load the array length.  (Positive movl does right thing on LP64.)
1219   ldrw(r2, Address(r5, Array<Klass*>::length_offset_in_bytes()));
1220   // Skip to start of data.
1221   add(r5, r5, Array<Klass*>::base_offset_in_bytes());
1222 
1223   cmp(sp, zr); // Clear Z flag; SP is never zero
1224   // Scan R2 words at [R5] for an occurrence of R0.
1225   // Set NZ/Z based on last compare.
1226   repne_scan(r5, r0, r2, rscratch1);
1227 
1228   // Unspill the temp. registers:
1229   pop(pushed_registers, sp);
1230 
1231   br(Assembler::NE, *L_failure);
1232 
1233   // Success.  Cache the super we found and proceed in triumph.
1234   str(super_klass, super_cache_addr);
1235 
1236   if (L_success != &L_fallthrough) {
1237     b(*L_success);
1238   }
1239 
1240 #undef IS_A_TEMP
1241 
1242   bind(L_fallthrough);
1243 }
1244 
1245 
1246 void MacroAssembler::verify_oop(Register reg, const char* s) {
1247   if (!VerifyOops) return;
1248 
1249   // Pass register number to verify_oop_subroutine
1250   const char* b = NULL;
1251   {
1252     ResourceMark rm;
1253     stringStream ss;
1254     ss.print("verify_oop: %s: %s", reg->name(), s);
1255     b = code_string(ss.as_string());
1256   }
1257   BLOCK_COMMENT("verify_oop {");
1258 
1259   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
1260   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
1261 
1262   mov(r0, reg);
1263   mov(rscratch1, (address)b);
1264 
1265   // call indirectly to solve generation ordering problem
1266   lea(rscratch2, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
1267   ldr(rscratch2, Address(rscratch2));
1268   blr(rscratch2);
1269 
1270   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
1271   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
1272 
1273   BLOCK_COMMENT("} verify_oop");
1274 }
1275 
1276 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
1277   if (!VerifyOops) return;
1278 
1279   const char* b = NULL;
1280   {
1281     ResourceMark rm;
1282     stringStream ss;
1283     ss.print("verify_oop_addr: %s", s);
1284     b = code_string(ss.as_string());
1285   }
1286   BLOCK_COMMENT("verify_oop_addr {");
1287 
1288   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
1289   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
1290 
1291   // addr may contain sp so we will have to adjust it based on the
1292   // pushes that we just did.
1293   if (addr.uses(sp)) {
1294     lea(r0, addr);
1295     ldr(r0, Address(r0, 4 * wordSize));
1296   } else {
1297     ldr(r0, addr);
1298   }
1299   mov(rscratch1, (address)b);
1300 
1301   // call indirectly to solve generation ordering problem
1302   lea(rscratch2, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
1303   ldr(rscratch2, Address(rscratch2));
1304   blr(rscratch2);
1305 
1306   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
1307   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
1308 
1309   BLOCK_COMMENT("} verify_oop_addr");
1310 }
1311 
1312 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
1313                                          int extra_slot_offset) {
1314   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
1315   int stackElementSize = Interpreter::stackElementSize;
1316   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
1317 #ifdef ASSERT
1318   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
1319   assert(offset1 - offset == stackElementSize, "correct arithmetic");
1320 #endif
1321   if (arg_slot.is_constant()) {
1322     return Address(esp, arg_slot.as_constant() * stackElementSize
1323                    + offset);
1324   } else {
1325     add(rscratch1, esp, arg_slot.as_register(),
1326         ext::uxtx, exact_log2(stackElementSize));
1327     return Address(rscratch1, offset);
1328   }
1329 }
1330 
1331 void MacroAssembler::call_VM_leaf_base(address entry_point,
1332                                        int number_of_arguments,
1333                                        Label *retaddr) {
1334   stp(rscratch1, rmethod, Address(pre(sp, -2 * wordSize)));
1335 
1336   // We add 1 to number_of_arguments because the thread in arg0 is
1337   // not counted
1338   mov(rscratch1, entry_point);
1339   blr(rscratch1);
1340   if (retaddr)
1341     bind(*retaddr);
1342 
1343   ldp(rscratch1, rmethod, Address(post(sp, 2 * wordSize)));
1344   maybe_isb();
1345 }
1346 
1347 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
1348   call_VM_leaf_base(entry_point, number_of_arguments);
1349 }
1350 
1351 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
1352   pass_arg0(this, arg_0);
1353   call_VM_leaf_base(entry_point, 1);
1354 }
1355 
1356 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1357   pass_arg0(this, arg_0);
1358   pass_arg1(this, arg_1);
1359   call_VM_leaf_base(entry_point, 2);
1360 }
1361 
1362 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0,
1363                                   Register arg_1, Register arg_2) {
1364   pass_arg0(this, arg_0);
1365   pass_arg1(this, arg_1);
1366   pass_arg2(this, arg_2);
1367   call_VM_leaf_base(entry_point, 3);
1368 }
1369 
1370 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
1371   pass_arg0(this, arg_0);
1372   MacroAssembler::call_VM_leaf_base(entry_point, 1);
1373 }
1374 
1375 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1376 
1377   assert(arg_0 != c_rarg1, "smashed arg");
1378   pass_arg1(this, arg_1);
1379   pass_arg0(this, arg_0);
1380   MacroAssembler::call_VM_leaf_base(entry_point, 2);
1381 }
1382 
1383 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
1384   assert(arg_0 != c_rarg2, "smashed arg");
1385   assert(arg_1 != c_rarg2, "smashed arg");
1386   pass_arg2(this, arg_2);
1387   assert(arg_0 != c_rarg1, "smashed arg");
1388   pass_arg1(this, arg_1);
1389   pass_arg0(this, arg_0);
1390   MacroAssembler::call_VM_leaf_base(entry_point, 3);
1391 }
1392 
1393 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
1394   assert(arg_0 != c_rarg3, "smashed arg");
1395   assert(arg_1 != c_rarg3, "smashed arg");
1396   assert(arg_2 != c_rarg3, "smashed arg");
1397   pass_arg3(this, arg_3);
1398   assert(arg_0 != c_rarg2, "smashed arg");
1399   assert(arg_1 != c_rarg2, "smashed arg");
1400   pass_arg2(this, arg_2);
1401   assert(arg_0 != c_rarg1, "smashed arg");
1402   pass_arg1(this, arg_1);
1403   pass_arg0(this, arg_0);
1404   MacroAssembler::call_VM_leaf_base(entry_point, 4);
1405 }
1406 
1407 void MacroAssembler::null_check(Register reg, int offset) {
1408   if (needs_explicit_null_check(offset)) {
1409     // provoke OS NULL exception if reg = NULL by
1410     // accessing M[reg] w/o changing any registers
1411     // NOTE: this is plenty to provoke a segv
1412     ldr(zr, Address(reg));
1413   } else {
1414     // nothing to do, (later) access of M[reg + offset]
1415     // will provoke OS NULL exception if reg = NULL
1416   }
1417 }
1418 
1419 // MacroAssembler protected routines needed to implement
1420 // public methods
1421 
1422 void MacroAssembler::mov(Register r, Address dest) {
1423   code_section()->relocate(pc(), dest.rspec());
1424   u_int64_t imm64 = (u_int64_t)dest.target();
1425   movptr(r, imm64);
1426 }
1427 
1428 // Move a constant pointer into r.  In AArch64 mode the virtual
1429 // address space is 48 bits in size, so we only need three
1430 // instructions to create a patchable instruction sequence that can
1431 // reach anywhere.
1432 void MacroAssembler::movptr(Register r, uintptr_t imm64) {
1433 #ifndef PRODUCT
1434   {
1435     char buffer[64];
1436     snprintf(buffer, sizeof(buffer), "0x%"PRIX64, imm64);
1437     block_comment(buffer);
1438   }
1439 #endif
1440   assert(imm64 < (1ul << 48), "48-bit overflow in address constant");
1441   movz(r, imm64 & 0xffff);
1442   imm64 >>= 16;
1443   movk(r, imm64 & 0xffff, 16);
1444   imm64 >>= 16;
1445   movk(r, imm64 & 0xffff, 32);
1446 }
1447 
1448 // Macro to mov replicated immediate to vector register.
1449 //  Vd will get the following values for different arrangements in T
1450 //   imm32 == hex 000000gh  T8B:  Vd = ghghghghghghghgh
1451 //   imm32 == hex 000000gh  T16B: Vd = ghghghghghghghghghghghghghghghgh
1452 //   imm32 == hex 0000efgh  T4H:  Vd = efghefghefghefgh
1453 //   imm32 == hex 0000efgh  T8H:  Vd = efghefghefghefghefghefghefghefgh
1454 //   imm32 == hex abcdefgh  T2S:  Vd = abcdefghabcdefgh
1455 //   imm32 == hex abcdefgh  T4S:  Vd = abcdefghabcdefghabcdefghabcdefgh
1456 //   T1D/T2D: invalid
1457 void MacroAssembler::mov(FloatRegister Vd, SIMD_Arrangement T, u_int32_t imm32) {
1458   assert(T != T1D && T != T2D, "invalid arrangement");
1459   if (T == T8B || T == T16B) {
1460     assert((imm32 & ~0xff) == 0, "extraneous bits in unsigned imm32 (T8B/T16B)");
1461     movi(Vd, T, imm32 & 0xff, 0);
1462     return;
1463   }
1464   u_int32_t nimm32 = ~imm32;
1465   if (T == T4H || T == T8H) {
1466     assert((imm32  & ~0xffff) == 0, "extraneous bits in unsigned imm32 (T4H/T8H)");
1467     imm32 &= 0xffff;
1468     nimm32 &= 0xffff;
1469   }
1470   u_int32_t x = imm32;
1471   int movi_cnt = 0;
1472   int movn_cnt = 0;
1473   while (x) { if (x & 0xff) movi_cnt++; x >>= 8; }
1474   x = nimm32;
1475   while (x) { if (x & 0xff) movn_cnt++; x >>= 8; }
1476   if (movn_cnt < movi_cnt) imm32 = nimm32;
1477   unsigned lsl = 0;
1478   while (imm32 && (imm32 & 0xff) == 0) { lsl += 8; imm32 >>= 8; }
1479   if (movn_cnt < movi_cnt)
1480     mvni(Vd, T, imm32 & 0xff, lsl);
1481   else
1482     movi(Vd, T, imm32 & 0xff, lsl);
1483   imm32 >>= 8; lsl += 8;
1484   while (imm32) {
1485     while ((imm32 & 0xff) == 0) { lsl += 8; imm32 >>= 8; }
1486     if (movn_cnt < movi_cnt)
1487       bici(Vd, T, imm32 & 0xff, lsl);
1488     else
1489       orri(Vd, T, imm32 & 0xff, lsl);
1490     lsl += 8; imm32 >>= 8;
1491   }
1492 }
1493 
1494 void MacroAssembler::mov_immediate64(Register dst, u_int64_t imm64)
1495 {
1496 #ifndef PRODUCT
1497   {
1498     char buffer[64];
1499     snprintf(buffer, sizeof(buffer), "0x%"PRIX64, imm64);
1500     block_comment(buffer);
1501   }
1502 #endif
1503   if (operand_valid_for_logical_immediate(false, imm64)) {
1504     orr(dst, zr, imm64);
1505   } else {
1506     // we can use a combination of MOVZ or MOVN with
1507     // MOVK to build up the constant
1508     u_int64_t imm_h[4];
1509     int zero_count = 0;
1510     int neg_count = 0;
1511     int i;
1512     for (i = 0; i < 4; i++) {
1513       imm_h[i] = ((imm64 >> (i * 16)) & 0xffffL);
1514       if (imm_h[i] == 0) {
1515         zero_count++;
1516       } else if (imm_h[i] == 0xffffL) {
1517         neg_count++;
1518       }
1519     }
1520     if (zero_count == 4) {
1521       // one MOVZ will do
1522       movz(dst, 0);
1523     } else if (neg_count == 4) {
1524       // one MOVN will do
1525       movn(dst, 0);
1526     } else if (zero_count == 3) {
1527       for (i = 0; i < 4; i++) {
1528         if (imm_h[i] != 0L) {
1529           movz(dst, (u_int32_t)imm_h[i], (i << 4));
1530           break;
1531         }
1532       }
1533     } else if (neg_count == 3) {
1534       // one MOVN will do
1535       for (int i = 0; i < 4; i++) {
1536         if (imm_h[i] != 0xffffL) {
1537           movn(dst, (u_int32_t)imm_h[i] ^ 0xffffL, (i << 4));
1538           break;
1539         }
1540       }
1541     } else if (zero_count == 2) {
1542       // one MOVZ and one MOVK will do
1543       for (i = 0; i < 3; i++) {
1544         if (imm_h[i] != 0L) {
1545           movz(dst, (u_int32_t)imm_h[i], (i << 4));
1546           i++;
1547           break;
1548         }
1549       }
1550       for (;i < 4; i++) {
1551         if (imm_h[i] != 0L) {
1552           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1553         }
1554       }
1555     } else if (neg_count == 2) {
1556       // one MOVN and one MOVK will do
1557       for (i = 0; i < 4; i++) {
1558         if (imm_h[i] != 0xffffL) {
1559           movn(dst, (u_int32_t)imm_h[i] ^ 0xffffL, (i << 4));
1560           i++;
1561           break;
1562         }
1563       }
1564       for (;i < 4; i++) {
1565         if (imm_h[i] != 0xffffL) {
1566           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1567         }
1568       }
1569     } else if (zero_count == 1) {
1570       // one MOVZ and two MOVKs will do
1571       for (i = 0; i < 4; i++) {
1572         if (imm_h[i] != 0L) {
1573           movz(dst, (u_int32_t)imm_h[i], (i << 4));
1574           i++;
1575           break;
1576         }
1577       }
1578       for (;i < 4; i++) {
1579         if (imm_h[i] != 0x0L) {
1580           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1581         }
1582       }
1583     } else if (neg_count == 1) {
1584       // one MOVN and two MOVKs will do
1585       for (i = 0; i < 4; i++) {
1586         if (imm_h[i] != 0xffffL) {
1587           movn(dst, (u_int32_t)imm_h[i] ^ 0xffffL, (i << 4));
1588           i++;
1589           break;
1590         }
1591       }
1592       for (;i < 4; i++) {
1593         if (imm_h[i] != 0xffffL) {
1594           movk(dst, (u_int32_t)imm_h[i], (i << 4));
1595         }
1596       }
1597     } else {
1598       // use a MOVZ and 3 MOVKs (makes it easier to debug)
1599       movz(dst, (u_int32_t)imm_h[0], 0);
1600       for (i = 1; i < 4; i++) {
1601         movk(dst, (u_int32_t)imm_h[i], (i << 4));
1602       }
1603     }
1604   }
1605 }
1606 
1607 void MacroAssembler::mov_immediate32(Register dst, u_int32_t imm32)
1608 {
1609 #ifndef PRODUCT
1610     {
1611       char buffer[64];
1612       snprintf(buffer, sizeof(buffer), "0x%"PRIX32, imm32);
1613       block_comment(buffer);
1614     }
1615 #endif
1616   if (operand_valid_for_logical_immediate(true, imm32)) {
1617     orrw(dst, zr, imm32);
1618   } else {
1619     // we can use MOVZ, MOVN or two calls to MOVK to build up the
1620     // constant
1621     u_int32_t imm_h[2];
1622     imm_h[0] = imm32 & 0xffff;
1623     imm_h[1] = ((imm32 >> 16) & 0xffff);
1624     if (imm_h[0] == 0) {
1625       movzw(dst, imm_h[1], 16);
1626     } else if (imm_h[0] == 0xffff) {
1627       movnw(dst, imm_h[1] ^ 0xffff, 16);
1628     } else if (imm_h[1] == 0) {
1629       movzw(dst, imm_h[0], 0);
1630     } else if (imm_h[1] == 0xffff) {
1631       movnw(dst, imm_h[0] ^ 0xffff, 0);
1632     } else {
1633       // use a MOVZ and MOVK (makes it easier to debug)
1634       movzw(dst, imm_h[0], 0);
1635       movkw(dst, imm_h[1], 16);
1636     }
1637   }
1638 }
1639 
1640 void MacroAssembler::mov(Register dst, address addr) {
1641   assert(Universe::heap() == NULL
1642          || !Universe::heap()->is_in(addr), "use movptr for oop pointers");
1643     mov_immediate64(dst, (uintptr_t)addr);
1644 }
1645 
1646 // Form an address from base + offset in Rd.  Rd may or may
1647 // not actually be used: you must use the Address that is returned.
1648 // It is up to you to ensure that the shift provided matches the size
1649 // of your data.
1650 Address MacroAssembler::form_address(Register Rd, Register base, long byte_offset, int shift) {
1651   if (Address::offset_ok_for_immed(byte_offset, shift))
1652     // It fits; no need for any heroics
1653     return Address(base, byte_offset);
1654 
1655   // Don't do anything clever with negative or misaligned offsets
1656   unsigned mask = (1 << shift) - 1;
1657   if (byte_offset < 0 || byte_offset & mask) {
1658     mov(Rd, byte_offset);
1659     add(Rd, base, Rd);
1660     return Address(Rd);
1661   }
1662 
1663   // See if we can do this with two 12-bit offsets
1664   {
1665     unsigned long word_offset = byte_offset >> shift;
1666     unsigned long masked_offset = word_offset & 0xfff000;
1667     if (Address::offset_ok_for_immed(word_offset - masked_offset)
1668         && Assembler::operand_valid_for_add_sub_immediate(masked_offset << shift)) {
1669       add(Rd, base, masked_offset << shift);
1670       word_offset -= masked_offset;
1671       return Address(Rd, word_offset << shift);
1672     }
1673   }
1674 
1675   // Do it the hard way
1676   mov(Rd, byte_offset);
1677   add(Rd, base, Rd);
1678   return Address(Rd);
1679 }
1680 
1681 void MacroAssembler::atomic_incw(Register counter_addr, Register tmp, Register tmp2) {
1682   if (UseLSE) {
1683     mov(tmp, 1);
1684     ldadd(Assembler::word, tmp, zr, counter_addr);
1685     return;
1686   }
1687   Label retry_load;
1688   if ((VM_Version::cpu_cpuFeatures() & VM_Version::CPU_STXR_PREFETCH))
1689     prfm(Address(counter_addr), PSTL1STRM);
1690   bind(retry_load);
1691   // flush and load exclusive from the memory location
1692   ldxrw(tmp, counter_addr);
1693   addw(tmp, tmp, 1);
1694   // if we store+flush with no intervening write tmp wil be zero
1695   stxrw(tmp2, tmp, counter_addr);
1696   cbnzw(tmp2, retry_load);
1697 }
1698 
1699 
1700 int MacroAssembler::corrected_idivl(Register result, Register ra, Register rb,
1701                                     bool want_remainder, Register scratch)
1702 {
1703   // Full implementation of Java idiv and irem.  The function
1704   // returns the (pc) offset of the div instruction - may be needed
1705   // for implicit exceptions.
1706   //
1707   // constraint : ra/rb =/= scratch
1708   //         normal case
1709   //
1710   // input : ra: dividend
1711   //         rb: divisor
1712   //
1713   // result: either
1714   //         quotient  (= ra idiv rb)
1715   //         remainder (= ra irem rb)
1716 
1717   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
1718 
1719   int idivl_offset = offset();
1720   if (! want_remainder) {
1721     sdivw(result, ra, rb);
1722   } else {
1723     sdivw(scratch, ra, rb);
1724     Assembler::msubw(result, scratch, rb, ra);
1725   }
1726 
1727   return idivl_offset;
1728 }
1729 
1730 int MacroAssembler::corrected_idivq(Register result, Register ra, Register rb,
1731                                     bool want_remainder, Register scratch)
1732 {
1733   // Full implementation of Java ldiv and lrem.  The function
1734   // returns the (pc) offset of the div instruction - may be needed
1735   // for implicit exceptions.
1736   //
1737   // constraint : ra/rb =/= scratch
1738   //         normal case
1739   //
1740   // input : ra: dividend
1741   //         rb: divisor
1742   //
1743   // result: either
1744   //         quotient  (= ra idiv rb)
1745   //         remainder (= ra irem rb)
1746 
1747   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
1748 
1749   int idivq_offset = offset();
1750   if (! want_remainder) {
1751     sdiv(result, ra, rb);
1752   } else {
1753     sdiv(scratch, ra, rb);
1754     Assembler::msub(result, scratch, rb, ra);
1755   }
1756 
1757   return idivq_offset;
1758 }
1759 
1760 // MacroAssembler routines found actually to be needed
1761 
1762 void MacroAssembler::push(Register src)
1763 {
1764   str(src, Address(pre(esp, -1 * wordSize)));
1765 }
1766 
1767 void MacroAssembler::pop(Register dst)
1768 {
1769   ldr(dst, Address(post(esp, 1 * wordSize)));
1770 }
1771 
1772 // Note: load_unsigned_short used to be called load_unsigned_word.
1773 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
1774   int off = offset();
1775   ldrh(dst, src);
1776   return off;
1777 }
1778 
1779 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
1780   int off = offset();
1781   ldrb(dst, src);
1782   return off;
1783 }
1784 
1785 int MacroAssembler::load_signed_short(Register dst, Address src) {
1786   int off = offset();
1787   ldrsh(dst, src);
1788   return off;
1789 }
1790 
1791 int MacroAssembler::load_signed_byte(Register dst, Address src) {
1792   int off = offset();
1793   ldrsb(dst, src);
1794   return off;
1795 }
1796 
1797 int MacroAssembler::load_signed_short32(Register dst, Address src) {
1798   int off = offset();
1799   ldrshw(dst, src);
1800   return off;
1801 }
1802 
1803 int MacroAssembler::load_signed_byte32(Register dst, Address src) {
1804   int off = offset();
1805   ldrsbw(dst, src);
1806   return off;
1807 }
1808 
1809 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
1810   switch (size_in_bytes) {
1811   case  8:  ldr(dst, src); break;
1812   case  4:  ldrw(dst, src); break;
1813   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
1814   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
1815   default:  ShouldNotReachHere();
1816   }
1817 }
1818 
1819 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
1820   switch (size_in_bytes) {
1821   case  8:  str(src, dst); break;
1822   case  4:  strw(src, dst); break;
1823   case  2:  strh(src, dst); break;
1824   case  1:  strb(src, dst); break;
1825   default:  ShouldNotReachHere();
1826   }
1827 }
1828 
1829 void MacroAssembler::decrementw(Register reg, int value)
1830 {
1831   if (value < 0)  { incrementw(reg, -value);      return; }
1832   if (value == 0) {                               return; }
1833   if (value < (1 << 12)) { subw(reg, reg, value); return; }
1834   /* else */ {
1835     guarantee(reg != rscratch2, "invalid dst for register decrement");
1836     movw(rscratch2, (unsigned)value);
1837     subw(reg, reg, rscratch2);
1838   }
1839 }
1840 
1841 void MacroAssembler::decrement(Register reg, int value)
1842 {
1843   if (value < 0)  { increment(reg, -value);      return; }
1844   if (value == 0) {                              return; }
1845   if (value < (1 << 12)) { sub(reg, reg, value); return; }
1846   /* else */ {
1847     assert(reg != rscratch2, "invalid dst for register decrement");
1848     mov(rscratch2, (unsigned long)value);
1849     sub(reg, reg, rscratch2);
1850   }
1851 }
1852 
1853 void MacroAssembler::decrementw(Address dst, int value)
1854 {
1855   assert(!dst.uses(rscratch1), "invalid dst for address decrement");
1856   ldrw(rscratch1, dst);
1857   decrementw(rscratch1, value);
1858   strw(rscratch1, dst);
1859 }
1860 
1861 void MacroAssembler::decrement(Address dst, int value)
1862 {
1863   assert(!dst.uses(rscratch1), "invalid address for decrement");
1864   ldr(rscratch1, dst);
1865   decrement(rscratch1, value);
1866   str(rscratch1, dst);
1867 }
1868 
1869 void MacroAssembler::incrementw(Register reg, int value)
1870 {
1871   if (value < 0)  { decrementw(reg, -value);      return; }
1872   if (value == 0) {                               return; }
1873   if (value < (1 << 12)) { addw(reg, reg, value); return; }
1874   /* else */ {
1875     assert(reg != rscratch2, "invalid dst for register increment");
1876     movw(rscratch2, (unsigned)value);
1877     addw(reg, reg, rscratch2);
1878   }
1879 }
1880 
1881 void MacroAssembler::increment(Register reg, int value)
1882 {
1883   if (value < 0)  { decrement(reg, -value);      return; }
1884   if (value == 0) {                              return; }
1885   if (value < (1 << 12)) { add(reg, reg, value); return; }
1886   /* else */ {
1887     assert(reg != rscratch2, "invalid dst for register increment");
1888     movw(rscratch2, (unsigned)value);
1889     add(reg, reg, rscratch2);
1890   }
1891 }
1892 
1893 void MacroAssembler::incrementw(Address dst, int value)
1894 {
1895   assert(!dst.uses(rscratch1), "invalid dst for address increment");
1896   ldrw(rscratch1, dst);
1897   incrementw(rscratch1, value);
1898   strw(rscratch1, dst);
1899 }
1900 
1901 void MacroAssembler::increment(Address dst, int value)
1902 {
1903   assert(!dst.uses(rscratch1), "invalid dst for address increment");
1904   ldr(rscratch1, dst);
1905   increment(rscratch1, value);
1906   str(rscratch1, dst);
1907 }
1908 
1909 
1910 void MacroAssembler::pusha() {
1911   push(0x7fffffff, sp);
1912 }
1913 
1914 void MacroAssembler::popa() {
1915   pop(0x7fffffff, sp);
1916 }
1917 
1918 // Push lots of registers in the bit set supplied.  Don't push sp.
1919 // Return the number of words pushed
1920 int MacroAssembler::push(unsigned int bitset, Register stack) {
1921   int words_pushed = 0;
1922 
1923   // Scan bitset to accumulate register pairs
1924   unsigned char regs[32];
1925   int count = 0;
1926   for (int reg = 0; reg <= 30; reg++) {
1927     if (1 & bitset)
1928       regs[count++] = reg;
1929     bitset >>= 1;
1930   }
1931   regs[count++] = zr->encoding_nocheck();
1932   count &= ~1;  // Only push an even nuber of regs
1933 
1934   if (count) {
1935     stp(as_Register(regs[0]), as_Register(regs[1]),
1936        Address(pre(stack, -count * wordSize)));
1937     words_pushed += 2;
1938   }
1939   for (int i = 2; i < count; i += 2) {
1940     stp(as_Register(regs[i]), as_Register(regs[i+1]),
1941        Address(stack, i * wordSize));
1942     words_pushed += 2;
1943   }
1944 
1945   assert(words_pushed == count, "oops, pushed != count");
1946 
1947   return count;
1948 }
1949 
1950 int MacroAssembler::pop(unsigned int bitset, Register stack) {
1951   int words_pushed = 0;
1952 
1953   // Scan bitset to accumulate register pairs
1954   unsigned char regs[32];
1955   int count = 0;
1956   for (int reg = 0; reg <= 30; reg++) {
1957     if (1 & bitset)
1958       regs[count++] = reg;
1959     bitset >>= 1;
1960   }
1961   regs[count++] = zr->encoding_nocheck();
1962   count &= ~1;
1963 
1964   for (int i = 2; i < count; i += 2) {
1965     ldp(as_Register(regs[i]), as_Register(regs[i+1]),
1966        Address(stack, i * wordSize));
1967     words_pushed += 2;
1968   }
1969   if (count) {
1970     ldp(as_Register(regs[0]), as_Register(regs[1]),
1971        Address(post(stack, count * wordSize)));
1972     words_pushed += 2;
1973   }
1974 
1975   assert(words_pushed == count, "oops, pushed != count");
1976 
1977   return count;
1978 }
1979 #ifdef ASSERT
1980 void MacroAssembler::verify_heapbase(const char* msg) {
1981 #if 0
1982   assert (UseCompressedOops || UseCompressedClassPointers, "should be compressed");
1983   assert (Universe::heap() != NULL, "java heap should be initialized");
1984   if (CheckCompressedOops) {
1985     Label ok;
1986     push(1 << rscratch1->encoding(), sp); // cmpptr trashes rscratch1
1987     cmpptr(rheapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
1988     br(Assembler::EQ, ok);
1989     stop(msg);
1990     bind(ok);
1991     pop(1 << rscratch1->encoding(), sp);
1992   }
1993 #endif
1994 }
1995 #endif
1996 
1997 void MacroAssembler::stop(const char* msg) {
1998   address ip = pc();
1999   pusha();
2000   mov(c_rarg0, (address)msg);
2001   mov(c_rarg1, (address)ip);
2002   mov(c_rarg2, sp);
2003   mov(c_rarg3, CAST_FROM_FN_PTR(address, MacroAssembler::debug64));
2004   blr(c_rarg3);
2005   hlt(0);
2006 }
2007 
2008 void MacroAssembler::warn(const char* msg) {
2009   pusha();
2010   mov(c_rarg0, (address)msg);
2011   mov(lr, CAST_FROM_FN_PTR(address, warning));
2012   blr(lr);
2013   popa();
2014 }
2015 
2016 // If a constant does not fit in an immediate field, generate some
2017 // number of MOV instructions and then perform the operation.
2018 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, unsigned imm,
2019                                            add_sub_imm_insn insn1,
2020                                            add_sub_reg_insn insn2) {
2021   assert(Rd != zr, "Rd = zr and not setting flags?");
2022   if (operand_valid_for_add_sub_immediate((int)imm)) {
2023     (this->*insn1)(Rd, Rn, imm);
2024   } else {
2025     if (uabs(imm) < (1 << 24)) {
2026        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
2027        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
2028     } else {
2029        assert_different_registers(Rd, Rn);
2030        mov(Rd, (uint64_t)imm);
2031        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2032     }
2033   }
2034 }
2035 
2036 // Seperate vsn which sets the flags. Optimisations are more restricted
2037 // because we must set the flags correctly.
2038 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, unsigned imm,
2039                                            add_sub_imm_insn insn1,
2040                                            add_sub_reg_insn insn2) {
2041   if (operand_valid_for_add_sub_immediate((int)imm)) {
2042     (this->*insn1)(Rd, Rn, imm);
2043   } else {
2044     assert_different_registers(Rd, Rn);
2045     assert(Rd != zr, "overflow in immediate operand");
2046     mov(Rd, (uint64_t)imm);
2047     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2048   }
2049 }
2050 
2051 
2052 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
2053   if (increment.is_register()) {
2054     add(Rd, Rn, increment.as_register());
2055   } else {
2056     add(Rd, Rn, increment.as_constant());
2057   }
2058 }
2059 
2060 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
2061   if (increment.is_register()) {
2062     addw(Rd, Rn, increment.as_register());
2063   } else {
2064     addw(Rd, Rn, increment.as_constant());
2065   }
2066 }
2067 
2068 void MacroAssembler::sub(Register Rd, Register Rn, RegisterOrConstant decrement) {
2069   if (decrement.is_register()) {
2070     sub(Rd, Rn, decrement.as_register());
2071   } else {
2072     sub(Rd, Rn, decrement.as_constant());
2073   }
2074 }
2075 
2076 void MacroAssembler::subw(Register Rd, Register Rn, RegisterOrConstant decrement) {
2077   if (decrement.is_register()) {
2078     subw(Rd, Rn, decrement.as_register());
2079   } else {
2080     subw(Rd, Rn, decrement.as_constant());
2081   }
2082 }
2083 
2084 void MacroAssembler::reinit_heapbase()
2085 {
2086   if (UseCompressedOops) {
2087     if (Universe::is_fully_initialized()) {
2088       mov(rheapbase, Universe::narrow_ptrs_base());
2089     } else {
2090       lea(rheapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
2091       ldr(rheapbase, Address(rheapbase));
2092     }
2093   }
2094 }
2095 
2096 // this simulates the behaviour of the x86 cmpxchg instruction using a
2097 // load linked/store conditional pair. we use the acquire/release
2098 // versions of these instructions so that we flush pending writes as
2099 // per Java semantics.
2100 
2101 // n.b the x86 version assumes the old value to be compared against is
2102 // in rax and updates rax with the value located in memory if the
2103 // cmpxchg fails. we supply a register for the old value explicitly
2104 
2105 // the aarch64 load linked/store conditional instructions do not
2106 // accept an offset. so, unlike x86, we must provide a plain register
2107 // to identify the memory word to be compared/exchanged rather than a
2108 // register+offset Address.
2109 
2110 void MacroAssembler::cmpxchgptr(Register oldv, Register newv, Register addr, Register tmp,
2111                                 Label &succeed, Label *fail) {
2112   // oldv holds comparison value
2113   // newv holds value to write in exchange
2114   // addr identifies memory word to compare against/update
2115   if (UseLSE) {
2116     mov(tmp, oldv);
2117     casal(Assembler::xword, oldv, newv, addr);
2118     cmp(tmp, oldv);
2119     br(Assembler::EQ, succeed);
2120     membar(AnyAny);
2121   } else {
2122     Label retry_load, nope;
2123     if ((VM_Version::cpu_cpuFeatures() & VM_Version::CPU_STXR_PREFETCH))
2124       prfm(Address(addr), PSTL1STRM);
2125     bind(retry_load);
2126     // flush and load exclusive from the memory location
2127     // and fail if it is not what we expect
2128     ldaxr(tmp, addr);
2129     cmp(tmp, oldv);
2130     br(Assembler::NE, nope);
2131     // if we store+flush with no intervening write tmp wil be zero
2132     stlxr(tmp, newv, addr);
2133     cbzw(tmp, succeed);
2134     // retry so we only ever return after a load fails to compare
2135     // ensures we don't return a stale value after a failed write.
2136     b(retry_load);
2137     // if the memory word differs we return it in oldv and signal a fail
2138     bind(nope);
2139     membar(AnyAny);
2140     mov(oldv, tmp);
2141   }
2142   if (fail)
2143     b(*fail);
2144 }
2145 
2146 void MacroAssembler::cmpxchgw(Register oldv, Register newv, Register addr, Register tmp,
2147                                 Label &succeed, Label *fail) {
2148   // oldv holds comparison value
2149   // newv holds value to write in exchange
2150   // addr identifies memory word to compare against/update
2151   // tmp returns 0/1 for success/failure
2152   if (UseLSE) {
2153     mov(tmp, oldv);
2154     casal(Assembler::word, oldv, newv, addr);
2155     cmp(tmp, oldv);
2156     br(Assembler::EQ, succeed);
2157     membar(AnyAny);
2158   } else {
2159     Label retry_load, nope;
2160     if ((VM_Version::cpu_cpuFeatures() & VM_Version::CPU_STXR_PREFETCH))
2161       prfm(Address(addr), PSTL1STRM);
2162     bind(retry_load);
2163     // flush and load exclusive from the memory location
2164     // and fail if it is not what we expect
2165     ldaxrw(tmp, addr);
2166     cmp(tmp, oldv);
2167     br(Assembler::NE, nope);
2168     // if we store+flush with no intervening write tmp wil be zero
2169     stlxrw(tmp, newv, addr);
2170     cbzw(tmp, succeed);
2171     // retry so we only ever return after a load fails to compare
2172     // ensures we don't return a stale value after a failed write.
2173     b(retry_load);
2174     // if the memory word differs we return it in oldv and signal a fail
2175     bind(nope);
2176     membar(AnyAny);
2177     mov(oldv, tmp);
2178   }
2179   if (fail)
2180     b(*fail);
2181 }
2182 
2183 // A generic CAS; success or failure is in the EQ flag.
2184 void MacroAssembler::cmpxchg(Register addr, Register expected,
2185                              Register new_val,
2186                              enum operand_size size,
2187                              bool acquire, bool release,
2188                              Register tmp) {
2189   if (UseLSE) {
2190     mov(tmp, expected);
2191     lse_cas(tmp, new_val, addr, size, acquire, release, /*not_pair*/ true);
2192     cmp(tmp, expected);
2193   } else {
2194     BLOCK_COMMENT("cmpxchg {");
2195     Label retry_load, done;
2196     if ((VM_Version::cpu_cpuFeatures() & VM_Version::CPU_STXR_PREFETCH))
2197       prfm(Address(addr), PSTL1STRM);
2198     bind(retry_load);
2199     load_exclusive(tmp, addr, size, acquire);
2200     if (size == xword)
2201       cmp(tmp, expected);
2202     else
2203       cmpw(tmp, expected);
2204     br(Assembler::NE, done);
2205     store_exclusive(tmp, new_val, addr, size, release);
2206     cbnzw(tmp, retry_load);
2207     bind(done);
2208     BLOCK_COMMENT("} cmpxchg");
2209   }
2210 }
2211 
2212 static bool different(Register a, RegisterOrConstant b, Register c) {
2213   if (b.is_constant())
2214     return a != c;
2215   else
2216     return a != b.as_register() && a != c && b.as_register() != c;
2217 }
2218 
2219 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
2220 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
2221   if (UseLSE) {                                                         \
2222     prev = prev->is_valid() ? prev : zr;                                \
2223     if (incr.is_register()) {                                           \
2224       AOP(sz, incr.as_register(), prev, addr);                          \
2225     } else {                                                            \
2226       mov(rscratch2, incr.as_constant());                               \
2227       AOP(sz, rscratch2, prev, addr);                                   \
2228     }                                                                   \
2229     return;                                                             \
2230   }                                                                     \
2231   Register result = rscratch2;                                          \
2232   if (prev->is_valid())                                                 \
2233     result = different(prev, incr, addr) ? prev : rscratch2;            \
2234                                                                         \
2235   Label retry_load;                                                     \
2236   if ((VM_Version::cpu_cpuFeatures() & VM_Version::CPU_STXR_PREFETCH))         \
2237     prfm(Address(addr), PSTL1STRM);                                     \
2238   bind(retry_load);                                                     \
2239   LDXR(result, addr);                                                   \
2240   OP(rscratch1, result, incr);                                          \
2241   STXR(rscratch2, rscratch1, addr);                                     \
2242   cbnzw(rscratch2, retry_load);                                         \
2243   if (prev->is_valid() && prev != result) {                             \
2244     IOP(prev, rscratch1, incr);                                         \
2245   }                                                                     \
2246 }
2247 
2248 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
2249 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
2250 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
2251 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
2252 
2253 #undef ATOMIC_OP
2254 
2255 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
2256 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
2257   if (UseLSE) {                                                         \
2258     prev = prev->is_valid() ? prev : zr;                                \
2259     AOP(sz, newv, prev, addr);                                          \
2260     return;                                                             \
2261   }                                                                     \
2262   Register result = rscratch2;                                          \
2263   if (prev->is_valid())                                                 \
2264     result = different(prev, newv, addr) ? prev : rscratch2;            \
2265                                                                         \
2266   Label retry_load;                                                     \
2267   if ((VM_Version::cpu_cpuFeatures() & VM_Version::CPU_STXR_PREFETCH))         \
2268     prfm(Address(addr), PSTL1STRM);                                     \
2269   bind(retry_load);                                                     \
2270   LDXR(result, addr);                                                   \
2271   STXR(rscratch1, newv, addr);                                          \
2272   cbnzw(rscratch1, retry_load);                                         \
2273   if (prev->is_valid() && prev != result)                               \
2274     mov(prev, result);                                                  \
2275 }
2276 
2277 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
2278 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
2279 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
2280 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
2281 
2282 #undef ATOMIC_XCHG
2283 
2284 void MacroAssembler::incr_allocated_bytes(Register thread,
2285                                           Register var_size_in_bytes,
2286                                           int con_size_in_bytes,
2287                                           Register t1) {
2288   if (!thread->is_valid()) {
2289     thread = rthread;
2290   }
2291   assert(t1->is_valid(), "need temp reg");
2292 
2293   ldr(t1, Address(thread, in_bytes(JavaThread::allocated_bytes_offset())));
2294   if (var_size_in_bytes->is_valid()) {
2295     add(t1, t1, var_size_in_bytes);
2296   } else {
2297     add(t1, t1, con_size_in_bytes);
2298   }
2299   str(t1, Address(thread, in_bytes(JavaThread::allocated_bytes_offset())));
2300 }
2301 
2302 #ifndef PRODUCT
2303 extern "C" void findpc(intptr_t x);
2304 #endif
2305 
2306 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
2307 {
2308   // In order to get locks to work, we need to fake a in_VM state
2309   if (ShowMessageBoxOnError ) {
2310     JavaThread* thread = JavaThread::current();
2311     JavaThreadState saved_state = thread->thread_state();
2312     thread->set_thread_state(_thread_in_vm);
2313 #ifndef PRODUCT
2314     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
2315       ttyLocker ttyl;
2316       BytecodeCounter::print();
2317     }
2318 #endif
2319     if (os::message_box(msg, "Execution stopped, print registers?")) {
2320       ttyLocker ttyl;
2321       tty->print_cr(" pc = 0x%016lx", pc);
2322 #ifndef PRODUCT
2323       tty->cr();
2324       findpc(pc);
2325       tty->cr();
2326 #endif
2327       tty->print_cr(" r0 = 0x%016lx", regs[0]);
2328       tty->print_cr(" r1 = 0x%016lx", regs[1]);
2329       tty->print_cr(" r2 = 0x%016lx", regs[2]);
2330       tty->print_cr(" r3 = 0x%016lx", regs[3]);
2331       tty->print_cr(" r4 = 0x%016lx", regs[4]);
2332       tty->print_cr(" r5 = 0x%016lx", regs[5]);
2333       tty->print_cr(" r6 = 0x%016lx", regs[6]);
2334       tty->print_cr(" r7 = 0x%016lx", regs[7]);
2335       tty->print_cr(" r8 = 0x%016lx", regs[8]);
2336       tty->print_cr(" r9 = 0x%016lx", regs[9]);
2337       tty->print_cr("r10 = 0x%016lx", regs[10]);
2338       tty->print_cr("r11 = 0x%016lx", regs[11]);
2339       tty->print_cr("r12 = 0x%016lx", regs[12]);
2340       tty->print_cr("r13 = 0x%016lx", regs[13]);
2341       tty->print_cr("r14 = 0x%016lx", regs[14]);
2342       tty->print_cr("r15 = 0x%016lx", regs[15]);
2343       tty->print_cr("r16 = 0x%016lx", regs[16]);
2344       tty->print_cr("r17 = 0x%016lx", regs[17]);
2345       tty->print_cr("r18 = 0x%016lx", regs[18]);
2346       tty->print_cr("r19 = 0x%016lx", regs[19]);
2347       tty->print_cr("r20 = 0x%016lx", regs[20]);
2348       tty->print_cr("r21 = 0x%016lx", regs[21]);
2349       tty->print_cr("r22 = 0x%016lx", regs[22]);
2350       tty->print_cr("r23 = 0x%016lx", regs[23]);
2351       tty->print_cr("r24 = 0x%016lx", regs[24]);
2352       tty->print_cr("r25 = 0x%016lx", regs[25]);
2353       tty->print_cr("r26 = 0x%016lx", regs[26]);
2354       tty->print_cr("r27 = 0x%016lx", regs[27]);
2355       tty->print_cr("r28 = 0x%016lx", regs[28]);
2356       tty->print_cr("r30 = 0x%016lx", regs[30]);
2357       tty->print_cr("r31 = 0x%016lx", regs[31]);
2358       BREAKPOINT;
2359     }
2360     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
2361   } else {
2362     ttyLocker ttyl;
2363     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
2364                     msg);
2365     assert(false, err_msg("DEBUG MESSAGE: %s", msg));
2366   }
2367 }
2368 
2369 void MacroAssembler::push_call_clobbered_fp_registers() {
2370   // Push v0-v7, v16-v31.
2371   for (int i = 30; i >= 0; i -= 2) {
2372     if (i <= v7->encoding() || i >= v16->encoding()) {
2373       stpd(as_FloatRegister(i), as_FloatRegister(i+1),
2374            Address(pre(sp, -2 * wordSize)));
2375     }
2376   }
2377 }
2378 
2379 void MacroAssembler::pop_call_clobbered_fp_registers() {
2380 
2381   for (int i = 0; i < 32; i += 2) {
2382     if (i <= v7->encoding() || i >= v16->encoding()) {
2383       ldpd(as_FloatRegister(i), as_FloatRegister(i+1),
2384            Address(post(sp, 2 * wordSize)));
2385     }
2386   }
2387 }
2388 
2389 void MacroAssembler::push_call_clobbered_registers() {
2390   push(RegSet::range(r0, r18) - RegSet::of(rscratch1, rscratch2), sp);
2391 
2392   push_call_clobbered_fp_registers();
2393 }
2394 
2395 void MacroAssembler::pop_call_clobbered_registers() {
2396 
2397   pop_call_clobbered_fp_registers();
2398 
2399   pop(RegSet::range(r0, r18) - RegSet::of(rscratch1, rscratch2), sp);
2400 }
2401 
2402 void MacroAssembler::push_CPU_state(bool save_vectors) {
2403   push(0x3fffffff, sp);         // integer registers except lr & sp
2404 
2405   if (!save_vectors) {
2406     for (int i = 30; i >= 0; i -= 2)
2407       stpd(as_FloatRegister(i), as_FloatRegister(i+1),
2408            Address(pre(sp, -2 * wordSize)));
2409   } else {
2410     for (int i = 30; i >= 0; i -= 2)
2411       stpq(as_FloatRegister(i), as_FloatRegister(i+1),
2412            Address(pre(sp, -4 * wordSize)));
2413   }
2414 }
2415 
2416 void MacroAssembler::pop_CPU_state(bool restore_vectors) {
2417   if (!restore_vectors) {
2418     for (int i = 0; i < 32; i += 2)
2419       ldpd(as_FloatRegister(i), as_FloatRegister(i+1),
2420            Address(post(sp, 2 * wordSize)));
2421   } else {
2422     for (int i = 0; i < 32; i += 2)
2423       ldpq(as_FloatRegister(i), as_FloatRegister(i+1),
2424            Address(post(sp, 4 * wordSize)));
2425   }
2426 
2427   pop(0x3fffffff, sp);         // integer registers except lr & sp
2428 }
2429 
2430 /**
2431  * Helpers for multiply_to_len().
2432  */
2433 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
2434                                      Register src1, Register src2) {
2435   adds(dest_lo, dest_lo, src1);
2436   adc(dest_hi, dest_hi, zr);
2437   adds(dest_lo, dest_lo, src2);
2438   adc(final_dest_hi, dest_hi, zr);
2439 }
2440 
2441 // Generate an address from (r + r1 extend offset).  "size" is the
2442 // size of the operand.  The result may be in rscratch2.
2443 Address MacroAssembler::offsetted_address(Register r, Register r1,
2444                                           Address::extend ext, int offset, int size) {
2445   if (offset || (ext.shift() % size != 0)) {
2446     lea(rscratch2, Address(r, r1, ext));
2447     return Address(rscratch2, offset);
2448   } else {
2449     return Address(r, r1, ext);
2450   }
2451 }
2452 
2453 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
2454 {
2455   assert(offset >= 0, "spill to negative address?");
2456   // Offset reachable ?
2457   //   Not aligned - 9 bits signed offset
2458   //   Aligned - 12 bits unsigned offset shifted
2459   Register base = sp;
2460   if ((offset & (size-1)) && offset >= (1<<8)) {
2461     add(tmp, base, offset & ((1<<12)-1));
2462     base = tmp;
2463     offset &= -1<<12;
2464   }
2465 
2466   if (offset >= (1<<12) * size) {
2467     add(tmp, base, offset & (((1<<12)-1)<<12));
2468     base = tmp;
2469     offset &= ~(((1<<12)-1)<<12);
2470   }
2471 
2472   return Address(base, offset);
2473 }
2474 
2475 /**
2476  * Multiply 64 bit by 64 bit first loop.
2477  */
2478 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
2479                                            Register y, Register y_idx, Register z,
2480                                            Register carry, Register product,
2481                                            Register idx, Register kdx) {
2482   //
2483   //  jlong carry, x[], y[], z[];
2484   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2485   //    huge_128 product = y[idx] * x[xstart] + carry;
2486   //    z[kdx] = (jlong)product;
2487   //    carry  = (jlong)(product >>> 64);
2488   //  }
2489   //  z[xstart] = carry;
2490   //
2491 
2492   Label L_first_loop, L_first_loop_exit;
2493   Label L_one_x, L_one_y, L_multiply;
2494 
2495   subsw(xstart, xstart, 1);
2496   br(Assembler::MI, L_one_x);
2497 
2498   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
2499   ldr(x_xstart, Address(rscratch1));
2500   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
2501 
2502   bind(L_first_loop);
2503   subsw(idx, idx, 1);
2504   br(Assembler::MI, L_first_loop_exit);
2505   subsw(idx, idx, 1);
2506   br(Assembler::MI, L_one_y);
2507   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2508   ldr(y_idx, Address(rscratch1));
2509   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
2510   bind(L_multiply);
2511 
2512   // AArch64 has a multiply-accumulate instruction that we can't use
2513   // here because it has no way to process carries, so we have to use
2514   // separate add and adc instructions.  Bah.
2515   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
2516   mul(product, x_xstart, y_idx);
2517   adds(product, product, carry);
2518   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
2519 
2520   subw(kdx, kdx, 2);
2521   ror(product, product, 32); // back to big-endian
2522   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
2523 
2524   b(L_first_loop);
2525 
2526   bind(L_one_y);
2527   ldrw(y_idx, Address(y,  0));
2528   b(L_multiply);
2529 
2530   bind(L_one_x);
2531   ldrw(x_xstart, Address(x,  0));
2532   b(L_first_loop);
2533 
2534   bind(L_first_loop_exit);
2535 }
2536 
2537 /**
2538  * Multiply 128 bit by 128. Unrolled inner loop.
2539  *
2540  */
2541 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
2542                                              Register carry, Register carry2,
2543                                              Register idx, Register jdx,
2544                                              Register yz_idx1, Register yz_idx2,
2545                                              Register tmp, Register tmp3, Register tmp4,
2546                                              Register tmp6, Register product_hi) {
2547 
2548   //   jlong carry, x[], y[], z[];
2549   //   int kdx = ystart+1;
2550   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
2551   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
2552   //     jlong carry2  = (jlong)(tmp3 >>> 64);
2553   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
2554   //     carry  = (jlong)(tmp4 >>> 64);
2555   //     z[kdx+idx+1] = (jlong)tmp3;
2556   //     z[kdx+idx] = (jlong)tmp4;
2557   //   }
2558   //   idx += 2;
2559   //   if (idx > 0) {
2560   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
2561   //     z[kdx+idx] = (jlong)yz_idx1;
2562   //     carry  = (jlong)(yz_idx1 >>> 64);
2563   //   }
2564   //
2565 
2566   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
2567 
2568   lsrw(jdx, idx, 2);
2569 
2570   bind(L_third_loop);
2571 
2572   subsw(jdx, jdx, 1);
2573   br(Assembler::MI, L_third_loop_exit);
2574   subw(idx, idx, 4);
2575 
2576   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2577 
2578   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
2579 
2580   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2581 
2582   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
2583   ror(yz_idx2, yz_idx2, 32);
2584 
2585   ldp(rscratch2, rscratch1, Address(tmp6, 0));
2586 
2587   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2588   umulh(tmp4, product_hi, yz_idx1);
2589 
2590   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
2591   ror(rscratch2, rscratch2, 32);
2592 
2593   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
2594   umulh(carry2, product_hi, yz_idx2);
2595 
2596   // propagate sum of both multiplications into carry:tmp4:tmp3
2597   adds(tmp3, tmp3, carry);
2598   adc(tmp4, tmp4, zr);
2599   adds(tmp3, tmp3, rscratch1);
2600   adcs(tmp4, tmp4, tmp);
2601   adc(carry, carry2, zr);
2602   adds(tmp4, tmp4, rscratch2);
2603   adc(carry, carry, zr);
2604 
2605   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
2606   ror(tmp4, tmp4, 32);
2607   stp(tmp4, tmp3, Address(tmp6, 0));
2608 
2609   b(L_third_loop);
2610   bind (L_third_loop_exit);
2611 
2612   andw (idx, idx, 0x3);
2613   cbz(idx, L_post_third_loop_done);
2614 
2615   Label L_check_1;
2616   subsw(idx, idx, 2);
2617   br(Assembler::MI, L_check_1);
2618 
2619   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2620   ldr(yz_idx1, Address(rscratch1, 0));
2621   ror(yz_idx1, yz_idx1, 32);
2622   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2623   umulh(tmp4, product_hi, yz_idx1);
2624   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2625   ldr(yz_idx2, Address(rscratch1, 0));
2626   ror(yz_idx2, yz_idx2, 32);
2627 
2628   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
2629 
2630   ror(tmp3, tmp3, 32);
2631   str(tmp3, Address(rscratch1, 0));
2632 
2633   bind (L_check_1);
2634 
2635   andw (idx, idx, 0x1);
2636   subsw(idx, idx, 1);
2637   br(Assembler::MI, L_post_third_loop_done);
2638   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2639   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
2640   umulh(carry2, tmp4, product_hi);
2641   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2642 
2643   add2_with_carry(carry2, tmp3, tmp4, carry);
2644 
2645   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2646   extr(carry, carry2, tmp3, 32);
2647 
2648   bind(L_post_third_loop_done);
2649 }
2650 
2651 /**
2652  * Code for BigInteger::multiplyToLen() instrinsic.
2653  *
2654  * r0: x
2655  * r1: xlen
2656  * r2: y
2657  * r3: ylen
2658  * r4:  z
2659  * r5: zlen
2660  * r10: tmp1
2661  * r11: tmp2
2662  * r12: tmp3
2663  * r13: tmp4
2664  * r14: tmp5
2665  * r15: tmp6
2666  * r16: tmp7
2667  *
2668  */
2669 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
2670                                      Register z, Register zlen,
2671                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
2672                                      Register tmp5, Register tmp6, Register product_hi) {
2673 
2674   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6);
2675 
2676   const Register idx = tmp1;
2677   const Register kdx = tmp2;
2678   const Register xstart = tmp3;
2679 
2680   const Register y_idx = tmp4;
2681   const Register carry = tmp5;
2682   const Register product  = xlen;
2683   const Register x_xstart = zlen;  // reuse register
2684 
2685   // First Loop.
2686   //
2687   //  final static long LONG_MASK = 0xffffffffL;
2688   //  int xstart = xlen - 1;
2689   //  int ystart = ylen - 1;
2690   //  long carry = 0;
2691   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2692   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
2693   //    z[kdx] = (int)product;
2694   //    carry = product >>> 32;
2695   //  }
2696   //  z[xstart] = (int)carry;
2697   //
2698 
2699   movw(idx, ylen);      // idx = ylen;
2700   movw(kdx, zlen);      // kdx = xlen+ylen;
2701   mov(carry, zr);       // carry = 0;
2702 
2703   Label L_done;
2704 
2705   movw(xstart, xlen);
2706   subsw(xstart, xstart, 1);
2707   br(Assembler::MI, L_done);
2708 
2709   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
2710 
2711   Label L_second_loop;
2712   cbzw(kdx, L_second_loop);
2713 
2714   Label L_carry;
2715   subw(kdx, kdx, 1);
2716   cbzw(kdx, L_carry);
2717 
2718   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
2719   lsr(carry, carry, 32);
2720   subw(kdx, kdx, 1);
2721 
2722   bind(L_carry);
2723   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
2724 
2725   // Second and third (nested) loops.
2726   //
2727   // for (int i = xstart-1; i >= 0; i--) { // Second loop
2728   //   carry = 0;
2729   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
2730   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
2731   //                    (z[k] & LONG_MASK) + carry;
2732   //     z[k] = (int)product;
2733   //     carry = product >>> 32;
2734   //   }
2735   //   z[i] = (int)carry;
2736   // }
2737   //
2738   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
2739 
2740   const Register jdx = tmp1;
2741 
2742   bind(L_second_loop);
2743   mov(carry, zr);                // carry = 0;
2744   movw(jdx, ylen);               // j = ystart+1
2745 
2746   subsw(xstart, xstart, 1);      // i = xstart-1;
2747   br(Assembler::MI, L_done);
2748 
2749   str(z, Address(pre(sp, -4 * wordSize)));
2750 
2751   Label L_last_x;
2752   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
2753   subsw(xstart, xstart, 1);       // i = xstart-1;
2754   br(Assembler::MI, L_last_x);
2755 
2756   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
2757   ldr(product_hi, Address(rscratch1));
2758   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
2759 
2760   Label L_third_loop_prologue;
2761   bind(L_third_loop_prologue);
2762 
2763   str(ylen, Address(sp, wordSize));
2764   stp(x, xstart, Address(sp, 2 * wordSize));
2765   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
2766                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
2767   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
2768   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
2769 
2770   addw(tmp3, xlen, 1);
2771   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
2772   subsw(tmp3, tmp3, 1);
2773   br(Assembler::MI, L_done);
2774 
2775   lsr(carry, carry, 32);
2776   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
2777   b(L_second_loop);
2778 
2779   // Next infrequent code is moved outside loops.
2780   bind(L_last_x);
2781   ldrw(product_hi, Address(x,  0));
2782   b(L_third_loop_prologue);
2783 
2784   bind(L_done);
2785 }
2786 
2787 /**
2788  * Emits code to update CRC-32 with a byte value according to constants in table
2789  *
2790  * @param [in,out]crc   Register containing the crc.
2791  * @param [in]val       Register containing the byte to fold into the CRC.
2792  * @param [in]table     Register containing the table of crc constants.
2793  *
2794  * uint32_t crc;
2795  * val = crc_table[(val ^ crc) & 0xFF];
2796  * crc = val ^ (crc >> 8);
2797  *
2798  */
2799 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
2800   eor(val, val, crc);
2801   andr(val, val, 0xff);
2802   ldrw(val, Address(table, val, Address::lsl(2)));
2803   eor(crc, val, crc, Assembler::LSR, 8);
2804 }
2805 
2806 /**
2807  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
2808  *
2809  * @param [in,out]crc   Register containing the crc.
2810  * @param [in]v         Register containing the 32-bit to fold into the CRC.
2811  * @param [in]table0    Register containing table 0 of crc constants.
2812  * @param [in]table1    Register containing table 1 of crc constants.
2813  * @param [in]table2    Register containing table 2 of crc constants.
2814  * @param [in]table3    Register containing table 3 of crc constants.
2815  *
2816  * uint32_t crc;
2817  *   v = crc ^ v
2818  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
2819  *
2820  */
2821 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
2822         Register table0, Register table1, Register table2, Register table3,
2823         bool upper) {
2824   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
2825   uxtb(tmp, v);
2826   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
2827   ubfx(tmp, v, 8, 8);
2828   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
2829   eor(crc, crc, tmp);
2830   ubfx(tmp, v, 16, 8);
2831   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
2832   eor(crc, crc, tmp);
2833   ubfx(tmp, v, 24, 8);
2834   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
2835   eor(crc, crc, tmp);
2836 }
2837 
2838 /**
2839  * @param crc   register containing existing CRC (32-bit)
2840  * @param buf   register pointing to input byte buffer (byte*)
2841  * @param len   register containing number of bytes
2842  * @param table register that will contain address of CRC table
2843  * @param tmp   scratch register
2844  */
2845 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
2846         Register table0, Register table1, Register table2, Register table3,
2847         Register tmp, Register tmp2, Register tmp3) {
2848   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
2849   unsigned long offset;
2850 
2851     ornw(crc, zr, crc);
2852 
2853   if (UseCRC32) {
2854     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop;
2855 
2856       subs(len, len, 64);
2857       br(Assembler::GE, CRC_by64_loop);
2858       adds(len, len, 64-4);
2859       br(Assembler::GE, CRC_by4_loop);
2860       adds(len, len, 4);
2861       br(Assembler::GT, CRC_by1_loop);
2862       b(L_exit);
2863 
2864     BIND(CRC_by4_loop);
2865       ldrw(tmp, Address(post(buf, 4)));
2866       subs(len, len, 4);
2867       crc32w(crc, crc, tmp);
2868       br(Assembler::GE, CRC_by4_loop);
2869       adds(len, len, 4);
2870       br(Assembler::LE, L_exit);
2871     BIND(CRC_by1_loop);
2872       ldrb(tmp, Address(post(buf, 1)));
2873       subs(len, len, 1);
2874       crc32b(crc, crc, tmp);
2875       br(Assembler::GT, CRC_by1_loop);
2876       b(L_exit);
2877 
2878       align(CodeEntryAlignment);
2879     BIND(CRC_by64_loop);
2880       subs(len, len, 64);
2881       ldp(tmp, tmp3, Address(post(buf, 16)));
2882       crc32x(crc, crc, tmp);
2883       crc32x(crc, crc, tmp3);
2884       ldp(tmp, tmp3, Address(post(buf, 16)));
2885       crc32x(crc, crc, tmp);
2886       crc32x(crc, crc, tmp3);
2887       ldp(tmp, tmp3, Address(post(buf, 16)));
2888       crc32x(crc, crc, tmp);
2889       crc32x(crc, crc, tmp3);
2890       ldp(tmp, tmp3, Address(post(buf, 16)));
2891       crc32x(crc, crc, tmp);
2892       crc32x(crc, crc, tmp3);
2893       br(Assembler::GE, CRC_by64_loop);
2894       adds(len, len, 64-4);
2895       br(Assembler::GE, CRC_by4_loop);
2896       adds(len, len, 4);
2897       br(Assembler::GT, CRC_by1_loop);
2898     BIND(L_exit);
2899       ornw(crc, zr, crc);
2900       return;
2901   }
2902 
2903     adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
2904     if (offset) add(table0, table0, offset);
2905     add(table1, table0, 1*256*sizeof(juint));
2906     add(table2, table0, 2*256*sizeof(juint));
2907     add(table3, table0, 3*256*sizeof(juint));
2908 
2909   if (UseNeon) {
2910       cmp(len, 64);
2911       br(Assembler::LT, L_by16);
2912       eor(v16, T16B, v16, v16);
2913 
2914     Label L_fold;
2915 
2916       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
2917 
2918       ld1(v0, v1, T2D, post(buf, 32));
2919       ld1r(v4, T2D, post(tmp, 8));
2920       ld1r(v5, T2D, post(tmp, 8));
2921       ld1r(v6, T2D, post(tmp, 8));
2922       ld1r(v7, T2D, post(tmp, 8));
2923       mov(v16, T4S, 0, crc);
2924 
2925       eor(v0, T16B, v0, v16);
2926       sub(len, len, 64);
2927 
2928     BIND(L_fold);
2929       pmull(v22, T8H, v0, v5, T8B);
2930       pmull(v20, T8H, v0, v7, T8B);
2931       pmull(v23, T8H, v0, v4, T8B);
2932       pmull(v21, T8H, v0, v6, T8B);
2933 
2934       pmull2(v18, T8H, v0, v5, T16B);
2935       pmull2(v16, T8H, v0, v7, T16B);
2936       pmull2(v19, T8H, v0, v4, T16B);
2937       pmull2(v17, T8H, v0, v6, T16B);
2938 
2939       uzp1(v24, v20, v22, T8H);
2940       uzp2(v25, v20, v22, T8H);
2941       eor(v20, T16B, v24, v25);
2942 
2943       uzp1(v26, v16, v18, T8H);
2944       uzp2(v27, v16, v18, T8H);
2945       eor(v16, T16B, v26, v27);
2946 
2947       ushll2(v22, T4S, v20, T8H, 8);
2948       ushll(v20, T4S, v20, T4H, 8);
2949 
2950       ushll2(v18, T4S, v16, T8H, 8);
2951       ushll(v16, T4S, v16, T4H, 8);
2952 
2953       eor(v22, T16B, v23, v22);
2954       eor(v18, T16B, v19, v18);
2955       eor(v20, T16B, v21, v20);
2956       eor(v16, T16B, v17, v16);
2957 
2958       uzp1(v17, v16, v20, T2D);
2959       uzp2(v21, v16, v20, T2D);
2960       eor(v17, T16B, v17, v21);
2961 
2962       ushll2(v20, T2D, v17, T4S, 16);
2963       ushll(v16, T2D, v17, T2S, 16);
2964 
2965       eor(v20, T16B, v20, v22);
2966       eor(v16, T16B, v16, v18);
2967 
2968       uzp1(v17, v20, v16, T2D);
2969       uzp2(v21, v20, v16, T2D);
2970       eor(v28, T16B, v17, v21);
2971 
2972       pmull(v22, T8H, v1, v5, T8B);
2973       pmull(v20, T8H, v1, v7, T8B);
2974       pmull(v23, T8H, v1, v4, T8B);
2975       pmull(v21, T8H, v1, v6, T8B);
2976 
2977       pmull2(v18, T8H, v1, v5, T16B);
2978       pmull2(v16, T8H, v1, v7, T16B);
2979       pmull2(v19, T8H, v1, v4, T16B);
2980       pmull2(v17, T8H, v1, v6, T16B);
2981 
2982       ld1(v0, v1, T2D, post(buf, 32));
2983 
2984       uzp1(v24, v20, v22, T8H);
2985       uzp2(v25, v20, v22, T8H);
2986       eor(v20, T16B, v24, v25);
2987 
2988       uzp1(v26, v16, v18, T8H);
2989       uzp2(v27, v16, v18, T8H);
2990       eor(v16, T16B, v26, v27);
2991 
2992       ushll2(v22, T4S, v20, T8H, 8);
2993       ushll(v20, T4S, v20, T4H, 8);
2994 
2995       ushll2(v18, T4S, v16, T8H, 8);
2996       ushll(v16, T4S, v16, T4H, 8);
2997 
2998       eor(v22, T16B, v23, v22);
2999       eor(v18, T16B, v19, v18);
3000       eor(v20, T16B, v21, v20);
3001       eor(v16, T16B, v17, v16);
3002 
3003       uzp1(v17, v16, v20, T2D);
3004       uzp2(v21, v16, v20, T2D);
3005       eor(v16, T16B, v17, v21);
3006 
3007       ushll2(v20, T2D, v16, T4S, 16);
3008       ushll(v16, T2D, v16, T2S, 16);
3009 
3010       eor(v20, T16B, v22, v20);
3011       eor(v16, T16B, v16, v18);
3012 
3013       uzp1(v17, v20, v16, T2D);
3014       uzp2(v21, v20, v16, T2D);
3015       eor(v20, T16B, v17, v21);
3016 
3017       shl(v16, T2D, v28, 1);
3018       shl(v17, T2D, v20, 1);
3019 
3020       eor(v0, T16B, v0, v16);
3021       eor(v1, T16B, v1, v17);
3022 
3023       subs(len, len, 32);
3024       br(Assembler::GE, L_fold);
3025 
3026       mov(crc, 0);
3027       mov(tmp, v0, T1D, 0);
3028       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3029       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3030       mov(tmp, v0, T1D, 1);
3031       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3032       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3033       mov(tmp, v1, T1D, 0);
3034       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3035       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3036       mov(tmp, v1, T1D, 1);
3037       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3038       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3039 
3040       add(len, len, 32);
3041   }
3042 
3043   BIND(L_by16);
3044     subs(len, len, 16);
3045     br(Assembler::GE, L_by16_loop);
3046     adds(len, len, 16-4);
3047     br(Assembler::GE, L_by4_loop);
3048     adds(len, len, 4);
3049     br(Assembler::GT, L_by1_loop);
3050     b(L_exit);
3051 
3052   BIND(L_by4_loop);
3053     ldrw(tmp, Address(post(buf, 4)));
3054     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
3055     subs(len, len, 4);
3056     br(Assembler::GE, L_by4_loop);
3057     adds(len, len, 4);
3058     br(Assembler::LE, L_exit);
3059   BIND(L_by1_loop);
3060     subs(len, len, 1);
3061     ldrb(tmp, Address(post(buf, 1)));
3062     update_byte_crc32(crc, tmp, table0);
3063     br(Assembler::GT, L_by1_loop);
3064     b(L_exit);
3065 
3066     align(CodeEntryAlignment);
3067   BIND(L_by16_loop);
3068     subs(len, len, 16);
3069     ldp(tmp, tmp3, Address(post(buf, 16)));
3070     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3071     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3072     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
3073     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
3074     br(Assembler::GE, L_by16_loop);
3075     adds(len, len, 16-4);
3076     br(Assembler::GE, L_by4_loop);
3077     adds(len, len, 4);
3078     br(Assembler::GT, L_by1_loop);
3079   BIND(L_exit);
3080     ornw(crc, zr, crc);
3081 }
3082 
3083 SkipIfEqual::SkipIfEqual(
3084     MacroAssembler* masm, const bool* flag_addr, bool value) {
3085   _masm = masm;
3086   unsigned long offset;
3087   _masm->adrp(rscratch1, ExternalAddress((address)flag_addr), offset);
3088   _masm->ldrb(rscratch1, Address(rscratch1, offset));
3089   _masm->cbzw(rscratch1, _label);
3090 }
3091 
3092 SkipIfEqual::~SkipIfEqual() {
3093   _masm->bind(_label);
3094 }
3095 
3096 void MacroAssembler::addptr(const Address &dst, int32_t src) {
3097   Address adr;
3098   switch(dst.getMode()) {
3099   case Address::base_plus_offset:
3100     // This is the expected mode, although we allow all the other
3101     // forms below.
3102     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
3103     break;
3104   default:
3105     lea(rscratch2, dst);
3106     adr = Address(rscratch2);
3107     break;
3108   }
3109   ldr(rscratch1, adr);
3110   add(rscratch1, rscratch1, src);
3111   str(rscratch1, adr);
3112 }
3113 
3114 void MacroAssembler::cmpptr(Register src1, Address src2) {
3115   unsigned long offset;
3116   adrp(rscratch1, src2, offset);
3117   ldr(rscratch1, Address(rscratch1, offset));
3118   cmp(src1, rscratch1);
3119 }
3120 
3121 void MacroAssembler::store_check(Register obj) {
3122   // Does a store check for the oop in register obj. The content of
3123   // register obj is destroyed afterwards.
3124   store_check_part_1(obj);
3125   store_check_part_2(obj);
3126 }
3127 
3128 void MacroAssembler::store_check(Register obj, Address dst) {
3129   store_check(obj);
3130 }
3131 
3132 
3133 // split the store check operation so that other instructions can be scheduled inbetween
3134 void MacroAssembler::store_check_part_1(Register obj) {
3135   BarrierSet* bs = Universe::heap()->barrier_set();
3136   assert(bs->kind() == BarrierSet::CardTableModRef, "Wrong barrier set kind");
3137   lsr(obj, obj, CardTableModRefBS::card_shift);
3138 }
3139 
3140 void MacroAssembler::store_check_part_2(Register obj) {
3141   BarrierSet* bs = Universe::heap()->barrier_set();
3142   assert(bs->kind() == BarrierSet::CardTableModRef, "Wrong barrier set kind");
3143   CardTableModRefBS* ct = (CardTableModRefBS*)bs;
3144   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3145 
3146   // The calculation for byte_map_base is as follows:
3147   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
3148   // So this essentially converts an address to a displacement and
3149   // it will never need to be relocated.
3150 
3151   // FIXME: It's not likely that disp will fit into an offset so we
3152   // don't bother to check, but it could save an instruction.
3153   intptr_t disp = (intptr_t) ct->byte_map_base;
3154   load_byte_map_base(rscratch1);
3155 
3156   if (UseConcMarkSweepGC && CMSPrecleaningEnabled) {
3157       membar(StoreStore);
3158   }
3159   strb(zr, Address(obj, rscratch1));
3160 }
3161 
3162 void MacroAssembler::load_klass(Register dst, Register src) {
3163   if (UseCompressedClassPointers) {
3164     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3165     decode_klass_not_null(dst);
3166   } else {
3167     ldr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3168   }
3169 }
3170 
3171 void MacroAssembler::cmp_klass(Register oop, Register trial_klass, Register tmp) {
3172   if (UseCompressedClassPointers) {
3173     ldrw(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3174     if (Universe::narrow_klass_base() == NULL) {
3175       cmp(trial_klass, tmp, LSL, Universe::narrow_klass_shift());
3176       return;
3177     } else if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3178                && Universe::narrow_klass_shift() == 0) {
3179       // Only the bottom 32 bits matter
3180       cmpw(trial_klass, tmp);
3181       return;
3182     }
3183     decode_klass_not_null(tmp);
3184   } else {
3185     ldr(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3186   }
3187   cmp(trial_klass, tmp);
3188 }
3189 
3190 void MacroAssembler::load_prototype_header(Register dst, Register src) {
3191   load_klass(dst, src);
3192   ldr(dst, Address(dst, Klass::prototype_header_offset()));
3193 }
3194 
3195 void MacroAssembler::store_klass(Register dst, Register src) {
3196   // FIXME: Should this be a store release?  concurrent gcs assumes
3197   // klass length is valid if klass field is not null.
3198   if (UseCompressedClassPointers) {
3199     encode_klass_not_null(src);
3200     strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3201   } else {
3202     str(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3203   }
3204 }
3205 
3206 void MacroAssembler::store_klass_gap(Register dst, Register src) {
3207   if (UseCompressedClassPointers) {
3208     // Store to klass gap in destination
3209     strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
3210   }
3211 }
3212 
3213 // Algorithm must match oop.inline.hpp encode_heap_oop.
3214 void MacroAssembler::encode_heap_oop(Register d, Register s) {
3215 #ifdef ASSERT
3216   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
3217 #endif
3218   verify_oop(s, "broken oop in encode_heap_oop");
3219   if (Universe::narrow_oop_base() == NULL) {
3220     if (Universe::narrow_oop_shift() != 0) {
3221       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3222       lsr(d, s, LogMinObjAlignmentInBytes);
3223     } else {
3224       mov(d, s);
3225     }
3226   } else {
3227     subs(d, s, rheapbase);
3228     csel(d, d, zr, Assembler::HS);
3229     lsr(d, d, LogMinObjAlignmentInBytes);
3230 
3231     /*  Old algorithm: is this any worse?
3232     Label nonnull;
3233     cbnz(r, nonnull);
3234     sub(r, r, rheapbase);
3235     bind(nonnull);
3236     lsr(r, r, LogMinObjAlignmentInBytes);
3237     */
3238   }
3239 }
3240 
3241 void MacroAssembler::encode_heap_oop_not_null(Register r) {
3242 #ifdef ASSERT
3243   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
3244   if (CheckCompressedOops) {
3245     Label ok;
3246     cbnz(r, ok);
3247     stop("null oop passed to encode_heap_oop_not_null");
3248     bind(ok);
3249   }
3250 #endif
3251   verify_oop(r, "broken oop in encode_heap_oop_not_null");
3252   if (Universe::narrow_oop_base() != NULL) {
3253     sub(r, r, rheapbase);
3254   }
3255   if (Universe::narrow_oop_shift() != 0) {
3256     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3257     lsr(r, r, LogMinObjAlignmentInBytes);
3258   }
3259 }
3260 
3261 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
3262 #ifdef ASSERT
3263   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
3264   if (CheckCompressedOops) {
3265     Label ok;
3266     cbnz(src, ok);
3267     stop("null oop passed to encode_heap_oop_not_null2");
3268     bind(ok);
3269   }
3270 #endif
3271   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
3272 
3273   Register data = src;
3274   if (Universe::narrow_oop_base() != NULL) {
3275     sub(dst, src, rheapbase);
3276     data = dst;
3277   }
3278   if (Universe::narrow_oop_shift() != 0) {
3279     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3280     lsr(dst, data, LogMinObjAlignmentInBytes);
3281     data = dst;
3282   }
3283   if (data == src)
3284     mov(dst, src);
3285 }
3286 
3287 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
3288 #ifdef ASSERT
3289   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
3290 #endif
3291   if (Universe::narrow_oop_base() == NULL) {
3292     if (Universe::narrow_oop_shift() != 0 || d != s) {
3293       lsl(d, s, Universe::narrow_oop_shift());
3294     }
3295   } else {
3296     Label done;
3297     if (d != s)
3298       mov(d, s);
3299     cbz(s, done);
3300     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
3301     bind(done);
3302   }
3303   verify_oop(d, "broken oop in decode_heap_oop");
3304 }
3305 
3306 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
3307   assert (UseCompressedOops, "should only be used for compressed headers");
3308   assert (Universe::heap() != NULL, "java heap should be initialized");
3309   // Cannot assert, unverified entry point counts instructions (see .ad file)
3310   // vtableStubs also counts instructions in pd_code_size_limit.
3311   // Also do not verify_oop as this is called by verify_oop.
3312   if (Universe::narrow_oop_shift() != 0) {
3313     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3314     if (Universe::narrow_oop_base() != NULL) {
3315       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3316     } else {
3317       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3318     }
3319   } else {
3320     assert (Universe::narrow_oop_base() == NULL, "sanity");
3321   }
3322 }
3323 
3324 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
3325   assert (UseCompressedOops, "should only be used for compressed headers");
3326   assert (Universe::heap() != NULL, "java heap should be initialized");
3327   // Cannot assert, unverified entry point counts instructions (see .ad file)
3328   // vtableStubs also counts instructions in pd_code_size_limit.
3329   // Also do not verify_oop as this is called by verify_oop.
3330   if (Universe::narrow_oop_shift() != 0) {
3331     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3332     if (Universe::narrow_oop_base() != NULL) {
3333       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3334     } else {
3335       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3336     }
3337   } else {
3338     assert (Universe::narrow_oop_base() == NULL, "sanity");
3339     if (dst != src) {
3340       mov(dst, src);
3341     }
3342   }
3343 }
3344 
3345 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
3346   if (Universe::narrow_klass_base() == NULL) {
3347     if (Universe::narrow_klass_shift() != 0) {
3348       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3349       lsr(dst, src, LogKlassAlignmentInBytes);
3350     } else {
3351       if (dst != src) mov(dst, src);
3352     }
3353     return;
3354   }
3355 
3356   if (use_XOR_for_compressed_class_base) {
3357     if (Universe::narrow_klass_shift() != 0) {
3358       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3359       lsr(dst, dst, LogKlassAlignmentInBytes);
3360     } else {
3361       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3362     }
3363     return;
3364   }
3365 
3366   if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3367       && Universe::narrow_klass_shift() == 0) {
3368     movw(dst, src);
3369     return;
3370   }
3371 
3372 #ifdef ASSERT
3373   verify_heapbase("MacroAssembler::encode_klass_not_null2: heap base corrupted?");
3374 #endif
3375 
3376   Register rbase = dst;
3377   if (dst == src) rbase = rheapbase;
3378   mov(rbase, (uint64_t)Universe::narrow_klass_base());
3379   sub(dst, src, rbase);
3380   if (Universe::narrow_klass_shift() != 0) {
3381     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3382     lsr(dst, dst, LogKlassAlignmentInBytes);
3383   }
3384   if (dst == src) reinit_heapbase();
3385 }
3386 
3387 void MacroAssembler::encode_klass_not_null(Register r) {
3388   encode_klass_not_null(r, r);
3389 }
3390 
3391 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
3392   Register rbase = dst;
3393   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3394 
3395   if (Universe::narrow_klass_base() == NULL) {
3396     if (Universe::narrow_klass_shift() != 0) {
3397       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3398       lsl(dst, src, LogKlassAlignmentInBytes);
3399     } else {
3400       if (dst != src) mov(dst, src);
3401     }
3402     return;
3403   }
3404 
3405   if (use_XOR_for_compressed_class_base) {
3406     if (Universe::narrow_klass_shift() != 0) {
3407       lsl(dst, src, LogKlassAlignmentInBytes);
3408       eor(dst, dst, (uint64_t)Universe::narrow_klass_base());
3409     } else {
3410       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3411     }
3412     return;
3413   }
3414 
3415   if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3416       && Universe::narrow_klass_shift() == 0) {
3417     if (dst != src)
3418       movw(dst, src);
3419     movk(dst, (uint64_t)Universe::narrow_klass_base() >> 32, 32);
3420     return;
3421   }
3422 
3423   // Cannot assert, unverified entry point counts instructions (see .ad file)
3424   // vtableStubs also counts instructions in pd_code_size_limit.
3425   // Also do not verify_oop as this is called by verify_oop.
3426   if (dst == src) rbase = rheapbase;
3427   mov(rbase, (uint64_t)Universe::narrow_klass_base());
3428   if (Universe::narrow_klass_shift() != 0) {
3429     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3430     add(dst, rbase, src, Assembler::LSL, LogKlassAlignmentInBytes);
3431   } else {
3432     add(dst, rbase, src);
3433   }
3434   if (dst == src) reinit_heapbase();
3435 }
3436 
3437 void  MacroAssembler::decode_klass_not_null(Register r) {
3438   decode_klass_not_null(r, r);
3439 }
3440 
3441 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
3442   assert (UseCompressedOops, "should only be used for compressed oops");
3443   assert (Universe::heap() != NULL, "java heap should be initialized");
3444   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
3445 
3446   int oop_index = oop_recorder()->find_index(obj);
3447   assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "should be real oop");
3448 
3449   InstructionMark im(this);
3450   RelocationHolder rspec = oop_Relocation::spec(oop_index);
3451   code_section()->relocate(inst_mark(), rspec);
3452   movz(dst, 0xDEAD, 16);
3453   movk(dst, 0xBEEF);
3454 }
3455 
3456 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
3457   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3458   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
3459   int index = oop_recorder()->find_index(k);
3460   assert(! Universe::heap()->is_in_reserved(k), "should not be an oop");
3461 
3462   InstructionMark im(this);
3463   RelocationHolder rspec = metadata_Relocation::spec(index);
3464   code_section()->relocate(inst_mark(), rspec);
3465   narrowKlass nk = Klass::encode_klass(k);
3466   movz(dst, (nk >> 16), 16);
3467   movk(dst, nk & 0xffff);
3468 }
3469 
3470 void MacroAssembler::load_heap_oop(Register dst, Address src)
3471 {
3472   if (UseCompressedOops) {
3473     ldrw(dst, src);
3474     decode_heap_oop(dst);
3475   } else {
3476     ldr(dst, src);
3477   }
3478 
3479 #if INCLUDE_ALL_GCS
3480   if (UseShenandoahGC) {
3481     ShenandoahBarrierSetAssembler::bsasm()->load_reference_barrier(this, dst);
3482   }
3483 #endif
3484 }
3485 
3486 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src)
3487 {
3488   if (UseCompressedOops) {
3489     ldrw(dst, src);
3490     decode_heap_oop_not_null(dst);
3491   } else {
3492     ldr(dst, src);
3493   }
3494 
3495 #if INCLUDE_ALL_GCS
3496   if (UseShenandoahGC) {
3497     ShenandoahBarrierSetAssembler::bsasm()->load_reference_barrier(this, dst);
3498   }
3499 #endif
3500 }
3501 
3502 void MacroAssembler::store_heap_oop(Address dst, Register src) {
3503   if (UseCompressedOops) {
3504     assert(!dst.uses(src), "not enough registers");
3505     encode_heap_oop(src);
3506     strw(src, dst);
3507   } else
3508     str(src, dst);
3509 }
3510 
3511 // Used for storing NULLs.
3512 void MacroAssembler::store_heap_oop_null(Address dst) {
3513   if (UseCompressedOops) {
3514     strw(zr, dst);
3515   } else
3516     str(zr, dst);
3517 }
3518 
3519 #if INCLUDE_ALL_GCS
3520 /*
3521  * g1_write_barrier_pre -- G1GC pre-write barrier for store of new_val at
3522  * store_addr.
3523  *
3524  * Allocates rscratch1
3525  */
3526 void MacroAssembler::g1_write_barrier_pre(Register obj,
3527                                           Register pre_val,
3528                                           Register thread,
3529                                           Register tmp,
3530                                           bool tosca_live,
3531                                           bool expand_call) {
3532   // If expand_call is true then we expand the call_VM_leaf macro
3533   // directly to skip generating the check by
3534   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
3535 
3536 #ifdef _LP64
3537   assert(thread == rthread, "must be");
3538 #endif // _LP64
3539 
3540   Label done;
3541   Label runtime;
3542 
3543   assert_different_registers(obj, pre_val, tmp, rscratch1);
3544   assert(pre_val != noreg &&  tmp != noreg, "expecting a register");
3545 
3546   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3547                                        PtrQueue::byte_offset_of_active()));
3548   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3549                                        PtrQueue::byte_offset_of_index()));
3550   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3551                                        PtrQueue::byte_offset_of_buf()));
3552 
3553 
3554   // Is marking active?
3555   if (in_bytes(PtrQueue::byte_width_of_active()) == 4) {
3556     ldrw(tmp, in_progress);
3557   } else {
3558     assert(in_bytes(PtrQueue::byte_width_of_active()) == 1, "Assumption");
3559     ldrb(tmp, in_progress);
3560   }
3561   cbzw(tmp, done);
3562 
3563   // Do we need to load the previous value?
3564   if (obj != noreg) {
3565     load_heap_oop(pre_val, Address(obj, 0));
3566   }
3567 
3568   // Is the previous value null?
3569   cbz(pre_val, done);
3570 
3571   // Can we store original value in the thread's buffer?
3572   // Is index == 0?
3573   // (The index field is typed as size_t.)
3574 
3575   ldr(tmp, index);                      // tmp := *index_adr
3576   cbz(tmp, runtime);                    // tmp == 0?
3577                                         // If yes, goto runtime
3578 
3579   sub(tmp, tmp, wordSize);              // tmp := tmp - wordSize
3580   str(tmp, index);                      // *index_adr := tmp
3581   ldr(rscratch1, buffer);
3582   add(tmp, tmp, rscratch1);             // tmp := tmp + *buffer_adr
3583 
3584   // Record the previous value
3585   str(pre_val, Address(tmp, 0));
3586   b(done);
3587 
3588   bind(runtime);
3589   // save the live input values
3590   push(r0->bit(tosca_live) | obj->bit(obj != noreg) | pre_val->bit(true), sp);
3591 
3592   // Calling the runtime using the regular call_VM_leaf mechanism generates
3593   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
3594   // that checks that the *(rfp+frame::interpreter_frame_last_sp) == NULL.
3595   //
3596   // If we care generating the pre-barrier without a frame (e.g. in the
3597   // intrinsified Reference.get() routine) then ebp might be pointing to
3598   // the caller frame and so this check will most likely fail at runtime.
3599   //
3600   // Expanding the call directly bypasses the generation of the check.
3601   // So when we do not have have a full interpreter frame on the stack
3602   // expand_call should be passed true.
3603 
3604   if (expand_call) {
3605     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
3606     pass_arg1(this, thread);
3607     pass_arg0(this, pre_val);
3608     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
3609   } else {
3610     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
3611   }
3612 
3613   pop(r0->bit(tosca_live) | obj->bit(obj != noreg) | pre_val->bit(true), sp);
3614 
3615   bind(done);
3616 }
3617 
3618 /*
3619  * g1_write_barrier_post -- G1GC post-write barrier for store of new_val at
3620  * store_addr
3621  *
3622  * Allocates rscratch1
3623  */
3624 void MacroAssembler::g1_write_barrier_post(Register store_addr,
3625                                            Register new_val,
3626                                            Register thread,
3627                                            Register tmp,
3628                                            Register tmp2) {
3629 #ifdef _LP64
3630   assert(thread == rthread, "must be");
3631 #endif // _LP64
3632   assert_different_registers(store_addr, new_val, thread, tmp, tmp2,
3633                              rscratch1);
3634   assert(store_addr != noreg && new_val != noreg && tmp != noreg
3635          && tmp2 != noreg, "expecting a register");
3636 
3637   if (UseShenandoahGC) {
3638     // No need for this in Shenandoah.
3639     return;
3640   }
3641 
3642   assert(UseG1GC, "expect G1 GC");
3643 
3644   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
3645                                        PtrQueue::byte_offset_of_index()));
3646   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
3647                                        PtrQueue::byte_offset_of_buf()));
3648 
3649   BarrierSet* bs = Universe::heap()->barrier_set();
3650   CardTableModRefBS* ct = (CardTableModRefBS*)bs;
3651   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3652 
3653   Label done;
3654   Label runtime;
3655 
3656   // Does store cross heap regions?
3657 
3658   eor(tmp, store_addr, new_val);
3659   lsr(tmp, tmp, HeapRegion::LogOfHRGrainBytes);
3660   cbz(tmp, done);
3661 
3662   // crosses regions, storing NULL?
3663 
3664   cbz(new_val, done);
3665 
3666   // storing region crossing non-NULL, is card already dirty?
3667 
3668   ExternalAddress cardtable((address) ct->byte_map_base);
3669   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3670   const Register card_addr = tmp;
3671 
3672   lsr(card_addr, store_addr, CardTableModRefBS::card_shift);
3673 
3674   // get the address of the card
3675   load_byte_map_base(tmp2);
3676   add(card_addr, card_addr, tmp2);
3677   ldrb(tmp2, Address(card_addr));
3678   cmpw(tmp2, (int)G1SATBCardTableModRefBS::g1_young_card_val());
3679   br(Assembler::EQ, done);
3680 
3681   assert((int)CardTableModRefBS::dirty_card_val() == 0, "must be 0");
3682 
3683   membar(Assembler::Assembler::StoreLoad);
3684 
3685   ldrb(tmp2, Address(card_addr));
3686   cbzw(tmp2, done);
3687 
3688   // storing a region crossing, non-NULL oop, card is clean.
3689   // dirty card and log.
3690 
3691   strb(zr, Address(card_addr));
3692 
3693   ldr(rscratch1, queue_index);
3694   cbz(rscratch1, runtime);
3695   sub(rscratch1, rscratch1, wordSize);
3696   str(rscratch1, queue_index);
3697 
3698   ldr(tmp2, buffer);
3699   str(card_addr, Address(tmp2, rscratch1));
3700   b(done);
3701 
3702   bind(runtime);
3703   // save the live input values
3704   push(store_addr->bit(true) | new_val->bit(true), sp);
3705   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
3706   pop(store_addr->bit(true) | new_val->bit(true), sp);
3707 
3708   bind(done);
3709 }
3710 
3711 #endif // INCLUDE_ALL_GCS
3712 
3713 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
3714   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
3715   int index = oop_recorder()->allocate_metadata_index(obj);
3716   RelocationHolder rspec = metadata_Relocation::spec(index);
3717   return Address((address)obj, rspec);
3718 }
3719 
3720 // Move an oop into a register.  immediate is true if we want
3721 // immediate instrcutions, i.e. we are not going to patch this
3722 // instruction while the code is being executed by another thread.  In
3723 // that case we can use move immediates rather than the constant pool.
3724 void MacroAssembler::movoop(Register dst, jobject obj, bool immediate) {
3725   int oop_index;
3726   if (obj == NULL) {
3727     oop_index = oop_recorder()->allocate_oop_index(obj);
3728   } else {
3729     oop_index = oop_recorder()->find_index(obj);
3730     assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "should be real oop");
3731   }
3732   RelocationHolder rspec = oop_Relocation::spec(oop_index);
3733   if (! immediate) {
3734     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
3735     ldr_constant(dst, Address(dummy, rspec));
3736   } else
3737     mov(dst, Address((address)obj, rspec));
3738 }
3739 
3740 // Move a metadata address into a register.
3741 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
3742   int oop_index;
3743   if (obj == NULL) {
3744     oop_index = oop_recorder()->allocate_metadata_index(obj);
3745   } else {
3746     oop_index = oop_recorder()->find_index(obj);
3747   }
3748   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
3749   mov(dst, Address((address)obj, rspec));
3750 }
3751 
3752 Address MacroAssembler::constant_oop_address(jobject obj) {
3753   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
3754   assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "not an oop");
3755   int oop_index = oop_recorder()->find_index(obj);
3756   return Address((address)obj, oop_Relocation::spec(oop_index));
3757 }
3758 
3759 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
3760 void MacroAssembler::tlab_allocate(Register obj,
3761                                    Register var_size_in_bytes,
3762                                    int con_size_in_bytes,
3763                                    Register t1,
3764                                    Register t2,
3765                                    Label& slow_case) {
3766   assert_different_registers(obj, t2);
3767   assert_different_registers(obj, var_size_in_bytes);
3768   Register end = t2;
3769 
3770   // verify_tlab();
3771 
3772   ldr(obj, Address(rthread, JavaThread::tlab_top_offset()));
3773   if (var_size_in_bytes == noreg) {
3774     lea(end, Address(obj, con_size_in_bytes));
3775   } else {
3776     lea(end, Address(obj, var_size_in_bytes));
3777   }
3778   ldr(rscratch1, Address(rthread, JavaThread::tlab_end_offset()));
3779   cmp(end, rscratch1);
3780   br(Assembler::HI, slow_case);
3781 
3782   // update the tlab top pointer
3783   str(end, Address(rthread, JavaThread::tlab_top_offset()));
3784 
3785   // recover var_size_in_bytes if necessary
3786   if (var_size_in_bytes == end) {
3787     sub(var_size_in_bytes, var_size_in_bytes, obj);
3788   }
3789   // verify_tlab();
3790 }
3791 
3792 // Preserves r19, and r3.
3793 Register MacroAssembler::tlab_refill(Label& retry,
3794                                      Label& try_eden,
3795                                      Label& slow_case) {
3796   Register top = r0;
3797   Register t1  = r2;
3798   Register t2  = r4;
3799   assert_different_registers(top, rthread, t1, t2, /* preserve: */ r19, r3);
3800   Label do_refill, discard_tlab;
3801 
3802   if (CMSIncrementalMode || !Universe::heap()->supports_inline_contig_alloc()) {
3803     // No allocation in the shared eden.
3804     b(slow_case);
3805   }
3806 
3807   ldr(top, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3808   ldr(t1,  Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
3809 
3810   // calculate amount of free space
3811   sub(t1, t1, top);
3812   lsr(t1, t1, LogHeapWordSize);
3813 
3814   // Retain tlab and allocate object in shared space if
3815   // the amount free in the tlab is too large to discard.
3816 
3817   ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3818   cmp(t1, rscratch1);
3819   br(Assembler::LE, discard_tlab);
3820 
3821   // Retain
3822   // ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3823   mov(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
3824   add(rscratch1, rscratch1, t2);
3825   str(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3826 
3827   if (TLABStats) {
3828     // increment number of slow_allocations
3829     addmw(Address(rthread, in_bytes(JavaThread::tlab_slow_allocations_offset())),
3830          1, rscratch1);
3831   }
3832   b(try_eden);
3833 
3834   bind(discard_tlab);
3835   if (TLABStats) {
3836     // increment number of refills
3837     addmw(Address(rthread, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1,
3838          rscratch1);
3839     // accumulate wastage -- t1 is amount free in tlab
3840     addmw(Address(rthread, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1,
3841          rscratch1);
3842   }
3843 
3844   // if tlab is currently allocated (top or end != null) then
3845   // fill [top, end + alignment_reserve) with array object
3846   cbz(top, do_refill);
3847 
3848   // set up the mark word
3849   mov(rscratch1, (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
3850   str(rscratch1, Address(top, oopDesc::mark_offset_in_bytes()));
3851   // set the length to the remaining space
3852   sub(t1, t1, typeArrayOopDesc::header_size(T_INT));
3853   add(t1, t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
3854   lsl(t1, t1, log2_intptr(HeapWordSize/sizeof(jint)));
3855   strw(t1, Address(top, arrayOopDesc::length_offset_in_bytes()));
3856   // set klass to intArrayKlass
3857   {
3858     unsigned long offset;
3859     // dubious reloc why not an oop reloc?
3860     adrp(rscratch1, ExternalAddress((address)Universe::intArrayKlassObj_addr()),
3861          offset);
3862     ldr(t1, Address(rscratch1, offset));
3863   }
3864   // store klass last.  concurrent gcs assumes klass length is valid if
3865   // klass field is not null.
3866   store_klass(top, t1);
3867 
3868   mov(t1, top);
3869   ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
3870   sub(t1, t1, rscratch1);
3871   incr_allocated_bytes(rthread, t1, 0, rscratch1);
3872 
3873   // refill the tlab with an eden allocation
3874   bind(do_refill);
3875   ldr(t1, Address(rthread, in_bytes(JavaThread::tlab_size_offset())));
3876   lsl(t1, t1, LogHeapWordSize);
3877   // allocate new tlab, address returned in top
3878   eden_allocate(top, t1, 0, t2, slow_case);
3879 
3880   // Check that t1 was preserved in eden_allocate.
3881 #ifdef ASSERT
3882   if (UseTLAB) {
3883     Label ok;
3884     Register tsize = r4;
3885     assert_different_registers(tsize, rthread, t1);
3886     str(tsize, Address(pre(sp, -16)));
3887     ldr(tsize, Address(rthread, in_bytes(JavaThread::tlab_size_offset())));
3888     lsl(tsize, tsize, LogHeapWordSize);
3889     cmp(t1, tsize);
3890     br(Assembler::EQ, ok);
3891     STOP("assert(t1 != tlab size)");
3892     should_not_reach_here();
3893 
3894     bind(ok);
3895     ldr(tsize, Address(post(sp, 16)));
3896   }
3897 #endif
3898   str(top, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
3899   str(top, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3900   add(top, top, t1);
3901   sub(top, top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
3902   str(top, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
3903   verify_tlab();
3904   b(retry);
3905 
3906   return rthread; // for use by caller
3907 }
3908 
3909 // Defines obj, preserves var_size_in_bytes
3910 void MacroAssembler::eden_allocate(Register obj,
3911                                    Register var_size_in_bytes,
3912                                    int con_size_in_bytes,
3913                                    Register t1,
3914                                    Label& slow_case) {
3915   assert_different_registers(obj, var_size_in_bytes, t1);
3916   if (CMSIncrementalMode || !Universe::heap()->supports_inline_contig_alloc()) {
3917     b(slow_case);
3918   } else {
3919     Register end = t1;
3920     Register heap_end = rscratch2;
3921     Label retry;
3922     bind(retry);
3923     {
3924       unsigned long offset;
3925       adrp(rscratch1, ExternalAddress((address) Universe::heap()->end_addr()), offset);
3926       ldr(heap_end, Address(rscratch1, offset));
3927     }
3928 
3929     ExternalAddress heap_top((address) Universe::heap()->top_addr());
3930 
3931     // Get the current top of the heap
3932     {
3933       unsigned long offset;
3934       adrp(rscratch1, heap_top, offset);
3935       // Use add() here after ARDP, rather than lea().
3936       // lea() does not generate anything if its offset is zero.
3937       // However, relocs expect to find either an ADD or a load/store
3938       // insn after an ADRP.  add() always generates an ADD insn, even
3939       // for add(Rn, Rn, 0).
3940       add(rscratch1, rscratch1, offset);
3941       ldaxr(obj, rscratch1);
3942     }
3943 
3944     // Adjust it my the size of our new object
3945     if (var_size_in_bytes == noreg) {
3946       lea(end, Address(obj, con_size_in_bytes));
3947     } else {
3948       lea(end, Address(obj, var_size_in_bytes));
3949     }
3950 
3951     // if end < obj then we wrapped around high memory
3952     cmp(end, obj);
3953     br(Assembler::LO, slow_case);
3954 
3955     cmp(end, heap_end);
3956     br(Assembler::HI, slow_case);
3957 
3958     // If heap_top hasn't been changed by some other thread, update it.
3959     stlxr(rscratch2, end, rscratch1);
3960     cbnzw(rscratch2, retry);
3961   }
3962 }
3963 
3964 void MacroAssembler::verify_tlab() {
3965 #ifdef ASSERT
3966   if (UseTLAB && VerifyOops) {
3967     Label next, ok;
3968 
3969     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
3970 
3971     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3972     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
3973     cmp(rscratch2, rscratch1);
3974     br(Assembler::HS, next);
3975     STOP("assert(top >= start)");
3976     should_not_reach_here();
3977 
3978     bind(next);
3979     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
3980     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3981     cmp(rscratch2, rscratch1);
3982     br(Assembler::HS, ok);
3983     STOP("assert(top <= end)");
3984     should_not_reach_here();
3985 
3986     bind(ok);
3987     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
3988   }
3989 #endif
3990 }
3991 
3992 // Writes to stack successive pages until offset reached to check for
3993 // stack overflow + shadow pages.  This clobbers tmp.
3994 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
3995   assert_different_registers(tmp, size, rscratch1);
3996   mov(tmp, sp);
3997   // Bang stack for total size given plus shadow page size.
3998   // Bang one page at a time because large size can bang beyond yellow and
3999   // red zones.
4000   Label loop;
4001   mov(rscratch1, os::vm_page_size());
4002   bind(loop);
4003   lea(tmp, Address(tmp, -os::vm_page_size()));
4004   subsw(size, size, rscratch1);
4005   str(size, Address(tmp));
4006   br(Assembler::GT, loop);
4007 
4008   // Bang down shadow pages too.
4009   // The -1 because we already subtracted 1 page.
4010   for (int i = 0; i< StackShadowPages-1; i++) {
4011     // this could be any sized move but this is can be a debugging crumb
4012     // so the bigger the better.
4013     lea(tmp, Address(tmp, -os::vm_page_size()));
4014     str(size, Address(tmp));
4015   }
4016 }
4017 
4018 
4019 address MacroAssembler::read_polling_page(Register r, address page, relocInfo::relocType rtype) {
4020   unsigned long off;
4021   adrp(r, Address(page, rtype), off);
4022   InstructionMark im(this);
4023   code_section()->relocate(inst_mark(), rtype);
4024   ldrw(zr, Address(r, off));
4025   return inst_mark();
4026 }
4027 
4028 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
4029   InstructionMark im(this);
4030   code_section()->relocate(inst_mark(), rtype);
4031   ldrw(zr, Address(r, 0));
4032   return inst_mark();
4033 }
4034 
4035 void MacroAssembler::adrp(Register reg1, const Address &dest, unsigned long &byte_offset) {
4036   relocInfo::relocType rtype = dest.rspec().reloc()->type();
4037   unsigned long low_page = (unsigned long)CodeCache::low_bound() >> 12;
4038   unsigned long high_page = (unsigned long)(CodeCache::high_bound()-1) >> 12;
4039   unsigned long dest_page = (unsigned long)dest.target() >> 12;
4040   long offset_low = dest_page - low_page;
4041   long offset_high = dest_page - high_page;
4042 
4043   assert(is_valid_AArch64_address(dest.target()), "bad address");
4044   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
4045 
4046   InstructionMark im(this);
4047   code_section()->relocate(inst_mark(), dest.rspec());
4048   // 8143067: Ensure that the adrp can reach the dest from anywhere within
4049   // the code cache so that if it is relocated we know it will still reach
4050   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
4051     _adrp(reg1, dest.target());
4052   } else {
4053     unsigned long target = (unsigned long)dest.target();
4054     unsigned long adrp_target
4055       = (target & 0xffffffffUL) | ((unsigned long)pc() & 0xffff00000000UL);
4056 
4057     _adrp(reg1, (address)adrp_target);
4058     movk(reg1, target >> 32, 32);
4059   }
4060   byte_offset = (unsigned long)dest.target() & 0xfff;
4061 }
4062 
4063 void MacroAssembler::load_byte_map_base(Register reg) {
4064   jbyte *byte_map_base =
4065     ((CardTableModRefBS*)(Universe::heap()->barrier_set()))->byte_map_base;
4066 
4067   if (is_valid_AArch64_address((address)byte_map_base)) {
4068     // Strictly speaking the byte_map_base isn't an address at all,
4069     // and it might even be negative.
4070     unsigned long offset;
4071     adrp(reg, ExternalAddress((address)byte_map_base), offset);
4072     // We expect offset to be zero with most collectors.
4073     if (offset != 0) {
4074       add(reg, reg, offset);
4075     }
4076   } else {
4077     mov(reg, (uint64_t)byte_map_base);
4078   }
4079 }
4080 
4081 void MacroAssembler::build_frame(int framesize) {
4082   if (framesize == 0) {
4083     // Is this even possible?
4084     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
4085   } else if (framesize < ((1 << 9) + 2 * wordSize)) {
4086     sub(sp, sp, framesize);
4087     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4088   } else {
4089     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
4090     if (framesize < ((1 << 12) + 2 * wordSize))
4091       sub(sp, sp, framesize - 2 * wordSize);
4092     else {
4093       mov(rscratch1, framesize - 2 * wordSize);
4094       sub(sp, sp, rscratch1);
4095     }
4096   }
4097 }
4098 
4099 void MacroAssembler::remove_frame(int framesize) {
4100   if (framesize == 0) {
4101     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
4102   } else if (framesize < ((1 << 9) + 2 * wordSize)) {
4103     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4104     add(sp, sp, framesize);
4105   } else {
4106     if (framesize < ((1 << 12) + 2 * wordSize))
4107       add(sp, sp, framesize - 2 * wordSize);
4108     else {
4109       mov(rscratch1, framesize - 2 * wordSize);
4110       add(sp, sp, rscratch1);
4111     }
4112     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
4113   }
4114 }
4115 
4116 // Search for str1 in str2 and return index or -1
4117 void MacroAssembler::string_indexof(Register str2, Register str1,
4118                                     Register cnt2, Register cnt1,
4119                                     Register tmp1, Register tmp2,
4120                                     Register tmp3, Register tmp4,
4121                                     int icnt1, Register result) {
4122   Label BM, LINEARSEARCH, DONE, NOMATCH, MATCH;
4123 
4124   Register ch1 = rscratch1;
4125   Register ch2 = rscratch2;
4126   Register cnt1tmp = tmp1;
4127   Register cnt2tmp = tmp2;
4128   Register cnt1_neg = cnt1;
4129   Register cnt2_neg = cnt2;
4130   Register result_tmp = tmp4;
4131 
4132   // Note, inline_string_indexOf() generates checks:
4133   // if (substr.count > string.count) return -1;
4134   // if (substr.count == 0) return 0;
4135 
4136 // We have two strings, a source string in str2, cnt2 and a pattern string
4137 // in str1, cnt1. Find the 1st occurence of pattern in source or return -1.
4138 
4139 // For larger pattern and source we use a simplified Boyer Moore algorithm.
4140 // With a small pattern and source we use linear scan.
4141 
4142   if (icnt1 == -1) {
4143     cmp(cnt1, 256);             // Use Linear Scan if cnt1 < 8 || cnt1 >= 256
4144     ccmp(cnt1, 8, 0b0000, LO);  // Can't handle skip >= 256 because we use
4145     br(LO, LINEARSEARCH);       // a byte array.
4146     cmp(cnt1, cnt2, LSR, 2);    // Source must be 4 * pattern for BM
4147     br(HS, LINEARSEARCH);
4148   }
4149 
4150 // The Boyer Moore alogorithm is based on the description here:-
4151 //
4152 // http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm
4153 //
4154 // This describes and algorithm with 2 shift rules. The 'Bad Character' rule
4155 // and the 'Good Suffix' rule.
4156 //
4157 // These rules are essentially heuristics for how far we can shift the
4158 // pattern along the search string.
4159 //
4160 // The implementation here uses the 'Bad Character' rule only because of the
4161 // complexity of initialisation for the 'Good Suffix' rule.
4162 //
4163 // This is also known as the Boyer-Moore-Horspool algorithm:-
4164 //
4165 // http://en.wikipedia.org/wiki/Boyer-Moore-Horspool_algorithm
4166 //
4167 // #define ASIZE 128
4168 //
4169 //    int bm(unsigned char *x, int m, unsigned char *y, int n) {
4170 //       int i, j;
4171 //       unsigned c;
4172 //       unsigned char bc[ASIZE];
4173 //    
4174 //       /* Preprocessing */
4175 //       for (i = 0; i < ASIZE; ++i)
4176 //          bc[i] = 0;
4177 //       for (i = 0; i < m - 1; ) {
4178 //          c = x[i];
4179 //          ++i;
4180 //          if (c < ASIZE) bc[c] = i;
4181 //       }
4182 //    
4183 //       /* Searching */
4184 //       j = 0;
4185 //       while (j <= n - m) {
4186 //          c = y[i+j];
4187 //          if (x[m-1] == c)
4188 //            for (i = m - 2; i >= 0 && x[i] == y[i + j]; --i);
4189 //          if (i < 0) return j;
4190 //          if (c < ASIZE)
4191 //            j = j - bc[y[j+m-1]] + m;
4192 //          else
4193 //            j += 1; // Advance by 1 only if char >= ASIZE
4194 //       }
4195 //    }
4196 
4197   if (icnt1 == -1) {
4198     BIND(BM);
4199 
4200     Label ZLOOP, BCLOOP, BCSKIP, BMLOOPSTR2, BMLOOPSTR1, BMSKIP;
4201     Label BMADV, BMMATCH, BMCHECKEND;
4202 
4203     Register cnt1end = tmp2;
4204     Register str2end = cnt2;
4205     Register skipch = tmp2;
4206 
4207     // Restrict ASIZE to 128 to reduce stack space/initialisation.
4208     // The presence of chars >= ASIZE in the target string does not affect
4209     // performance, but we must be careful not to initialise them in the stack
4210     // array.
4211     // The presence of chars >= ASIZE in the source string may adversely affect
4212     // performance since we can only advance by one when we encounter one.
4213 
4214       stp(zr, zr, pre(sp, -128));
4215       for (int i = 1; i < 8; i++)
4216           stp(zr, zr, Address(sp, i*16));
4217 
4218       mov(cnt1tmp, 0);
4219       sub(cnt1end, cnt1, 1);
4220     BIND(BCLOOP);
4221       ldrh(ch1, Address(str1, cnt1tmp, Address::lsl(1)));
4222       cmp(ch1, 128);
4223       add(cnt1tmp, cnt1tmp, 1);
4224       br(HS, BCSKIP);
4225       strb(cnt1tmp, Address(sp, ch1));
4226     BIND(BCSKIP);
4227       cmp(cnt1tmp, cnt1end);
4228       br(LT, BCLOOP);
4229 
4230       mov(result_tmp, str2);
4231 
4232       sub(cnt2, cnt2, cnt1);
4233       add(str2end, str2, cnt2, LSL, 1);
4234     BIND(BMLOOPSTR2);
4235       sub(cnt1tmp, cnt1, 1);
4236       ldrh(ch1, Address(str1, cnt1tmp, Address::lsl(1)));
4237       ldrh(skipch, Address(str2, cnt1tmp, Address::lsl(1)));
4238       cmp(ch1, skipch);
4239       br(NE, BMSKIP);
4240       subs(cnt1tmp, cnt1tmp, 1);
4241       br(LT, BMMATCH);
4242     BIND(BMLOOPSTR1);
4243       ldrh(ch1, Address(str1, cnt1tmp, Address::lsl(1)));
4244       ldrh(ch2, Address(str2, cnt1tmp, Address::lsl(1)));
4245       cmp(ch1, ch2);
4246       br(NE, BMSKIP);
4247       subs(cnt1tmp, cnt1tmp, 1);
4248       br(GE, BMLOOPSTR1);
4249     BIND(BMMATCH);
4250       sub(result_tmp, str2, result_tmp);
4251       lsr(result, result_tmp, 1);
4252       add(sp, sp, 128);
4253       b(DONE);
4254     BIND(BMADV);
4255       add(str2, str2, 2);
4256       b(BMCHECKEND);
4257     BIND(BMSKIP);
4258       cmp(skipch, 128);
4259       br(HS, BMADV);
4260       ldrb(ch2, Address(sp, skipch));
4261       add(str2, str2, cnt1, LSL, 1);
4262       sub(str2, str2, ch2, LSL, 1);
4263     BIND(BMCHECKEND);
4264       cmp(str2, str2end);
4265       br(LE, BMLOOPSTR2);
4266       add(sp, sp, 128);
4267       b(NOMATCH);
4268   }
4269 
4270   BIND(LINEARSEARCH);
4271   {
4272     Label DO1, DO2, DO3;
4273 
4274     Register str2tmp = tmp2;
4275     Register first = tmp3;
4276 
4277     if (icnt1 == -1)
4278     {
4279         Label DOSHORT, FIRST_LOOP, STR2_NEXT, STR1_LOOP, STR1_NEXT, LAST_WORD;
4280 
4281         cmp(cnt1, 4);
4282         br(LT, DOSHORT);
4283 
4284         sub(cnt2, cnt2, cnt1);
4285         sub(cnt1, cnt1, 4);
4286         mov(result_tmp, cnt2);
4287 
4288         lea(str1, Address(str1, cnt1, Address::uxtw(1)));
4289         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4290         sub(cnt1_neg, zr, cnt1, LSL, 1);
4291         sub(cnt2_neg, zr, cnt2, LSL, 1);
4292         ldr(first, Address(str1, cnt1_neg));
4293 
4294       BIND(FIRST_LOOP);
4295         ldr(ch2, Address(str2, cnt2_neg));
4296         cmp(first, ch2);
4297         br(EQ, STR1_LOOP);
4298       BIND(STR2_NEXT);
4299         adds(cnt2_neg, cnt2_neg, 2);
4300         br(LE, FIRST_LOOP);
4301         b(NOMATCH);
4302 
4303       BIND(STR1_LOOP);
4304         adds(cnt1tmp, cnt1_neg, 8);
4305         add(cnt2tmp, cnt2_neg, 8);
4306         br(GE, LAST_WORD);
4307 
4308       BIND(STR1_NEXT);
4309         ldr(ch1, Address(str1, cnt1tmp));
4310         ldr(ch2, Address(str2, cnt2tmp));
4311         cmp(ch1, ch2);
4312         br(NE, STR2_NEXT);
4313         adds(cnt1tmp, cnt1tmp, 8);
4314         add(cnt2tmp, cnt2tmp, 8);
4315         br(LT, STR1_NEXT);
4316 
4317       BIND(LAST_WORD);
4318         ldr(ch1, Address(str1));
4319         sub(str2tmp, str2, cnt1_neg);         // adjust to corresponding
4320         ldr(ch2, Address(str2tmp, cnt2_neg)); // word in str2
4321         cmp(ch1, ch2);
4322         br(NE, STR2_NEXT);
4323         b(MATCH);
4324 
4325       BIND(DOSHORT);
4326         cmp(cnt1, 2);
4327         br(LT, DO1);
4328         br(GT, DO3);
4329     }
4330 
4331     if (icnt1 == 4) {
4332       Label CH1_LOOP;
4333 
4334         ldr(ch1, str1);
4335         sub(cnt2, cnt2, 4);
4336         mov(result_tmp, cnt2);
4337         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4338         sub(cnt2_neg, zr, cnt2, LSL, 1);
4339 
4340       BIND(CH1_LOOP);
4341         ldr(ch2, Address(str2, cnt2_neg));
4342         cmp(ch1, ch2);
4343         br(EQ, MATCH);
4344         adds(cnt2_neg, cnt2_neg, 2);
4345         br(LE, CH1_LOOP);
4346         b(NOMATCH);
4347     }
4348 
4349     if (icnt1 == -1 || icnt1 == 2) {
4350       Label CH1_LOOP;
4351 
4352       BIND(DO2);
4353         ldrw(ch1, str1);
4354         sub(cnt2, cnt2, 2);
4355         mov(result_tmp, cnt2);
4356         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4357         sub(cnt2_neg, zr, cnt2, LSL, 1);
4358 
4359       BIND(CH1_LOOP);
4360         ldrw(ch2, Address(str2, cnt2_neg));
4361         cmp(ch1, ch2);
4362         br(EQ, MATCH);
4363         adds(cnt2_neg, cnt2_neg, 2);
4364         br(LE, CH1_LOOP);
4365         b(NOMATCH);
4366     }
4367 
4368     if (icnt1 == -1 || icnt1 == 3) {
4369       Label FIRST_LOOP, STR2_NEXT, STR1_LOOP;
4370 
4371       BIND(DO3);
4372         ldrw(first, str1);
4373         ldrh(ch1, Address(str1, 4));
4374 
4375         sub(cnt2, cnt2, 3);
4376         mov(result_tmp, cnt2);
4377         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4378         sub(cnt2_neg, zr, cnt2, LSL, 1);
4379 
4380       BIND(FIRST_LOOP);
4381         ldrw(ch2, Address(str2, cnt2_neg));
4382         cmpw(first, ch2);
4383         br(EQ, STR1_LOOP);
4384       BIND(STR2_NEXT);
4385         adds(cnt2_neg, cnt2_neg, 2);
4386         br(LE, FIRST_LOOP);
4387         b(NOMATCH);
4388 
4389       BIND(STR1_LOOP);
4390         add(cnt2tmp, cnt2_neg, 4);
4391         ldrh(ch2, Address(str2, cnt2tmp));
4392         cmp(ch1, ch2);
4393         br(NE, STR2_NEXT);
4394         b(MATCH);
4395     }
4396 
4397     if (icnt1 == -1 || icnt1 == 1) {
4398       Label CH1_LOOP, HAS_ZERO;
4399       Label DO1_SHORT, DO1_LOOP;
4400 
4401       BIND(DO1);
4402         ldrh(ch1, str1);
4403         cmp(cnt2, 4);
4404         br(LT, DO1_SHORT);
4405 
4406         orr(ch1, ch1, ch1, LSL, 16);
4407         orr(ch1, ch1, ch1, LSL, 32);
4408 
4409         sub(cnt2, cnt2, 4);
4410         mov(result_tmp, cnt2);
4411         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4412         sub(cnt2_neg, zr, cnt2, LSL, 1);
4413 
4414         mov(tmp3, 0x0001000100010001);
4415       BIND(CH1_LOOP);
4416         ldr(ch2, Address(str2, cnt2_neg));
4417         eor(ch2, ch1, ch2);
4418         sub(tmp1, ch2, tmp3);
4419         orr(tmp2, ch2, 0x7fff7fff7fff7fff);
4420         bics(tmp1, tmp1, tmp2);
4421         br(NE, HAS_ZERO);
4422         adds(cnt2_neg, cnt2_neg, 8);
4423         br(LT, CH1_LOOP);
4424 
4425         cmp(cnt2_neg, 8);
4426         mov(cnt2_neg, 0);
4427         br(LT, CH1_LOOP);
4428         b(NOMATCH);
4429 
4430       BIND(HAS_ZERO);
4431         rev(tmp1, tmp1);
4432         clz(tmp1, tmp1);
4433         add(cnt2_neg, cnt2_neg, tmp1, LSR, 3);
4434         b(MATCH);
4435 
4436       BIND(DO1_SHORT);
4437         mov(result_tmp, cnt2);
4438         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4439         sub(cnt2_neg, zr, cnt2, LSL, 1);
4440       BIND(DO1_LOOP);
4441         ldrh(ch2, Address(str2, cnt2_neg));
4442         cmpw(ch1, ch2);
4443         br(EQ, MATCH);
4444         adds(cnt2_neg, cnt2_neg, 2);
4445         br(LT, DO1_LOOP);
4446     }
4447   }
4448   BIND(NOMATCH);
4449     mov(result, -1);
4450     b(DONE);
4451   BIND(MATCH);
4452     add(result, result_tmp, cnt2_neg, ASR, 1);
4453   BIND(DONE);
4454 }
4455 
4456 // Compare strings.
4457 void MacroAssembler::string_compare(Register str1, Register str2,
4458                                     Register cnt1, Register cnt2, Register result,
4459                                     Register tmp1) {
4460   Label LENGTH_DIFF, DONE, SHORT_LOOP, SHORT_STRING,
4461     NEXT_WORD, DIFFERENCE;
4462 
4463   BLOCK_COMMENT("string_compare {");
4464 
4465   // Compute the minimum of the string lengths and save the difference.
4466   subsw(tmp1, cnt1, cnt2);
4467   cselw(cnt2, cnt1, cnt2, Assembler::LE); // min
4468 
4469   // A very short string
4470   cmpw(cnt2, 4);
4471   br(Assembler::LT, SHORT_STRING);
4472 
4473   // Check if the strings start at the same location.
4474   cmp(str1, str2);
4475   br(Assembler::EQ, LENGTH_DIFF);
4476 
4477   // Compare longwords
4478   {
4479     subw(cnt2, cnt2, 4); // The last longword is a special case
4480 
4481     // Move both string pointers to the last longword of their
4482     // strings, negate the remaining count, and convert it to bytes.
4483     lea(str1, Address(str1, cnt2, Address::uxtw(1)));
4484     lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4485     sub(cnt2, zr, cnt2, LSL, 1);
4486 
4487     // Loop, loading longwords and comparing them into rscratch2.
4488     bind(NEXT_WORD);
4489     ldr(result, Address(str1, cnt2));
4490     ldr(cnt1, Address(str2, cnt2));
4491     adds(cnt2, cnt2, wordSize);
4492     eor(rscratch2, result, cnt1);
4493     cbnz(rscratch2, DIFFERENCE);
4494     br(Assembler::LT, NEXT_WORD);
4495 
4496     // Last longword.  In the case where length == 4 we compare the
4497     // same longword twice, but that's still faster than another
4498     // conditional branch.
4499 
4500     ldr(result, Address(str1));
4501     ldr(cnt1, Address(str2));
4502     eor(rscratch2, result, cnt1);
4503     cbz(rscratch2, LENGTH_DIFF);
4504 
4505     // Find the first different characters in the longwords and
4506     // compute their difference.
4507     bind(DIFFERENCE);
4508     rev(rscratch2, rscratch2);
4509     clz(rscratch2, rscratch2);
4510     andr(rscratch2, rscratch2, -16);
4511     lsrv(result, result, rscratch2);
4512     uxthw(result, result);
4513     lsrv(cnt1, cnt1, rscratch2);
4514     uxthw(cnt1, cnt1);
4515     subw(result, result, cnt1);
4516     b(DONE);
4517   }
4518 
4519   bind(SHORT_STRING);
4520   // Is the minimum length zero?
4521   cbz(cnt2, LENGTH_DIFF);
4522 
4523   bind(SHORT_LOOP);
4524   load_unsigned_short(result, Address(post(str1, 2)));
4525   load_unsigned_short(cnt1, Address(post(str2, 2)));
4526   subw(result, result, cnt1);
4527   cbnz(result, DONE);
4528   sub(cnt2, cnt2, 1);
4529   cbnz(cnt2, SHORT_LOOP);
4530 
4531   // Strings are equal up to min length.  Return the length difference.
4532   bind(LENGTH_DIFF);
4533   mov(result, tmp1);
4534 
4535   // That's it
4536   bind(DONE);
4537 
4538   BLOCK_COMMENT("} string_compare");
4539 }
4540 
4541 
4542 // base:     Address of a buffer to be zeroed, 8 bytes aligned.
4543 // cnt:      Count in HeapWords.
4544 // is_large: True when 'cnt' is known to be >= BlockZeroingLowLimit.
4545 void MacroAssembler::zero_words(Register base, Register cnt)
4546 {
4547   if (UseBlockZeroing) {
4548     block_zero(base, cnt);
4549   } else {
4550     fill_words(base, cnt, zr);
4551   }
4552 }
4553 
4554 // r10 = base:   Address of a buffer to be zeroed, 8 bytes aligned.
4555 // cnt:          Immediate count in HeapWords.
4556 // r11 = tmp:    For use as cnt if we need to call out
4557 #define ShortArraySize (18 * BytesPerLong)
4558 void MacroAssembler::zero_words(Register base, u_int64_t cnt)
4559 {
4560   Register tmp = r11;
4561   int i = cnt & 1;  // store any odd word to start
4562   if (i) str(zr, Address(base));
4563 
4564   if (cnt <= ShortArraySize / BytesPerLong) {
4565     for (; i < (int)cnt; i += 2)
4566       stp(zr, zr, Address(base, i * wordSize));
4567   } else if (UseBlockZeroing && cnt >= (u_int64_t)(BlockZeroingLowLimit >> LogBytesPerWord)) {
4568     mov(tmp, cnt);
4569     block_zero(base, tmp, true);
4570   } else {
4571     const int unroll = 4; // Number of stp(zr, zr) instructions we'll unroll
4572     int remainder = cnt % (2 * unroll);
4573     for (; i < remainder; i += 2)
4574       stp(zr, zr, Address(base, i * wordSize));
4575 
4576     Label loop;
4577     Register cnt_reg = rscratch1;
4578     Register loop_base = rscratch2;
4579     cnt = cnt - remainder;
4580     mov(cnt_reg, cnt);
4581     // adjust base and prebias by -2 * wordSize so we can pre-increment
4582     add(loop_base, base, (remainder - 2) * wordSize);
4583     bind(loop);
4584     sub(cnt_reg, cnt_reg, 2 * unroll);
4585     for (i = 1; i < unroll; i++)
4586       stp(zr, zr, Address(loop_base, 2 * i * wordSize));
4587     stp(zr, zr, Address(pre(loop_base, 2 * unroll * wordSize)));
4588     cbnz(cnt_reg, loop);
4589   }
4590 }
4591 
4592 // base:   Address of a buffer to be filled, 8 bytes aligned.
4593 // cnt:    Count in 8-byte unit.
4594 // value:  Value to be filled with.
4595 // base will point to the end of the buffer after filling.
4596 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
4597 {
4598 //  Algorithm:
4599 //
4600 //    scratch1 = cnt & 7;
4601 //    cnt -= scratch1;
4602 //    p += scratch1;
4603 //    switch (scratch1) {
4604 //      do {
4605 //        cnt -= 8;
4606 //          p[-8] = v;
4607 //        case 7:
4608 //          p[-7] = v;
4609 //        case 6:
4610 //          p[-6] = v;
4611 //          // ...
4612 //        case 1:
4613 //          p[-1] = v;
4614 //        case 0:
4615 //          p += 8;
4616 //      } while (cnt);
4617 //    }
4618 
4619   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
4620 
4621   Label fini, skip, entry, loop;
4622   const int unroll = 8; // Number of stp instructions we'll unroll
4623 
4624   cbz(cnt, fini);
4625   tbz(base, 3, skip);
4626   str(value, Address(post(base, 8)));
4627   sub(cnt, cnt, 1);
4628   bind(skip);
4629 
4630   andr(rscratch1, cnt, (unroll-1) * 2);
4631   sub(cnt, cnt, rscratch1);
4632   add(base, base, rscratch1, Assembler::LSL, 3);
4633   adr(rscratch2, entry);
4634   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
4635   br(rscratch2);
4636 
4637   bind(loop);
4638   add(base, base, unroll * 16);
4639   for (int i = -unroll; i < 0; i++)
4640     stp(value, value, Address(base, i * 16));
4641   bind(entry);
4642   subs(cnt, cnt, unroll * 2);
4643   br(Assembler::GE, loop);
4644 
4645   tbz(cnt, 0, fini);
4646   str(value, Address(post(base, 8)));
4647   bind(fini);
4648 }
4649 
4650 // Use DC ZVA to do fast zeroing.
4651 // base:   Address of a buffer to be zeroed, 8 bytes aligned.
4652 // cnt:    Count in HeapWords.
4653 // is_large: True when 'cnt' is known to be >= BlockZeroingLowLimit.
4654 void MacroAssembler::block_zero(Register base, Register cnt, bool is_large)
4655 {
4656   Label small;
4657   Label store_pair, loop_store_pair, done;
4658   Label base_aligned;
4659 
4660   assert_different_registers(base, cnt, rscratch1);
4661   guarantee(base == r10 && cnt == r11, "fix register usage");
4662 
4663   Register tmp = rscratch1;
4664   Register tmp2 = rscratch2;
4665   int zva_length = VM_Version::zva_length();
4666 
4667   // Ensure ZVA length can be divided by 16. This is required by
4668   // the subsequent operations.
4669   assert (zva_length % 16 == 0, "Unexpected ZVA Length");
4670 
4671   if (!is_large) cbz(cnt, done);
4672   tbz(base, 3, base_aligned);
4673   str(zr, Address(post(base, 8)));
4674   sub(cnt, cnt, 1);
4675   bind(base_aligned);
4676 
4677   // Ensure count >= zva_length * 2 so that it still deserves a zva after
4678   // alignment.
4679   if (!is_large || !(BlockZeroingLowLimit >= zva_length * 2)) {
4680     int low_limit = MAX2(zva_length * 2, (int)BlockZeroingLowLimit);
4681     subs(tmp, cnt, low_limit >> 3);
4682     br(Assembler::LT, small);
4683   }
4684 
4685   far_call(StubRoutines::aarch64::get_zero_longs());
4686 
4687   bind(small);
4688 
4689   const int unroll = 8; // Number of stp instructions we'll unroll
4690   Label small_loop, small_table_end;
4691 
4692   andr(tmp, cnt, (unroll-1) * 2);
4693   sub(cnt, cnt, tmp);
4694   add(base, base, tmp, Assembler::LSL, 3);
4695   adr(tmp2, small_table_end);
4696   sub(tmp2, tmp2, tmp, Assembler::LSL, 1);
4697   br(tmp2);
4698 
4699   bind(small_loop);
4700   add(base, base, unroll * 16);
4701   for (int i = -unroll; i < 0; i++)
4702     stp(zr, zr, Address(base, i * 16));
4703   bind(small_table_end);
4704   subs(cnt, cnt, unroll * 2);
4705   br(Assembler::GE, small_loop);
4706 
4707   tbz(cnt, 0, done);
4708   str(zr, Address(post(base, 8)));
4709 
4710   bind(done);
4711 }
4712 
4713 void MacroAssembler::string_equals(Register str1, Register str2,
4714                                    Register cnt, Register result,
4715                                    Register tmp1) {
4716   Label SAME_CHARS, DONE, SHORT_LOOP, SHORT_STRING,
4717     NEXT_WORD;
4718 
4719   const Register tmp2 = rscratch1;
4720   assert_different_registers(str1, str2, cnt, result, tmp1, tmp2, rscratch2);
4721 
4722   BLOCK_COMMENT("string_equals {");
4723 
4724   // Start by assuming that the strings are not equal.
4725   mov(result, zr);
4726 
4727   // A very short string
4728   cmpw(cnt, 4);
4729   br(Assembler::LT, SHORT_STRING);
4730 
4731   // Check if the strings start at the same location.
4732   cmp(str1, str2);
4733   br(Assembler::EQ, SAME_CHARS);
4734 
4735   // Compare longwords
4736   {
4737     subw(cnt, cnt, 4); // The last longword is a special case
4738 
4739     // Move both string pointers to the last longword of their
4740     // strings, negate the remaining count, and convert it to bytes.
4741     lea(str1, Address(str1, cnt, Address::uxtw(1)));
4742     lea(str2, Address(str2, cnt, Address::uxtw(1)));
4743     sub(cnt, zr, cnt, LSL, 1);
4744 
4745     // Loop, loading longwords and comparing them into rscratch2.
4746     bind(NEXT_WORD);
4747     ldr(tmp1, Address(str1, cnt));
4748     ldr(tmp2, Address(str2, cnt));
4749     adds(cnt, cnt, wordSize);
4750     eor(rscratch2, tmp1, tmp2);
4751     cbnz(rscratch2, DONE);
4752     br(Assembler::LT, NEXT_WORD);
4753 
4754     // Last longword.  In the case where length == 4 we compare the
4755     // same longword twice, but that's still faster than another
4756     // conditional branch.
4757 
4758     ldr(tmp1, Address(str1));
4759     ldr(tmp2, Address(str2));
4760     eor(rscratch2, tmp1, tmp2);
4761     cbz(rscratch2, SAME_CHARS);
4762     b(DONE);
4763   }
4764 
4765   bind(SHORT_STRING);
4766   // Is the length zero?
4767   cbz(cnt, SAME_CHARS);
4768 
4769   bind(SHORT_LOOP);
4770   load_unsigned_short(tmp1, Address(post(str1, 2)));
4771   load_unsigned_short(tmp2, Address(post(str2, 2)));
4772   subw(tmp1, tmp1, tmp2);
4773   cbnz(tmp1, DONE);
4774   sub(cnt, cnt, 1);
4775   cbnz(cnt, SHORT_LOOP);
4776 
4777   // Strings are equal.
4778   bind(SAME_CHARS);
4779   mov(result, true);
4780 
4781   // That's it
4782   bind(DONE);
4783 
4784   BLOCK_COMMENT("} string_equals");
4785 }
4786 
4787 // Compare char[] arrays aligned to 4 bytes
4788 void MacroAssembler::char_arrays_equals(Register ary1, Register ary2,
4789                                         Register result, Register tmp1)
4790 {
4791   Register cnt1 = rscratch1;
4792   Register cnt2 = rscratch2;
4793   Register tmp2 = rscratch2;
4794 
4795   Label SAME, DIFFER, NEXT, TAIL03, TAIL01;
4796 
4797   int length_offset  = arrayOopDesc::length_offset_in_bytes();
4798   int base_offset    = arrayOopDesc::base_offset_in_bytes(T_CHAR);
4799 
4800   BLOCK_COMMENT("char_arrays_equals  {");
4801 
4802     // different until proven equal
4803     mov(result, false);
4804 
4805     // same array?
4806     cmp(ary1, ary2);
4807     br(Assembler::EQ, SAME);
4808 
4809     // ne if either null
4810     cbz(ary1, DIFFER);
4811     cbz(ary2, DIFFER);
4812 
4813     // lengths ne?
4814     ldrw(cnt1, Address(ary1, length_offset));
4815     ldrw(cnt2, Address(ary2, length_offset));
4816     cmp(cnt1, cnt2);
4817     br(Assembler::NE, DIFFER);
4818 
4819     lea(ary1, Address(ary1, base_offset));
4820     lea(ary2, Address(ary2, base_offset));
4821 
4822     subs(cnt1, cnt1, 4);
4823     br(LT, TAIL03);
4824 
4825   BIND(NEXT);
4826     ldr(tmp1, Address(post(ary1, 8)));
4827     ldr(tmp2, Address(post(ary2, 8)));
4828     subs(cnt1, cnt1, 4);
4829     eor(tmp1, tmp1, tmp2);
4830     cbnz(tmp1, DIFFER);
4831     br(GE, NEXT);
4832 
4833   BIND(TAIL03);  // 0-3 chars left, cnt1 = #chars left - 4
4834     tst(cnt1, 0b10);
4835     br(EQ, TAIL01);
4836     ldrw(tmp1, Address(post(ary1, 4)));
4837     ldrw(tmp2, Address(post(ary2, 4)));
4838     cmp(tmp1, tmp2);
4839     br(NE, DIFFER);
4840   BIND(TAIL01);  // 0-1 chars left
4841     tst(cnt1, 0b01);
4842     br(EQ, SAME);
4843     ldrh(tmp1, ary1);
4844     ldrh(tmp2, ary2);
4845     cmp(tmp1, tmp2);
4846     br(NE, DIFFER);
4847 
4848   BIND(SAME);
4849     mov(result, true);
4850   BIND(DIFFER); // result already set
4851   
4852   BLOCK_COMMENT("} char_arrays_equals");
4853 }
4854 
4855 // encode char[] to byte[] in ISO_8859_1
4856 void MacroAssembler::encode_iso_array(Register src, Register dst,
4857                       Register len, Register result,
4858                       FloatRegister Vtmp1, FloatRegister Vtmp2,
4859                       FloatRegister Vtmp3, FloatRegister Vtmp4)
4860 {
4861     Label DONE, NEXT_32, LOOP_8, NEXT_8, LOOP_1, NEXT_1;
4862     Register tmp1 = rscratch1;
4863 
4864       mov(result, len); // Save initial len
4865 
4866       subs(len, len, 32);
4867       br(LT, LOOP_8);
4868 
4869 // The following code uses the SIMD 'uqxtn' and 'uqxtn2' instructions
4870 // to convert chars to bytes. These set the 'QC' bit in the FPSR if
4871 // any char could not fit in a byte, so clear the FPSR so we can test it.
4872       clear_fpsr();
4873 
4874     BIND(NEXT_32);
4875       ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
4876       uqxtn(Vtmp1, T8B, Vtmp1, T8H);  // uqxtn  - write bottom half
4877       uqxtn(Vtmp1, T16B, Vtmp2, T8H); // uqxtn2 - write top half
4878       uqxtn(Vtmp2, T8B, Vtmp3, T8H);
4879       uqxtn(Vtmp2, T16B, Vtmp4, T8H); // uqxtn2
4880       get_fpsr(tmp1);
4881       cbnzw(tmp1, LOOP_8);
4882       st1(Vtmp1, Vtmp2, T16B, post(dst, 32));
4883       subs(len, len, 32);
4884       add(src, src, 64);
4885       br(GE, NEXT_32);
4886 
4887     BIND(LOOP_8);
4888       adds(len, len, 32-8);
4889       br(LT, LOOP_1);
4890       clear_fpsr(); // QC may be set from loop above, clear again
4891     BIND(NEXT_8);
4892       ld1(Vtmp1, T8H, src);
4893       uqxtn(Vtmp1, T8B, Vtmp1, T8H);
4894       get_fpsr(tmp1);
4895       cbnzw(tmp1, LOOP_1);
4896       st1(Vtmp1, T8B, post(dst, 8));
4897       subs(len, len, 8);
4898       add(src, src, 16);
4899       br(GE, NEXT_8);
4900 
4901     BIND(LOOP_1);
4902       adds(len, len, 8);
4903       br(LE, DONE);
4904 
4905     BIND(NEXT_1);
4906       ldrh(tmp1, Address(post(src, 2)));
4907       tst(tmp1, 0xff00);
4908       br(NE, DONE);
4909       strb(tmp1, Address(post(dst, 1)));
4910       subs(len, len, 1);
4911       br(GT, NEXT_1);
4912 
4913     BIND(DONE);
4914       sub(result, result, len); // Return index where we stopped
4915 }