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