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