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