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 res, Register addr, Register expected,
2201                                             Register new_val,
2202                                             bool narrow,
2203                                             bool acquire, bool release,
2204                                             Register tmp1, Register tmp2) {
2205   assert(UseShenandoahGC, "only for shenandoah");
2206   assert_different_registers(res, addr, expected, new_val, tmp1, tmp2);
2207 
2208   Label retry, done, fail;
2209 
2210   mov(res, 0);
2211 
2212   // CAS, using LL/SC pair.
2213   bind(retry);
2214   load_exclusive(tmp1, addr, narrow ? word : xword, true);
2215   if (narrow) cmpw(tmp1, expected);
2216   else        cmp(tmp1, expected);
2217   br(Assembler::NE, fail);
2218   store_exclusive(tmp2, new_val, addr, narrow ? word : xword, true);
2219   cbnzw(tmp2, retry);
2220   mov(res, 1);
2221   b(done);
2222 
2223   bind(fail);
2224   // Check if rb(expected)==rb(tmp1)
2225   // Shuffle registers so that we have memory value ready for next expected.
2226   mov(tmp2, expected);
2227   mov(expected, tmp1);
2228   if (narrow) {
2229     decode_heap_oop(tmp1, tmp1);
2230     decode_heap_oop(tmp2, tmp2);
2231   }
2232   oopDesc::bs()->interpreter_read_barrier(this, tmp1);
2233   oopDesc::bs()->interpreter_read_barrier(this, tmp2);
2234   cmp(tmp1, tmp2);
2235   // Retry with expected now being the value we just loaded from addr.
2236   br(Assembler::EQ, retry);
2237 
2238   bind(done);
2239   membar(AnyAny);
2240 }
2241 
2242 static bool different(Register a, RegisterOrConstant b, Register c) {
2243   if (b.is_constant())
2244     return a != c;
2245   else
2246     return a != b.as_register() && a != c && b.as_register() != c;
2247 }
2248 
2249 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
2250 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
2251   if (UseLSE) {                                                         \
2252     prev = prev->is_valid() ? prev : zr;                                \
2253     if (incr.is_register()) {                                           \
2254       AOP(sz, incr.as_register(), prev, addr);                          \
2255     } else {                                                            \
2256       mov(rscratch2, incr.as_constant());                               \
2257       AOP(sz, rscratch2, prev, addr);                                   \
2258     }                                                                   \
2259     return;                                                             \
2260   }                                                                     \
2261   Register result = rscratch2;                                          \
2262   if (prev->is_valid())                                                 \
2263     result = different(prev, incr, addr) ? prev : rscratch2;            \
2264                                                                         \
2265   Label retry_load;                                                     \
2266   if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))         \
2267     prfm(Address(addr), PSTL1STRM);                                     \
2268   bind(retry_load);                                                     \
2269   LDXR(result, addr);                                                   \
2270   OP(rscratch1, result, incr);                                          \
2271   STXR(rscratch2, rscratch1, addr);                                     \
2272   cbnzw(rscratch2, retry_load);                                         \
2273   if (prev->is_valid() && prev != result) {                             \
2274     IOP(prev, rscratch1, incr);                                         \
2275   }                                                                     \
2276 }
2277 
2278 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
2279 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
2280 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
2281 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
2282 
2283 #undef ATOMIC_OP
2284 
2285 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
2286 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
2287   if (UseLSE) {                                                         \
2288     prev = prev->is_valid() ? prev : zr;                                \
2289     AOP(sz, newv, prev, addr);                                          \
2290     return;                                                             \
2291   }                                                                     \
2292   Register result = rscratch2;                                          \
2293   if (prev->is_valid())                                                 \
2294     result = different(prev, newv, addr) ? prev : rscratch2;            \
2295                                                                         \
2296   Label retry_load;                                                     \
2297   if ((VM_Version::features() & VM_Version::CPU_STXR_PREFETCH))         \
2298     prfm(Address(addr), PSTL1STRM);                                     \
2299   bind(retry_load);                                                     \
2300   LDXR(result, addr);                                                   \
2301   STXR(rscratch1, newv, addr);                                          \
2302   cbnzw(rscratch1, retry_load);                                         \
2303   if (prev->is_valid() && prev != result)                               \
2304     mov(prev, result);                                                  \
2305 }
2306 
2307 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
2308 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
2309 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
2310 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
2311 
2312 #undef ATOMIC_XCHG
2313 
2314 void MacroAssembler::incr_allocated_bytes(Register thread,
2315                                           Register var_size_in_bytes,
2316                                           int con_size_in_bytes,
2317                                           Register t1) {
2318   if (!thread->is_valid()) {
2319     thread = rthread;
2320   }
2321   assert(t1->is_valid(), "need temp reg");
2322 
2323   ldr(t1, Address(thread, in_bytes(JavaThread::allocated_bytes_offset())));
2324   if (var_size_in_bytes->is_valid()) {
2325     add(t1, t1, var_size_in_bytes);
2326   } else {
2327     add(t1, t1, con_size_in_bytes);
2328   }
2329   str(t1, Address(thread, in_bytes(JavaThread::allocated_bytes_offset())));
2330 }
2331 
2332 #ifndef PRODUCT
2333 extern "C" void findpc(intptr_t x);
2334 #endif
2335 
2336 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
2337 {
2338   // In order to get locks to work, we need to fake a in_VM state
2339   if (ShowMessageBoxOnError ) {
2340     JavaThread* thread = JavaThread::current();
2341     JavaThreadState saved_state = thread->thread_state();
2342     thread->set_thread_state(_thread_in_vm);
2343 #ifndef PRODUCT
2344     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
2345       ttyLocker ttyl;
2346       BytecodeCounter::print();
2347     }
2348 #endif
2349 
2350     if (os::message_box(msg, "Execution stopped, print registers?")) {
2351       ttyLocker ttyl;
2352       tty->print_cr(" pc = 0x%016lx", pc);
2353 #ifndef PRODUCT
2354       tty->cr();
2355       findpc(pc);
2356       tty->cr();
2357 #endif
2358       tty->print_cr(" r0 = 0x%016lx", regs[0]);
2359       tty->print_cr(" r1 = 0x%016lx", regs[1]);
2360       tty->print_cr(" r2 = 0x%016lx", regs[2]);
2361       tty->print_cr(" r3 = 0x%016lx", regs[3]);
2362       tty->print_cr(" r4 = 0x%016lx", regs[4]);
2363       tty->print_cr(" r5 = 0x%016lx", regs[5]);
2364       tty->print_cr(" r6 = 0x%016lx", regs[6]);
2365       tty->print_cr(" r7 = 0x%016lx", regs[7]);
2366       tty->print_cr(" r8 = 0x%016lx", regs[8]);
2367       tty->print_cr(" r9 = 0x%016lx", regs[9]);
2368       tty->print_cr("r10 = 0x%016lx", regs[10]);
2369       tty->print_cr("r11 = 0x%016lx", regs[11]);
2370       tty->print_cr("r12 = 0x%016lx", regs[12]);
2371       tty->print_cr("r13 = 0x%016lx", regs[13]);
2372       tty->print_cr("r14 = 0x%016lx", regs[14]);
2373       tty->print_cr("r15 = 0x%016lx", regs[15]);
2374       tty->print_cr("r16 = 0x%016lx", regs[16]);
2375       tty->print_cr("r17 = 0x%016lx", regs[17]);
2376       tty->print_cr("r18 = 0x%016lx", regs[18]);
2377       tty->print_cr("r19 = 0x%016lx", regs[19]);
2378       tty->print_cr("r20 = 0x%016lx", regs[20]);
2379       tty->print_cr("r21 = 0x%016lx", regs[21]);
2380       tty->print_cr("r22 = 0x%016lx", regs[22]);
2381       tty->print_cr("r23 = 0x%016lx", regs[23]);
2382       tty->print_cr("r24 = 0x%016lx", regs[24]);
2383       tty->print_cr("r25 = 0x%016lx", regs[25]);
2384       tty->print_cr("r26 = 0x%016lx", regs[26]);
2385       tty->print_cr("r27 = 0x%016lx", regs[27]);
2386       tty->print_cr("r28 = 0x%016lx", regs[28]);
2387       tty->print_cr("r30 = 0x%016lx", regs[30]);
2388       tty->print_cr("r31 = 0x%016lx", regs[31]);
2389       BREAKPOINT;
2390     }
2391     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
2392   } else {
2393     ttyLocker ttyl;
2394     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
2395                     msg);
2396     os::print_location(tty, pc, true);
2397     // A good place for a breakpoint:
2398     asm volatile("nop" : : "r"(pc), "r"(regs));
2399     assert(false, "DEBUG MESSAGE: %s", msg);
2400   }
2401 }
2402 
2403 #ifdef BUILTIN_SIM
2404 // routine to generate an x86 prolog for a stub function which
2405 // bootstraps into the generated ARM code which directly follows the
2406 // stub
2407 //
2408 // the argument encodes the number of general and fp registers
2409 // passed by the caller and the callng convention (currently just
2410 // the number of general registers and assumes C argument passing)
2411 
2412 extern "C" {
2413 int aarch64_stub_prolog_size();
2414 void aarch64_stub_prolog();
2415 void aarch64_prolog();
2416 }
2417 
2418 void MacroAssembler::c_stub_prolog(int gp_arg_count, int fp_arg_count, int ret_type,
2419                                    address *prolog_ptr)
2420 {
2421   int calltype = (((ret_type & 0x3) << 8) |
2422                   ((fp_arg_count & 0xf) << 4) |
2423                   (gp_arg_count & 0xf));
2424 
2425   // the addresses for the x86 to ARM entry code we need to use
2426   address start = pc();
2427   // printf("start = %lx\n", start);
2428   int byteCount =  aarch64_stub_prolog_size();
2429   // printf("byteCount = %x\n", byteCount);
2430   int instructionCount = (byteCount + 3)/ 4;
2431   // printf("instructionCount = %x\n", instructionCount);
2432   for (int i = 0; i < instructionCount; i++) {
2433     nop();
2434   }
2435 
2436   memcpy(start, (void*)aarch64_stub_prolog, byteCount);
2437 
2438   // write the address of the setup routine and the call format at the
2439   // end of into the copied code
2440   u_int64_t *patch_end = (u_int64_t *)(start + byteCount);
2441   if (prolog_ptr)
2442     patch_end[-2] = (u_int64_t)prolog_ptr;
2443   patch_end[-1] = calltype;
2444 }
2445 #endif
2446 
2447 void MacroAssembler::push_call_clobbered_fp_registers() {
2448   // Push v0-v7, v16-v31.
2449   for (int i = 30; i >= 0; i -= 2) {
2450     if (i <= v7->encoding() || i >= v16->encoding()) {
2451         stpd(as_FloatRegister(i), as_FloatRegister(i+1),
2452              Address(pre(sp, -2 * wordSize)));
2453     }
2454   }
2455 }
2456 
2457 void MacroAssembler::pop_call_clobbered_fp_registers() {
2458 
2459   for (int i = 0; i < 32; i += 2) {
2460     if (i <= v7->encoding() || i >= v16->encoding()) {
2461       ldpd(as_FloatRegister(i), as_FloatRegister(i+1),
2462            Address(post(sp, 2 * wordSize)));
2463     }
2464   }
2465 }
2466 
2467 void MacroAssembler::push_call_clobbered_registers() {
2468   push(RegSet::range(r0, r18) - RegSet::of(rscratch1, rscratch2), sp);
2469 
2470   push_call_clobbered_fp_registers();
2471 }
2472 
2473 void MacroAssembler::pop_call_clobbered_registers() {
2474   pop_call_clobbered_fp_registers();
2475 
2476   pop(RegSet::range(r0, r18) - RegSet::of(rscratch1, rscratch2), sp);
2477 }
2478 
2479 void MacroAssembler::push_CPU_state(bool save_vectors) {
2480   push(0x3fffffff, sp);         // integer registers except lr & sp
2481 
2482   if (!save_vectors) {
2483     for (int i = 30; i >= 0; i -= 2)
2484       stpd(as_FloatRegister(i), as_FloatRegister(i+1),
2485            Address(pre(sp, -2 * wordSize)));
2486   } else {
2487     for (int i = 30; i >= 0; i -= 2)
2488       stpq(as_FloatRegister(i), as_FloatRegister(i+1),
2489            Address(pre(sp, -4 * wordSize)));
2490   }
2491 }
2492 
2493 void MacroAssembler::pop_CPU_state(bool restore_vectors) {
2494   if (!restore_vectors) {
2495     for (int i = 0; i < 32; i += 2)
2496       ldpd(as_FloatRegister(i), as_FloatRegister(i+1),
2497            Address(post(sp, 2 * wordSize)));
2498   } else {
2499     for (int i = 0; i < 32; i += 2)
2500       ldpq(as_FloatRegister(i), as_FloatRegister(i+1),
2501            Address(post(sp, 4 * wordSize)));
2502   }
2503 
2504   pop(0x3fffffff, sp);         // integer registers except lr & sp
2505 }
2506 
2507 /**
2508  * Helpers for multiply_to_len().
2509  */
2510 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
2511                                      Register src1, Register src2) {
2512   adds(dest_lo, dest_lo, src1);
2513   adc(dest_hi, dest_hi, zr);
2514   adds(dest_lo, dest_lo, src2);
2515   adc(final_dest_hi, dest_hi, zr);
2516 }
2517 
2518 // Generate an address from (r + r1 extend offset).  "size" is the
2519 // size of the operand.  The result may be in rscratch2.
2520 Address MacroAssembler::offsetted_address(Register r, Register r1,
2521                                           Address::extend ext, int offset, int size) {
2522   if (offset || (ext.shift() % size != 0)) {
2523     lea(rscratch2, Address(r, r1, ext));
2524     return Address(rscratch2, offset);
2525   } else {
2526     return Address(r, r1, ext);
2527   }
2528 }
2529 
2530 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
2531 {
2532   assert(offset >= 0, "spill to negative address?");
2533   // Offset reachable ?
2534   //   Not aligned - 9 bits signed offset
2535   //   Aligned - 12 bits unsigned offset shifted
2536   Register base = sp;
2537   if ((offset & (size-1)) && offset >= (1<<8)) {
2538     add(tmp, base, offset & ((1<<12)-1));
2539     base = tmp;
2540     offset &= -1<<12;
2541   }
2542 
2543   if (offset >= (1<<12) * size) {
2544     add(tmp, base, offset & (((1<<12)-1)<<12));
2545     base = tmp;
2546     offset &= ~(((1<<12)-1)<<12);
2547   }
2548 
2549   return Address(base, offset);
2550 }
2551 
2552 /**
2553  * Multiply 64 bit by 64 bit first loop.
2554  */
2555 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
2556                                            Register y, Register y_idx, Register z,
2557                                            Register carry, Register product,
2558                                            Register idx, Register kdx) {
2559   //
2560   //  jlong carry, x[], y[], z[];
2561   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2562   //    huge_128 product = y[idx] * x[xstart] + carry;
2563   //    z[kdx] = (jlong)product;
2564   //    carry  = (jlong)(product >>> 64);
2565   //  }
2566   //  z[xstart] = carry;
2567   //
2568 
2569   Label L_first_loop, L_first_loop_exit;
2570   Label L_one_x, L_one_y, L_multiply;
2571 
2572   subsw(xstart, xstart, 1);
2573   br(Assembler::MI, L_one_x);
2574 
2575   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
2576   ldr(x_xstart, Address(rscratch1));
2577   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
2578 
2579   bind(L_first_loop);
2580   subsw(idx, idx, 1);
2581   br(Assembler::MI, L_first_loop_exit);
2582   subsw(idx, idx, 1);
2583   br(Assembler::MI, L_one_y);
2584   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2585   ldr(y_idx, Address(rscratch1));
2586   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
2587   bind(L_multiply);
2588 
2589   // AArch64 has a multiply-accumulate instruction that we can't use
2590   // here because it has no way to process carries, so we have to use
2591   // separate add and adc instructions.  Bah.
2592   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
2593   mul(product, x_xstart, y_idx);
2594   adds(product, product, carry);
2595   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
2596 
2597   subw(kdx, kdx, 2);
2598   ror(product, product, 32); // back to big-endian
2599   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
2600 
2601   b(L_first_loop);
2602 
2603   bind(L_one_y);
2604   ldrw(y_idx, Address(y,  0));
2605   b(L_multiply);
2606 
2607   bind(L_one_x);
2608   ldrw(x_xstart, Address(x,  0));
2609   b(L_first_loop);
2610 
2611   bind(L_first_loop_exit);
2612 }
2613 
2614 /**
2615  * Multiply 128 bit by 128. Unrolled inner loop.
2616  *
2617  */
2618 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
2619                                              Register carry, Register carry2,
2620                                              Register idx, Register jdx,
2621                                              Register yz_idx1, Register yz_idx2,
2622                                              Register tmp, Register tmp3, Register tmp4,
2623                                              Register tmp6, Register product_hi) {
2624 
2625   //   jlong carry, x[], y[], z[];
2626   //   int kdx = ystart+1;
2627   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
2628   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
2629   //     jlong carry2  = (jlong)(tmp3 >>> 64);
2630   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
2631   //     carry  = (jlong)(tmp4 >>> 64);
2632   //     z[kdx+idx+1] = (jlong)tmp3;
2633   //     z[kdx+idx] = (jlong)tmp4;
2634   //   }
2635   //   idx += 2;
2636   //   if (idx > 0) {
2637   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
2638   //     z[kdx+idx] = (jlong)yz_idx1;
2639   //     carry  = (jlong)(yz_idx1 >>> 64);
2640   //   }
2641   //
2642 
2643   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
2644 
2645   lsrw(jdx, idx, 2);
2646 
2647   bind(L_third_loop);
2648 
2649   subsw(jdx, jdx, 1);
2650   br(Assembler::MI, L_third_loop_exit);
2651   subw(idx, idx, 4);
2652 
2653   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2654 
2655   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
2656 
2657   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2658 
2659   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
2660   ror(yz_idx2, yz_idx2, 32);
2661 
2662   ldp(rscratch2, rscratch1, Address(tmp6, 0));
2663 
2664   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2665   umulh(tmp4, product_hi, yz_idx1);
2666 
2667   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
2668   ror(rscratch2, rscratch2, 32);
2669 
2670   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
2671   umulh(carry2, product_hi, yz_idx2);
2672 
2673   // propagate sum of both multiplications into carry:tmp4:tmp3
2674   adds(tmp3, tmp3, carry);
2675   adc(tmp4, tmp4, zr);
2676   adds(tmp3, tmp3, rscratch1);
2677   adcs(tmp4, tmp4, tmp);
2678   adc(carry, carry2, zr);
2679   adds(tmp4, tmp4, rscratch2);
2680   adc(carry, carry, zr);
2681 
2682   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
2683   ror(tmp4, tmp4, 32);
2684   stp(tmp4, tmp3, Address(tmp6, 0));
2685 
2686   b(L_third_loop);
2687   bind (L_third_loop_exit);
2688 
2689   andw (idx, idx, 0x3);
2690   cbz(idx, L_post_third_loop_done);
2691 
2692   Label L_check_1;
2693   subsw(idx, idx, 2);
2694   br(Assembler::MI, L_check_1);
2695 
2696   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2697   ldr(yz_idx1, Address(rscratch1, 0));
2698   ror(yz_idx1, yz_idx1, 32);
2699   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2700   umulh(tmp4, product_hi, yz_idx1);
2701   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2702   ldr(yz_idx2, Address(rscratch1, 0));
2703   ror(yz_idx2, yz_idx2, 32);
2704 
2705   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
2706 
2707   ror(tmp3, tmp3, 32);
2708   str(tmp3, Address(rscratch1, 0));
2709 
2710   bind (L_check_1);
2711 
2712   andw (idx, idx, 0x1);
2713   subsw(idx, idx, 1);
2714   br(Assembler::MI, L_post_third_loop_done);
2715   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2716   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
2717   umulh(carry2, tmp4, product_hi);
2718   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2719 
2720   add2_with_carry(carry2, tmp3, tmp4, carry);
2721 
2722   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2723   extr(carry, carry2, tmp3, 32);
2724 
2725   bind(L_post_third_loop_done);
2726 }
2727 
2728 /**
2729  * Code for BigInteger::multiplyToLen() instrinsic.
2730  *
2731  * r0: x
2732  * r1: xlen
2733  * r2: y
2734  * r3: ylen
2735  * r4:  z
2736  * r5: zlen
2737  * r10: tmp1
2738  * r11: tmp2
2739  * r12: tmp3
2740  * r13: tmp4
2741  * r14: tmp5
2742  * r15: tmp6
2743  * r16: tmp7
2744  *
2745  */
2746 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
2747                                      Register z, Register zlen,
2748                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
2749                                      Register tmp5, Register tmp6, Register product_hi) {
2750 
2751   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6);
2752 
2753   const Register idx = tmp1;
2754   const Register kdx = tmp2;
2755   const Register xstart = tmp3;
2756 
2757   const Register y_idx = tmp4;
2758   const Register carry = tmp5;
2759   const Register product  = xlen;
2760   const Register x_xstart = zlen;  // reuse register
2761 
2762   // First Loop.
2763   //
2764   //  final static long LONG_MASK = 0xffffffffL;
2765   //  int xstart = xlen - 1;
2766   //  int ystart = ylen - 1;
2767   //  long carry = 0;
2768   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2769   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
2770   //    z[kdx] = (int)product;
2771   //    carry = product >>> 32;
2772   //  }
2773   //  z[xstart] = (int)carry;
2774   //
2775 
2776   movw(idx, ylen);      // idx = ylen;
2777   movw(kdx, zlen);      // kdx = xlen+ylen;
2778   mov(carry, zr);       // carry = 0;
2779 
2780   Label L_done;
2781 
2782   movw(xstart, xlen);
2783   subsw(xstart, xstart, 1);
2784   br(Assembler::MI, L_done);
2785 
2786   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
2787 
2788   Label L_second_loop;
2789   cbzw(kdx, L_second_loop);
2790 
2791   Label L_carry;
2792   subw(kdx, kdx, 1);
2793   cbzw(kdx, L_carry);
2794 
2795   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
2796   lsr(carry, carry, 32);
2797   subw(kdx, kdx, 1);
2798 
2799   bind(L_carry);
2800   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
2801 
2802   // Second and third (nested) loops.
2803   //
2804   // for (int i = xstart-1; i >= 0; i--) { // Second loop
2805   //   carry = 0;
2806   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
2807   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
2808   //                    (z[k] & LONG_MASK) + carry;
2809   //     z[k] = (int)product;
2810   //     carry = product >>> 32;
2811   //   }
2812   //   z[i] = (int)carry;
2813   // }
2814   //
2815   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
2816 
2817   const Register jdx = tmp1;
2818 
2819   bind(L_second_loop);
2820   mov(carry, zr);                // carry = 0;
2821   movw(jdx, ylen);               // j = ystart+1
2822 
2823   subsw(xstart, xstart, 1);      // i = xstart-1;
2824   br(Assembler::MI, L_done);
2825 
2826   str(z, Address(pre(sp, -4 * wordSize)));
2827 
2828   Label L_last_x;
2829   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
2830   subsw(xstart, xstart, 1);       // i = xstart-1;
2831   br(Assembler::MI, L_last_x);
2832 
2833   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
2834   ldr(product_hi, Address(rscratch1));
2835   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
2836 
2837   Label L_third_loop_prologue;
2838   bind(L_third_loop_prologue);
2839 
2840   str(ylen, Address(sp, wordSize));
2841   stp(x, xstart, Address(sp, 2 * wordSize));
2842   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
2843                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
2844   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
2845   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
2846 
2847   addw(tmp3, xlen, 1);
2848   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
2849   subsw(tmp3, tmp3, 1);
2850   br(Assembler::MI, L_done);
2851 
2852   lsr(carry, carry, 32);
2853   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
2854   b(L_second_loop);
2855 
2856   // Next infrequent code is moved outside loops.
2857   bind(L_last_x);
2858   ldrw(product_hi, Address(x,  0));
2859   b(L_third_loop_prologue);
2860 
2861   bind(L_done);
2862 }
2863 
2864 /**
2865  * Emits code to update CRC-32 with a byte value according to constants in table
2866  *
2867  * @param [in,out]crc   Register containing the crc.
2868  * @param [in]val       Register containing the byte to fold into the CRC.
2869  * @param [in]table     Register containing the table of crc constants.
2870  *
2871  * uint32_t crc;
2872  * val = crc_table[(val ^ crc) & 0xFF];
2873  * crc = val ^ (crc >> 8);
2874  *
2875  */
2876 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
2877   eor(val, val, crc);
2878   andr(val, val, 0xff);
2879   ldrw(val, Address(table, val, Address::lsl(2)));
2880   eor(crc, val, crc, Assembler::LSR, 8);
2881 }
2882 
2883 /**
2884  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
2885  *
2886  * @param [in,out]crc   Register containing the crc.
2887  * @param [in]v         Register containing the 32-bit to fold into the CRC.
2888  * @param [in]table0    Register containing table 0 of crc constants.
2889  * @param [in]table1    Register containing table 1 of crc constants.
2890  * @param [in]table2    Register containing table 2 of crc constants.
2891  * @param [in]table3    Register containing table 3 of crc constants.
2892  *
2893  * uint32_t crc;
2894  *   v = crc ^ v
2895  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
2896  *
2897  */
2898 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
2899         Register table0, Register table1, Register table2, Register table3,
2900         bool upper) {
2901   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
2902   uxtb(tmp, v);
2903   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
2904   ubfx(tmp, v, 8, 8);
2905   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
2906   eor(crc, crc, tmp);
2907   ubfx(tmp, v, 16, 8);
2908   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
2909   eor(crc, crc, tmp);
2910   ubfx(tmp, v, 24, 8);
2911   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
2912   eor(crc, crc, tmp);
2913 }
2914 
2915 /**
2916  * @param crc   register containing existing CRC (32-bit)
2917  * @param buf   register pointing to input byte buffer (byte*)
2918  * @param len   register containing number of bytes
2919  * @param table register that will contain address of CRC table
2920  * @param tmp   scratch register
2921  */
2922 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
2923         Register table0, Register table1, Register table2, Register table3,
2924         Register tmp, Register tmp2, Register tmp3) {
2925   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
2926   unsigned long offset;
2927 
2928     ornw(crc, zr, crc);
2929 
2930   if (UseCRC32) {
2931     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop;
2932 
2933       subs(len, len, 64);
2934       br(Assembler::GE, CRC_by64_loop);
2935       adds(len, len, 64-4);
2936       br(Assembler::GE, CRC_by4_loop);
2937       adds(len, len, 4);
2938       br(Assembler::GT, CRC_by1_loop);
2939       b(L_exit);
2940 
2941     BIND(CRC_by4_loop);
2942       ldrw(tmp, Address(post(buf, 4)));
2943       subs(len, len, 4);
2944       crc32w(crc, crc, tmp);
2945       br(Assembler::GE, CRC_by4_loop);
2946       adds(len, len, 4);
2947       br(Assembler::LE, L_exit);
2948     BIND(CRC_by1_loop);
2949       ldrb(tmp, Address(post(buf, 1)));
2950       subs(len, len, 1);
2951       crc32b(crc, crc, tmp);
2952       br(Assembler::GT, CRC_by1_loop);
2953       b(L_exit);
2954 
2955       align(CodeEntryAlignment);
2956     BIND(CRC_by64_loop);
2957       subs(len, len, 64);
2958       ldp(tmp, tmp3, Address(post(buf, 16)));
2959       crc32x(crc, crc, tmp);
2960       crc32x(crc, crc, tmp3);
2961       ldp(tmp, tmp3, Address(post(buf, 16)));
2962       crc32x(crc, crc, tmp);
2963       crc32x(crc, crc, tmp3);
2964       ldp(tmp, tmp3, Address(post(buf, 16)));
2965       crc32x(crc, crc, tmp);
2966       crc32x(crc, crc, tmp3);
2967       ldp(tmp, tmp3, Address(post(buf, 16)));
2968       crc32x(crc, crc, tmp);
2969       crc32x(crc, crc, tmp3);
2970       br(Assembler::GE, CRC_by64_loop);
2971       adds(len, len, 64-4);
2972       br(Assembler::GE, CRC_by4_loop);
2973       adds(len, len, 4);
2974       br(Assembler::GT, CRC_by1_loop);
2975     BIND(L_exit);
2976       ornw(crc, zr, crc);
2977       return;
2978   }
2979 
2980     adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
2981     if (offset) add(table0, table0, offset);
2982     add(table1, table0, 1*256*sizeof(juint));
2983     add(table2, table0, 2*256*sizeof(juint));
2984     add(table3, table0, 3*256*sizeof(juint));
2985 
2986   if (UseNeon) {
2987       cmp(len, 64);
2988       br(Assembler::LT, L_by16);
2989       eor(v16, T16B, v16, v16);
2990 
2991     Label L_fold;
2992 
2993       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
2994 
2995       ld1(v0, v1, T2D, post(buf, 32));
2996       ld1r(v4, T2D, post(tmp, 8));
2997       ld1r(v5, T2D, post(tmp, 8));
2998       ld1r(v6, T2D, post(tmp, 8));
2999       ld1r(v7, T2D, post(tmp, 8));
3000       mov(v16, T4S, 0, crc);
3001 
3002       eor(v0, T16B, v0, v16);
3003       sub(len, len, 64);
3004 
3005     BIND(L_fold);
3006       pmull(v22, T8H, v0, v5, T8B);
3007       pmull(v20, T8H, v0, v7, T8B);
3008       pmull(v23, T8H, v0, v4, T8B);
3009       pmull(v21, T8H, v0, v6, T8B);
3010 
3011       pmull2(v18, T8H, v0, v5, T16B);
3012       pmull2(v16, T8H, v0, v7, T16B);
3013       pmull2(v19, T8H, v0, v4, T16B);
3014       pmull2(v17, T8H, v0, v6, T16B);
3015 
3016       uzp1(v24, v20, v22, T8H);
3017       uzp2(v25, v20, v22, T8H);
3018       eor(v20, T16B, v24, v25);
3019 
3020       uzp1(v26, v16, v18, T8H);
3021       uzp2(v27, v16, v18, T8H);
3022       eor(v16, T16B, v26, v27);
3023 
3024       ushll2(v22, T4S, v20, T8H, 8);
3025       ushll(v20, T4S, v20, T4H, 8);
3026 
3027       ushll2(v18, T4S, v16, T8H, 8);
3028       ushll(v16, T4S, v16, T4H, 8);
3029 
3030       eor(v22, T16B, v23, v22);
3031       eor(v18, T16B, v19, v18);
3032       eor(v20, T16B, v21, v20);
3033       eor(v16, T16B, v17, v16);
3034 
3035       uzp1(v17, v16, v20, T2D);
3036       uzp2(v21, v16, v20, T2D);
3037       eor(v17, T16B, v17, v21);
3038 
3039       ushll2(v20, T2D, v17, T4S, 16);
3040       ushll(v16, T2D, v17, T2S, 16);
3041 
3042       eor(v20, T16B, v20, v22);
3043       eor(v16, T16B, v16, v18);
3044 
3045       uzp1(v17, v20, v16, T2D);
3046       uzp2(v21, v20, v16, T2D);
3047       eor(v28, T16B, v17, v21);
3048 
3049       pmull(v22, T8H, v1, v5, T8B);
3050       pmull(v20, T8H, v1, v7, T8B);
3051       pmull(v23, T8H, v1, v4, T8B);
3052       pmull(v21, T8H, v1, v6, T8B);
3053 
3054       pmull2(v18, T8H, v1, v5, T16B);
3055       pmull2(v16, T8H, v1, v7, T16B);
3056       pmull2(v19, T8H, v1, v4, T16B);
3057       pmull2(v17, T8H, v1, v6, T16B);
3058 
3059       ld1(v0, v1, T2D, post(buf, 32));
3060 
3061       uzp1(v24, v20, v22, T8H);
3062       uzp2(v25, v20, v22, T8H);
3063       eor(v20, T16B, v24, v25);
3064 
3065       uzp1(v26, v16, v18, T8H);
3066       uzp2(v27, v16, v18, T8H);
3067       eor(v16, T16B, v26, v27);
3068 
3069       ushll2(v22, T4S, v20, T8H, 8);
3070       ushll(v20, T4S, v20, T4H, 8);
3071 
3072       ushll2(v18, T4S, v16, T8H, 8);
3073       ushll(v16, T4S, v16, T4H, 8);
3074 
3075       eor(v22, T16B, v23, v22);
3076       eor(v18, T16B, v19, v18);
3077       eor(v20, T16B, v21, v20);
3078       eor(v16, T16B, v17, v16);
3079 
3080       uzp1(v17, v16, v20, T2D);
3081       uzp2(v21, v16, v20, T2D);
3082       eor(v16, T16B, v17, v21);
3083 
3084       ushll2(v20, T2D, v16, T4S, 16);
3085       ushll(v16, T2D, v16, T2S, 16);
3086 
3087       eor(v20, T16B, v22, v20);
3088       eor(v16, T16B, v16, v18);
3089 
3090       uzp1(v17, v20, v16, T2D);
3091       uzp2(v21, v20, v16, T2D);
3092       eor(v20, T16B, v17, v21);
3093 
3094       shl(v16, T2D, v28, 1);
3095       shl(v17, T2D, v20, 1);
3096 
3097       eor(v0, T16B, v0, v16);
3098       eor(v1, T16B, v1, v17);
3099 
3100       subs(len, len, 32);
3101       br(Assembler::GE, L_fold);
3102 
3103       mov(crc, 0);
3104       mov(tmp, v0, T1D, 0);
3105       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3106       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3107       mov(tmp, v0, T1D, 1);
3108       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3109       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3110       mov(tmp, v1, T1D, 0);
3111       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3112       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3113       mov(tmp, v1, T1D, 1);
3114       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3115       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3116 
3117       add(len, len, 32);
3118   }
3119 
3120   BIND(L_by16);
3121     subs(len, len, 16);
3122     br(Assembler::GE, L_by16_loop);
3123     adds(len, len, 16-4);
3124     br(Assembler::GE, L_by4_loop);
3125     adds(len, len, 4);
3126     br(Assembler::GT, L_by1_loop);
3127     b(L_exit);
3128 
3129   BIND(L_by4_loop);
3130     ldrw(tmp, Address(post(buf, 4)));
3131     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
3132     subs(len, len, 4);
3133     br(Assembler::GE, L_by4_loop);
3134     adds(len, len, 4);
3135     br(Assembler::LE, L_exit);
3136   BIND(L_by1_loop);
3137     subs(len, len, 1);
3138     ldrb(tmp, Address(post(buf, 1)));
3139     update_byte_crc32(crc, tmp, table0);
3140     br(Assembler::GT, L_by1_loop);
3141     b(L_exit);
3142 
3143     align(CodeEntryAlignment);
3144   BIND(L_by16_loop);
3145     subs(len, len, 16);
3146     ldp(tmp, tmp3, Address(post(buf, 16)));
3147     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
3148     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
3149     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
3150     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
3151     br(Assembler::GE, L_by16_loop);
3152     adds(len, len, 16-4);
3153     br(Assembler::GE, L_by4_loop);
3154     adds(len, len, 4);
3155     br(Assembler::GT, L_by1_loop);
3156   BIND(L_exit);
3157     ornw(crc, zr, crc);
3158 }
3159 
3160 /**
3161  * @param crc   register containing existing CRC (32-bit)
3162  * @param buf   register pointing to input byte buffer (byte*)
3163  * @param len   register containing number of bytes
3164  * @param table register that will contain address of CRC table
3165  * @param tmp   scratch register
3166  */
3167 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
3168         Register table0, Register table1, Register table2, Register table3,
3169         Register tmp, Register tmp2, Register tmp3) {
3170   Label L_exit;
3171   Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop;
3172 
3173     subs(len, len, 64);
3174     br(Assembler::GE, CRC_by64_loop);
3175     adds(len, len, 64-4);
3176     br(Assembler::GE, CRC_by4_loop);
3177     adds(len, len, 4);
3178     br(Assembler::GT, CRC_by1_loop);
3179     b(L_exit);
3180 
3181   BIND(CRC_by4_loop);
3182     ldrw(tmp, Address(post(buf, 4)));
3183     subs(len, len, 4);
3184     crc32cw(crc, crc, tmp);
3185     br(Assembler::GE, CRC_by4_loop);
3186     adds(len, len, 4);
3187     br(Assembler::LE, L_exit);
3188   BIND(CRC_by1_loop);
3189     ldrb(tmp, Address(post(buf, 1)));
3190     subs(len, len, 1);
3191     crc32cb(crc, crc, tmp);
3192     br(Assembler::GT, CRC_by1_loop);
3193     b(L_exit);
3194 
3195     align(CodeEntryAlignment);
3196   BIND(CRC_by64_loop);
3197     subs(len, len, 64);
3198     ldp(tmp, tmp3, Address(post(buf, 16)));
3199     crc32cx(crc, crc, tmp);
3200     crc32cx(crc, crc, tmp3);
3201     ldp(tmp, tmp3, Address(post(buf, 16)));
3202     crc32cx(crc, crc, tmp);
3203     crc32cx(crc, crc, tmp3);
3204     ldp(tmp, tmp3, Address(post(buf, 16)));
3205     crc32cx(crc, crc, tmp);
3206     crc32cx(crc, crc, tmp3);
3207     ldp(tmp, tmp3, Address(post(buf, 16)));
3208     crc32cx(crc, crc, tmp);
3209     crc32cx(crc, crc, tmp3);
3210     br(Assembler::GE, CRC_by64_loop);
3211     adds(len, len, 64-4);
3212     br(Assembler::GE, CRC_by4_loop);
3213     adds(len, len, 4);
3214     br(Assembler::GT, CRC_by1_loop);
3215   BIND(L_exit);
3216     return;
3217 }
3218 
3219 SkipIfEqual::SkipIfEqual(
3220     MacroAssembler* masm, const bool* flag_addr, bool value) {
3221   _masm = masm;
3222   unsigned long offset;
3223   _masm->adrp(rscratch1, ExternalAddress((address)flag_addr), offset);
3224   _masm->ldrb(rscratch1, Address(rscratch1, offset));
3225   _masm->cbzw(rscratch1, _label);
3226 }
3227 
3228 SkipIfEqual::~SkipIfEqual() {
3229   _masm->bind(_label);
3230 }
3231 
3232 void MacroAssembler::addptr(const Address &dst, int32_t src) {
3233   Address adr;
3234   switch(dst.getMode()) {
3235   case Address::base_plus_offset:
3236     // This is the expected mode, although we allow all the other
3237     // forms below.
3238     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
3239     break;
3240   default:
3241     lea(rscratch2, dst);
3242     adr = Address(rscratch2);
3243     break;
3244   }
3245   ldr(rscratch1, adr);
3246   add(rscratch1, rscratch1, src);
3247   str(rscratch1, adr);
3248 }
3249 
3250 void MacroAssembler::cmpptr(Register src1, Address src2) {
3251   unsigned long offset;
3252   adrp(rscratch1, src2, offset);
3253   ldr(rscratch1, Address(rscratch1, offset));
3254   cmp(src1, rscratch1);
3255 }
3256 
3257 void MacroAssembler::store_check(Register obj, Address dst) {
3258   store_check(obj);
3259 }
3260 
3261 void MacroAssembler::store_check(Register obj) {
3262   // Does a store check for the oop in register obj. The content of
3263   // register obj is destroyed afterwards.
3264 
3265   BarrierSet* bs = Universe::heap()->barrier_set();
3266   assert(bs->kind() == BarrierSet::CardTableForRS ||
3267          bs->kind() == BarrierSet::CardTableExtension,
3268          "Wrong barrier set kind");
3269 
3270   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
3271   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3272 
3273   lsr(obj, obj, CardTableModRefBS::card_shift);
3274 
3275   assert(CardTableModRefBS::dirty_card_val() == 0, "must be");
3276 
3277   load_byte_map_base(rscratch1);
3278 
3279   if (UseCondCardMark) {
3280     Label L_already_dirty;
3281     membar(StoreLoad);
3282     ldrb(rscratch2,  Address(obj, rscratch1));
3283     cbz(rscratch2, L_already_dirty);
3284     strb(zr, Address(obj, rscratch1));
3285     bind(L_already_dirty);
3286   } else {
3287     if (UseConcMarkSweepGC && CMSPrecleaningEnabled) {
3288       membar(StoreStore);
3289     }
3290     strb(zr, Address(obj, rscratch1));
3291   }
3292 }
3293 
3294 void MacroAssembler::load_klass(Register dst, Register src) {
3295   if (UseCompressedClassPointers) {
3296     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3297     decode_klass_not_null(dst);
3298   } else {
3299     ldr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3300   }
3301 }
3302 
3303 void MacroAssembler::load_mirror(Register dst, Register method) {
3304   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
3305   ldr(dst, Address(rmethod, Method::const_offset()));
3306   ldr(dst, Address(dst, ConstMethod::constants_offset()));
3307   ldr(dst, Address(dst, ConstantPool::pool_holder_offset_in_bytes()));
3308   ldr(dst, Address(dst, mirror_offset));
3309 }
3310 
3311 void MacroAssembler::cmp_klass(Register oop, Register trial_klass, Register tmp) {
3312   if (UseCompressedClassPointers) {
3313     ldrw(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3314     if (Universe::narrow_klass_base() == NULL) {
3315       cmp(trial_klass, tmp, LSL, Universe::narrow_klass_shift());
3316       return;
3317     } else if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3318                && Universe::narrow_klass_shift() == 0) {
3319       // Only the bottom 32 bits matter
3320       cmpw(trial_klass, tmp);
3321       return;
3322     }
3323     decode_klass_not_null(tmp);
3324   } else {
3325     ldr(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3326   }
3327   cmp(trial_klass, tmp);
3328 }
3329 
3330 void MacroAssembler::load_prototype_header(Register dst, Register src) {
3331   load_klass(dst, src);
3332   ldr(dst, Address(dst, Klass::prototype_header_offset()));
3333 }
3334 
3335 void MacroAssembler::store_klass(Register dst, Register src) {
3336   // FIXME: Should this be a store release?  concurrent gcs assumes
3337   // klass length is valid if klass field is not null.
3338   if (UseCompressedClassPointers) {
3339     encode_klass_not_null(src);
3340     strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3341   } else {
3342     str(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3343   }
3344 }
3345 
3346 void MacroAssembler::store_klass_gap(Register dst, Register src) {
3347   if (UseCompressedClassPointers) {
3348     // Store to klass gap in destination
3349     strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
3350   }
3351 }
3352 
3353 // Algorithm must match oop.inline.hpp encode_heap_oop.
3354 void MacroAssembler::encode_heap_oop(Register d, Register s) {
3355 #ifdef ASSERT
3356   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
3357 #endif
3358   verify_oop(s, "broken oop in encode_heap_oop");
3359   if (Universe::narrow_oop_base() == NULL) {
3360     if (Universe::narrow_oop_shift() != 0) {
3361       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3362       lsr(d, s, LogMinObjAlignmentInBytes);
3363     } else {
3364       mov(d, s);
3365     }
3366   } else {
3367     subs(d, s, rheapbase);
3368     csel(d, d, zr, Assembler::HS);
3369     lsr(d, d, LogMinObjAlignmentInBytes);
3370 
3371     /*  Old algorithm: is this any worse?
3372     Label nonnull;
3373     cbnz(r, nonnull);
3374     sub(r, r, rheapbase);
3375     bind(nonnull);
3376     lsr(r, r, LogMinObjAlignmentInBytes);
3377     */
3378   }
3379 }
3380 
3381 void MacroAssembler::encode_heap_oop_not_null(Register r) {
3382 #ifdef ASSERT
3383   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
3384   if (CheckCompressedOops) {
3385     Label ok;
3386     cbnz(r, ok);
3387     stop("null oop passed to encode_heap_oop_not_null");
3388     bind(ok);
3389   }
3390 #endif
3391   verify_oop(r, "broken oop in encode_heap_oop_not_null");
3392   if (Universe::narrow_oop_base() != NULL) {
3393     sub(r, r, rheapbase);
3394   }
3395   if (Universe::narrow_oop_shift() != 0) {
3396     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3397     lsr(r, r, LogMinObjAlignmentInBytes);
3398   }
3399 }
3400 
3401 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
3402 #ifdef ASSERT
3403   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
3404   if (CheckCompressedOops) {
3405     Label ok;
3406     cbnz(src, ok);
3407     stop("null oop passed to encode_heap_oop_not_null2");
3408     bind(ok);
3409   }
3410 #endif
3411   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
3412 
3413   Register data = src;
3414   if (Universe::narrow_oop_base() != NULL) {
3415     sub(dst, src, rheapbase);
3416     data = dst;
3417   }
3418   if (Universe::narrow_oop_shift() != 0) {
3419     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3420     lsr(dst, data, LogMinObjAlignmentInBytes);
3421     data = dst;
3422   }
3423   if (data == src)
3424     mov(dst, src);
3425 }
3426 
3427 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
3428 #ifdef ASSERT
3429   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
3430 #endif
3431   if (Universe::narrow_oop_base() == NULL) {
3432     if (Universe::narrow_oop_shift() != 0 || d != s) {
3433       lsl(d, s, Universe::narrow_oop_shift());
3434     }
3435   } else {
3436     Label done;
3437     if (d != s)
3438       mov(d, s);
3439     cbz(s, done);
3440     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
3441     bind(done);
3442   }
3443   verify_oop(d, "broken oop in decode_heap_oop");
3444 }
3445 
3446 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
3447   assert (UseCompressedOops, "should only be used for compressed headers");
3448   assert (Universe::heap() != NULL, "java heap should be initialized");
3449   // Cannot assert, unverified entry point counts instructions (see .ad file)
3450   // vtableStubs also counts instructions in pd_code_size_limit.
3451   // Also do not verify_oop as this is called by verify_oop.
3452   if (Universe::narrow_oop_shift() != 0) {
3453     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3454     if (Universe::narrow_oop_base() != NULL) {
3455       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3456     } else {
3457       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3458     }
3459   } else {
3460     assert (Universe::narrow_oop_base() == NULL, "sanity");
3461   }
3462 }
3463 
3464 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
3465   assert (UseCompressedOops, "should only be used for compressed headers");
3466   assert (Universe::heap() != NULL, "java heap should be initialized");
3467   // Cannot assert, unverified entry point counts instructions (see .ad file)
3468   // vtableStubs also counts instructions in pd_code_size_limit.
3469   // Also do not verify_oop as this is called by verify_oop.
3470   if (Universe::narrow_oop_shift() != 0) {
3471     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3472     if (Universe::narrow_oop_base() != NULL) {
3473       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3474     } else {
3475       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3476     }
3477   } else {
3478     assert (Universe::narrow_oop_base() == NULL, "sanity");
3479     if (dst != src) {
3480       mov(dst, src);
3481     }
3482   }
3483 }
3484 
3485 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
3486   if (Universe::narrow_klass_base() == NULL) {
3487     if (Universe::narrow_klass_shift() != 0) {
3488       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3489       lsr(dst, src, LogKlassAlignmentInBytes);
3490     } else {
3491       if (dst != src) mov(dst, src);
3492     }
3493     return;
3494   }
3495 
3496   if (use_XOR_for_compressed_class_base) {
3497     if (Universe::narrow_klass_shift() != 0) {
3498       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3499       lsr(dst, dst, LogKlassAlignmentInBytes);
3500     } else {
3501       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3502     }
3503     return;
3504   }
3505 
3506   if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3507       && Universe::narrow_klass_shift() == 0) {
3508     movw(dst, src);
3509     return;
3510   }
3511 
3512 #ifdef ASSERT
3513   verify_heapbase("MacroAssembler::encode_klass_not_null2: heap base corrupted?");
3514 #endif
3515 
3516   Register rbase = dst;
3517   if (dst == src) rbase = rheapbase;
3518   mov(rbase, (uint64_t)Universe::narrow_klass_base());
3519   sub(dst, src, rbase);
3520   if (Universe::narrow_klass_shift() != 0) {
3521     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3522     lsr(dst, dst, LogKlassAlignmentInBytes);
3523   }
3524   if (dst == src) reinit_heapbase();
3525 }
3526 
3527 void MacroAssembler::encode_klass_not_null(Register r) {
3528   encode_klass_not_null(r, r);
3529 }
3530 
3531 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
3532   Register rbase = dst;
3533   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3534 
3535   if (Universe::narrow_klass_base() == NULL) {
3536     if (Universe::narrow_klass_shift() != 0) {
3537       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3538       lsl(dst, src, LogKlassAlignmentInBytes);
3539     } else {
3540       if (dst != src) mov(dst, src);
3541     }
3542     return;
3543   }
3544 
3545   if (use_XOR_for_compressed_class_base) {
3546     if (Universe::narrow_klass_shift() != 0) {
3547       lsl(dst, src, LogKlassAlignmentInBytes);
3548       eor(dst, dst, (uint64_t)Universe::narrow_klass_base());
3549     } else {
3550       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3551     }
3552     return;
3553   }
3554 
3555   if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3556       && Universe::narrow_klass_shift() == 0) {
3557     if (dst != src)
3558       movw(dst, src);
3559     movk(dst, (uint64_t)Universe::narrow_klass_base() >> 32, 32);
3560     return;
3561   }
3562 
3563   // Cannot assert, unverified entry point counts instructions (see .ad file)
3564   // vtableStubs also counts instructions in pd_code_size_limit.
3565   // Also do not verify_oop as this is called by verify_oop.
3566   if (dst == src) rbase = rheapbase;
3567   mov(rbase, (uint64_t)Universe::narrow_klass_base());
3568   if (Universe::narrow_klass_shift() != 0) {
3569     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3570     add(dst, rbase, src, Assembler::LSL, LogKlassAlignmentInBytes);
3571   } else {
3572     add(dst, rbase, src);
3573   }
3574   if (dst == src) reinit_heapbase();
3575 }
3576 
3577 void  MacroAssembler::decode_klass_not_null(Register r) {
3578   decode_klass_not_null(r, r);
3579 }
3580 
3581 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
3582   assert (UseCompressedOops, "should only be used for compressed oops");
3583   assert (Universe::heap() != NULL, "java heap should be initialized");
3584   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
3585 
3586   int oop_index = oop_recorder()->find_index(obj);
3587   assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "should be real oop");
3588 
3589   InstructionMark im(this);
3590   RelocationHolder rspec = oop_Relocation::spec(oop_index);
3591   code_section()->relocate(inst_mark(), rspec);
3592   movz(dst, 0xDEAD, 16);
3593   movk(dst, 0xBEEF);
3594 }
3595 
3596 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
3597   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3598   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
3599   int index = oop_recorder()->find_index(k);
3600   assert(! Universe::heap()->is_in_reserved(k), "should not be an oop");
3601 
3602   InstructionMark im(this);
3603   RelocationHolder rspec = metadata_Relocation::spec(index);
3604   code_section()->relocate(inst_mark(), rspec);
3605   narrowKlass nk = Klass::encode_klass(k);
3606   movz(dst, (nk >> 16), 16);
3607   movk(dst, nk & 0xffff);
3608 }
3609 
3610 void MacroAssembler::load_heap_oop(Register dst, Address src)
3611 {
3612   if (UseCompressedOops) {
3613     ldrw(dst, src);
3614     decode_heap_oop(dst);
3615   } else {
3616     ldr(dst, src);
3617   }
3618 }
3619 
3620 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src)
3621 {
3622   if (UseCompressedOops) {
3623     ldrw(dst, src);
3624     decode_heap_oop_not_null(dst);
3625   } else {
3626     ldr(dst, src);
3627   }
3628 }
3629 
3630 void MacroAssembler::store_heap_oop(Address dst, Register src) {
3631   if (UseCompressedOops) {
3632     assert(!dst.uses(src), "not enough registers");
3633     encode_heap_oop(src);
3634     strw(src, dst);
3635   } else
3636     str(src, dst);
3637 }
3638 
3639 // Used for storing NULLs.
3640 void MacroAssembler::store_heap_oop_null(Address dst) {
3641   if (UseCompressedOops) {
3642     strw(zr, dst);
3643   } else
3644     str(zr, dst);
3645 }
3646 
3647 #if INCLUDE_ALL_GCS
3648 void MacroAssembler::g1_write_barrier_pre(Register obj,
3649                                           Register pre_val,
3650                                           Register thread,
3651                                           Register tmp,
3652                                           bool tosca_live,
3653                                           bool expand_call) {
3654   // If expand_call is true then we expand the call_VM_leaf macro
3655   // directly to skip generating the check by
3656   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
3657 
3658   assert(thread == rthread, "must be");
3659 
3660   Label done;
3661   Label runtime;
3662 
3663   assert(pre_val != noreg, "check this code");
3664 
3665   if (obj != noreg)
3666     assert_different_registers(obj, pre_val, tmp);
3667 
3668   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3669                                        SATBMarkQueue::byte_offset_of_active()));
3670   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3671                                        SATBMarkQueue::byte_offset_of_index()));
3672   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3673                                        SATBMarkQueue::byte_offset_of_buf()));
3674 
3675 
3676   // Is marking active?
3677   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
3678     ldrw(tmp, in_progress);
3679   } else {
3680     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
3681     ldrb(tmp, in_progress);
3682   }
3683   cbzw(tmp, done);
3684 
3685   // Do we need to load the previous value?
3686   if (obj != noreg) {
3687     load_heap_oop(pre_val, Address(obj, 0));
3688   }
3689 
3690   // Is the previous value null?
3691   cbz(pre_val, done);
3692 
3693   // Can we store original value in the thread's buffer?
3694   // Is index == 0?
3695   // (The index field is typed as size_t.)
3696 
3697   ldr(tmp, index);                      // tmp := *index_adr
3698   cbz(tmp, runtime);                    // tmp == 0?
3699                                         // If yes, goto runtime
3700 
3701   sub(tmp, tmp, wordSize);              // tmp := tmp - wordSize
3702   str(tmp, index);                      // *index_adr := tmp
3703   ldr(rscratch1, buffer);
3704   add(tmp, tmp, rscratch1);             // tmp := tmp + *buffer_adr
3705 
3706   // Record the previous value
3707   str(pre_val, Address(tmp, 0));
3708   b(done);
3709 
3710   bind(runtime);
3711   // save the live input values
3712   push(r0->bit(tosca_live) | obj->bit(obj != noreg) | pre_val->bit(true), sp);
3713 
3714   // Calling the runtime using the regular call_VM_leaf mechanism generates
3715   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
3716   // that checks that the *(rfp+frame::interpreter_frame_last_sp) == NULL.
3717   //
3718   // If we care generating the pre-barrier without a frame (e.g. in the
3719   // intrinsified Reference.get() routine) then ebp might be pointing to
3720   // the caller frame and so this check will most likely fail at runtime.
3721   //
3722   // Expanding the call directly bypasses the generation of the check.
3723   // So when we do not have have a full interpreter frame on the stack
3724   // expand_call should be passed true.
3725 
3726   if (expand_call) {
3727     assert(pre_val != c_rarg1, "smashed arg");
3728     pass_arg1(this, thread);
3729     pass_arg0(this, pre_val);
3730     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
3731   } else {
3732     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
3733   }
3734 
3735   pop(r0->bit(tosca_live) | obj->bit(obj != noreg) | pre_val->bit(true), sp);
3736 
3737   bind(done);
3738 }
3739 
3740 void MacroAssembler::g1_write_barrier_post(Register store_addr,
3741                                            Register new_val,
3742                                            Register thread,
3743                                            Register tmp,
3744                                            Register tmp2) {
3745   assert(thread == rthread, "must be");
3746 
3747   if (UseShenandoahGC) {
3748     // No need for this in Shenandoah.
3749     return;
3750   }
3751 
3752   assert(UseG1GC, "expect G1 GC");
3753 
3754   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
3755                                        DirtyCardQueue::byte_offset_of_index()));
3756   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
3757                                        DirtyCardQueue::byte_offset_of_buf()));
3758 
3759   BarrierSet* bs = Universe::heap()->barrier_set();
3760   CardTableModRefBS* ct = (CardTableModRefBS*)bs;
3761   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3762 
3763   Label done;
3764   Label runtime;
3765 
3766   // Does store cross heap regions?
3767 
3768   eor(tmp, store_addr, new_val);
3769   lsr(tmp, tmp, HeapRegion::LogOfHRGrainBytes);
3770   cbz(tmp, done);
3771 
3772   // crosses regions, storing NULL?
3773 
3774   cbz(new_val, done);
3775 
3776   // storing region crossing non-NULL, is card already dirty?
3777 
3778   ExternalAddress cardtable((address) ct->byte_map_base);
3779   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3780   const Register card_addr = tmp;
3781 
3782   lsr(card_addr, store_addr, CardTableModRefBS::card_shift);
3783 
3784   // get the address of the card
3785   load_byte_map_base(tmp2);
3786   add(card_addr, card_addr, tmp2);
3787   ldrb(tmp2, Address(card_addr));
3788   cmpw(tmp2, (int)G1SATBCardTableModRefBS::g1_young_card_val());
3789   br(Assembler::EQ, done);
3790 
3791   assert((int)CardTableModRefBS::dirty_card_val() == 0, "must be 0");
3792 
3793   membar(Assembler::StoreLoad);
3794 
3795   ldrb(tmp2, Address(card_addr));
3796   cbzw(tmp2, done);
3797 
3798   // storing a region crossing, non-NULL oop, card is clean.
3799   // dirty card and log.
3800 
3801   strb(zr, Address(card_addr));
3802 
3803   ldr(rscratch1, queue_index);
3804   cbz(rscratch1, runtime);
3805   sub(rscratch1, rscratch1, wordSize);
3806   str(rscratch1, queue_index);
3807 
3808   ldr(tmp2, buffer);
3809   str(card_addr, Address(tmp2, rscratch1));
3810   b(done);
3811 
3812   bind(runtime);
3813   // save the live input values
3814   push(store_addr->bit(true) | new_val->bit(true), sp);
3815   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
3816   pop(store_addr->bit(true) | new_val->bit(true), sp);
3817 
3818   bind(done);
3819 }
3820 
3821 void MacroAssembler::shenandoah_write_barrier(Register dst) {
3822   assert(UseShenandoahGC, "must only be called with Shenandoah GC active");
3823   assert(dst != rscratch1, "need rscratch1");
3824   assert(dst != rscratch2, "need rscratch2");
3825 
3826   Label done;
3827 
3828   // Check for evacuation-in-progress
3829   Address evacuation_in_progress = Address(rthread, in_bytes(JavaThread::evacuation_in_progress_offset()));
3830   ldrb(rscratch1, evacuation_in_progress);
3831   membar(Assembler::LoadLoad);
3832 
3833   // The read-barrier.
3834   ldr(dst, Address(dst, BrooksPointer::byte_offset()));
3835 
3836   // Evac-check ...
3837   cbzw(rscratch1, done);
3838 
3839   RegSet to_save = RegSet::of(r0);
3840   if (dst != r0) {
3841     push(to_save, sp);
3842     mov(r0, dst);
3843   }
3844 
3845   assert(StubRoutines::aarch64::shenandoah_wb() != NULL, "need write barrier stub");
3846   far_call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::aarch64::shenandoah_wb())));
3847 
3848   if (dst != r0) {
3849     mov(dst, r0);
3850     pop(to_save, sp);
3851   }
3852   block_comment("} Shenandoah write barrier");
3853 
3854   bind(done);
3855 }
3856 
3857 #endif // INCLUDE_ALL_GCS
3858 
3859 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
3860   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
3861   int index = oop_recorder()->allocate_metadata_index(obj);
3862   RelocationHolder rspec = metadata_Relocation::spec(index);
3863   return Address((address)obj, rspec);
3864 }
3865 
3866 // Move an oop into a register.  immediate is true if we want
3867 // immediate instrcutions, i.e. we are not going to patch this
3868 // instruction while the code is being executed by another thread.  In
3869 // that case we can use move immediates rather than the constant pool.
3870 void MacroAssembler::movoop(Register dst, jobject obj, bool immediate) {
3871   int oop_index;
3872   if (obj == NULL) {
3873     oop_index = oop_recorder()->allocate_oop_index(obj);
3874   } else {
3875     oop_index = oop_recorder()->find_index(obj);
3876     assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "should be real oop");
3877   }
3878   RelocationHolder rspec = oop_Relocation::spec(oop_index);
3879   if (! immediate) {
3880     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
3881     ldr_constant(dst, Address(dummy, rspec));
3882   } else
3883     mov(dst, Address((address)obj, rspec));
3884 }
3885 
3886 // Move a metadata address into a register.
3887 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
3888   int oop_index;
3889   if (obj == NULL) {
3890     oop_index = oop_recorder()->allocate_metadata_index(obj);
3891   } else {
3892     oop_index = oop_recorder()->find_index(obj);
3893   }
3894   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
3895   mov(dst, Address((address)obj, rspec));
3896 }
3897 
3898 Address MacroAssembler::constant_oop_address(jobject obj) {
3899   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
3900   assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "not an oop");
3901   int oop_index = oop_recorder()->find_index(obj);
3902   return Address((address)obj, oop_Relocation::spec(oop_index));
3903 }
3904 
3905 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
3906 void MacroAssembler::tlab_allocate(Register obj,
3907                                    Register var_size_in_bytes,
3908                                    int con_size_in_bytes,
3909                                    Register t1,
3910                                    Register t2,
3911                                    Label& slow_case) {
3912   assert_different_registers(obj, t2);
3913   assert_different_registers(obj, var_size_in_bytes);
3914   Register end = t2;
3915 
3916   // verify_tlab();
3917 
3918   int oop_extra_words = Universe::heap()->oop_extra_words();
3919 
3920   ldr(obj, Address(rthread, JavaThread::tlab_top_offset()));
3921   if (var_size_in_bytes == noreg) {
3922     lea(end, Address(obj, con_size_in_bytes + oop_extra_words * HeapWordSize));
3923   } else {
3924     if (oop_extra_words > 0) {
3925       add(var_size_in_bytes, var_size_in_bytes, oop_extra_words * HeapWordSize);
3926     }
3927     lea(end, Address(obj, var_size_in_bytes));
3928   }
3929   ldr(rscratch1, Address(rthread, JavaThread::tlab_end_offset()));
3930   cmp(end, rscratch1);
3931   br(Assembler::HI, slow_case);
3932 
3933   // update the tlab top pointer
3934   str(end, Address(rthread, JavaThread::tlab_top_offset()));
3935 
3936   Universe::heap()->compile_prepare_oop(this, obj);
3937 
3938   // recover var_size_in_bytes if necessary
3939   if (var_size_in_bytes == end) {
3940     sub(var_size_in_bytes, var_size_in_bytes, obj);
3941   }
3942   // verify_tlab();
3943 }
3944 
3945 // Preserves r19, and r3.
3946 Register MacroAssembler::tlab_refill(Label& retry,
3947                                      Label& try_eden,
3948                                      Label& slow_case) {
3949   Register top = r0;
3950   Register t1  = r2;
3951   Register t2  = r4;
3952   assert_different_registers(top, rthread, t1, t2, /* preserve: */ r19, r3);
3953   Label do_refill, discard_tlab;
3954 
3955   if (!Universe::heap()->supports_inline_contig_alloc()) {
3956     // No allocation in the shared eden.
3957     b(slow_case);
3958   }
3959 
3960   ldr(top, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3961   ldr(t1,  Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
3962 
3963   // calculate amount of free space
3964   sub(t1, t1, top);
3965   lsr(t1, t1, LogHeapWordSize);
3966 
3967   // Retain tlab and allocate object in shared space if
3968   // the amount free in the tlab is too large to discard.
3969 
3970   ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3971   cmp(t1, rscratch1);
3972   br(Assembler::LE, discard_tlab);
3973 
3974   // Retain
3975   // ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3976   mov(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
3977   add(rscratch1, rscratch1, t2);
3978   str(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3979 
3980   if (TLABStats) {
3981     // increment number of slow_allocations
3982     addmw(Address(rthread, in_bytes(JavaThread::tlab_slow_allocations_offset())),
3983          1, rscratch1);
3984   }
3985   b(try_eden);
3986 
3987   bind(discard_tlab);
3988   if (TLABStats) {
3989     // increment number of refills
3990     addmw(Address(rthread, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1,
3991          rscratch1);
3992     // accumulate wastage -- t1 is amount free in tlab
3993     addmw(Address(rthread, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1,
3994          rscratch1);
3995   }
3996 
3997   // if tlab is currently allocated (top or end != null) then
3998   // fill [top, end + alignment_reserve) with array object
3999   cbz(top, do_refill);
4000 
4001   // set up the mark word
4002   mov(rscratch1, (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
4003   str(rscratch1, Address(top, oopDesc::mark_offset_in_bytes()));
4004   // set the length to the remaining space
4005   sub(t1, t1, typeArrayOopDesc::header_size(T_INT));
4006   add(t1, t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
4007   lsl(t1, t1, log2_intptr(HeapWordSize/sizeof(jint)));
4008   strw(t1, Address(top, arrayOopDesc::length_offset_in_bytes()));
4009   // set klass to intArrayKlass
4010   {
4011     unsigned long offset;
4012     // dubious reloc why not an oop reloc?
4013     adrp(rscratch1, ExternalAddress((address)Universe::intArrayKlassObj_addr()),
4014          offset);
4015     ldr(t1, Address(rscratch1, offset));
4016   }
4017   // store klass last.  concurrent gcs assumes klass length is valid if
4018   // klass field is not null.
4019   store_klass(top, t1);
4020 
4021   mov(t1, top);
4022   ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
4023   sub(t1, t1, rscratch1);
4024   incr_allocated_bytes(rthread, t1, 0, rscratch1);
4025 
4026   // refill the tlab with an eden allocation
4027   bind(do_refill);
4028   ldr(t1, Address(rthread, in_bytes(JavaThread::tlab_size_offset())));
4029   lsl(t1, t1, LogHeapWordSize);
4030   // allocate new tlab, address returned in top
4031   eden_allocate(top, t1, 0, t2, slow_case);
4032 
4033   // Check that t1 was preserved in eden_allocate.
4034 #ifdef ASSERT
4035   if (UseTLAB) {
4036     Label ok;
4037     Register tsize = r4;
4038     assert_different_registers(tsize, rthread, t1);
4039     str(tsize, Address(pre(sp, -16)));
4040     ldr(tsize, Address(rthread, in_bytes(JavaThread::tlab_size_offset())));
4041     lsl(tsize, tsize, LogHeapWordSize);
4042     cmp(t1, tsize);
4043     br(Assembler::EQ, ok);
4044     STOP("assert(t1 != tlab size)");
4045     should_not_reach_here();
4046 
4047     bind(ok);
4048     ldr(tsize, Address(post(sp, 16)));
4049   }
4050 #endif
4051   str(top, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
4052   str(top, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4053   add(top, top, t1);
4054   sub(top, top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
4055   str(top, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
4056   verify_tlab();
4057   b(retry);
4058 
4059   return rthread; // for use by caller
4060 }
4061 
4062 // Defines obj, preserves var_size_in_bytes
4063 void MacroAssembler::eden_allocate(Register obj,
4064                                    Register var_size_in_bytes,
4065                                    int con_size_in_bytes,
4066                                    Register t1,
4067                                    Label& slow_case) {
4068   assert_different_registers(obj, var_size_in_bytes, t1);
4069   if (!Universe::heap()->supports_inline_contig_alloc()) {
4070     b(slow_case);
4071   } else {
4072     Register end = t1;
4073     Register heap_end = rscratch2;
4074     Label retry;
4075     bind(retry);
4076     {
4077       unsigned long offset;
4078       adrp(rscratch1, ExternalAddress((address) Universe::heap()->end_addr()), offset);
4079       ldr(heap_end, Address(rscratch1, offset));
4080     }
4081 
4082     ExternalAddress heap_top((address) Universe::heap()->top_addr());
4083 
4084     // Get the current top of the heap
4085     {
4086       unsigned long offset;
4087       adrp(rscratch1, heap_top, offset);
4088       // Use add() here after ARDP, rather than lea().
4089       // lea() does not generate anything if its offset is zero.
4090       // However, relocs expect to find either an ADD or a load/store
4091       // insn after an ADRP.  add() always generates an ADD insn, even
4092       // for add(Rn, Rn, 0).
4093       add(rscratch1, rscratch1, offset);
4094       ldaxr(obj, rscratch1);
4095     }
4096 
4097     // Adjust it my the size of our new object
4098     if (var_size_in_bytes == noreg) {
4099       lea(end, Address(obj, con_size_in_bytes));
4100     } else {
4101       lea(end, Address(obj, var_size_in_bytes));
4102     }
4103 
4104     // if end < obj then we wrapped around high memory
4105     cmp(end, obj);
4106     br(Assembler::LO, slow_case);
4107 
4108     cmp(end, heap_end);
4109     br(Assembler::HI, slow_case);
4110 
4111     // If heap_top hasn't been changed by some other thread, update it.
4112     stlxr(rscratch2, end, rscratch1);
4113     cbnzw(rscratch2, retry);
4114   }
4115 }
4116 
4117 void MacroAssembler::verify_tlab() {
4118 #ifdef ASSERT
4119   if (UseTLAB && VerifyOops) {
4120     Label next, ok;
4121 
4122     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
4123 
4124     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4125     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
4126     cmp(rscratch2, rscratch1);
4127     br(Assembler::HS, next);
4128     STOP("assert(top >= start)");
4129     should_not_reach_here();
4130 
4131     bind(next);
4132     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
4133     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4134     cmp(rscratch2, rscratch1);
4135     br(Assembler::HS, ok);
4136     STOP("assert(top <= end)");
4137     should_not_reach_here();
4138 
4139     bind(ok);
4140     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
4141   }
4142 #endif
4143 }
4144 
4145 // Writes to stack successive pages until offset reached to check for
4146 // stack overflow + shadow pages.  This clobbers tmp.
4147 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
4148   assert_different_registers(tmp, size, rscratch1);
4149   mov(tmp, sp);
4150   // Bang stack for total size given plus shadow page size.
4151   // Bang one page at a time because large size can bang beyond yellow and
4152   // red zones.
4153   Label loop;
4154   mov(rscratch1, os::vm_page_size());
4155   bind(loop);
4156   lea(tmp, Address(tmp, -os::vm_page_size()));
4157   subsw(size, size, rscratch1);
4158   str(size, Address(tmp));
4159   br(Assembler::GT, loop);
4160 
4161   // Bang down shadow pages too.
4162   // At this point, (tmp-0) is the last address touched, so don't
4163   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
4164   // was post-decremented.)  Skip this address by starting at i=1, and
4165   // touch a few more pages below.  N.B.  It is important to touch all
4166   // the way down to and including i=StackShadowPages.
4167   for (int i = 0; i < (int)(JavaThread::stack_shadow_zone_size() / os::vm_page_size()) - 1; i++) {
4168     // this could be any sized move but this is can be a debugging crumb
4169     // so the bigger the better.
4170     lea(tmp, Address(tmp, -os::vm_page_size()));
4171     str(size, Address(tmp));
4172   }
4173 }
4174 
4175 
4176 address MacroAssembler::read_polling_page(Register r, address page, relocInfo::relocType rtype) {
4177   unsigned long off;
4178   adrp(r, Address(page, rtype), off);
4179   InstructionMark im(this);
4180   code_section()->relocate(inst_mark(), rtype);
4181   ldrw(zr, Address(r, off));
4182   return inst_mark();
4183 }
4184 
4185 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
4186   InstructionMark im(this);
4187   code_section()->relocate(inst_mark(), rtype);
4188   ldrw(zr, Address(r, 0));
4189   return inst_mark();
4190 }
4191 
4192 void MacroAssembler::adrp(Register reg1, const Address &dest, unsigned long &byte_offset) {
4193   relocInfo::relocType rtype = dest.rspec().reloc()->type();
4194   unsigned long low_page = (unsigned long)CodeCache::low_bound() >> 12;
4195   unsigned long high_page = (unsigned long)(CodeCache::high_bound()-1) >> 12;
4196   unsigned long dest_page = (unsigned long)dest.target() >> 12;
4197   long offset_low = dest_page - low_page;
4198   long offset_high = dest_page - high_page;
4199 
4200   assert(is_valid_AArch64_address(dest.target()), "bad address");
4201   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
4202 
4203   InstructionMark im(this);
4204   code_section()->relocate(inst_mark(), dest.rspec());
4205   // 8143067: Ensure that the adrp can reach the dest from anywhere within
4206   // the code cache so that if it is relocated we know it will still reach
4207   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
4208     _adrp(reg1, dest.target());
4209   } else {
4210     unsigned long target = (unsigned long)dest.target();
4211     unsigned long adrp_target
4212       = (target & 0xffffffffUL) | ((unsigned long)pc() & 0xffff00000000UL);
4213 
4214     _adrp(reg1, (address)adrp_target);
4215     movk(reg1, target >> 32, 32);
4216   }
4217   byte_offset = (unsigned long)dest.target() & 0xfff;
4218 }
4219 
4220 void MacroAssembler::load_byte_map_base(Register reg) {
4221   jbyte *byte_map_base =
4222     ((CardTableModRefBS*)(Universe::heap()->barrier_set()))->byte_map_base;
4223 
4224   if (is_valid_AArch64_address((address)byte_map_base)) {
4225     // Strictly speaking the byte_map_base isn't an address at all,
4226     // and it might even be negative.
4227     unsigned long offset;
4228     adrp(reg, ExternalAddress((address)byte_map_base), offset);
4229     // We expect offset to be zero with most collectors.
4230     if (offset != 0) {
4231       add(reg, reg, offset);
4232     }
4233   } else {
4234     mov(reg, (uint64_t)byte_map_base);
4235   }
4236 }
4237 
4238 void MacroAssembler::build_frame(int framesize) {
4239   assert(framesize > 0, "framesize must be > 0");
4240   if (framesize < ((1 << 9) + 2 * wordSize)) {
4241     sub(sp, sp, framesize);
4242     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4243     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
4244   } else {
4245     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
4246     if (PreserveFramePointer) mov(rfp, sp);
4247     if (framesize < ((1 << 12) + 2 * wordSize))
4248       sub(sp, sp, framesize - 2 * wordSize);
4249     else {
4250       mov(rscratch1, framesize - 2 * wordSize);
4251       sub(sp, sp, rscratch1);
4252     }
4253   }
4254 }
4255 
4256 void MacroAssembler::remove_frame(int framesize) {
4257   assert(framesize > 0, "framesize must be > 0");
4258   if (framesize < ((1 << 9) + 2 * wordSize)) {
4259     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4260     add(sp, sp, framesize);
4261   } else {
4262     if (framesize < ((1 << 12) + 2 * wordSize))
4263       add(sp, sp, framesize - 2 * wordSize);
4264     else {
4265       mov(rscratch1, framesize - 2 * wordSize);
4266       add(sp, sp, rscratch1);
4267     }
4268     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
4269   }
4270 }
4271 
4272 typedef void (MacroAssembler::* chr_insn)(Register Rt, const Address &adr);
4273 
4274 // Search for str1 in str2 and return index or -1
4275 void MacroAssembler::string_indexof(Register str2, Register str1,
4276                                     Register cnt2, Register cnt1,
4277                                     Register tmp1, Register tmp2,
4278                                     Register tmp3, Register tmp4,
4279                                     int icnt1, Register result, int ae) {
4280   Label BM, LINEARSEARCH, DONE, NOMATCH, MATCH;
4281 
4282   Register ch1 = rscratch1;
4283   Register ch2 = rscratch2;
4284   Register cnt1tmp = tmp1;
4285   Register cnt2tmp = tmp2;
4286   Register cnt1_neg = cnt1;
4287   Register cnt2_neg = cnt2;
4288   Register result_tmp = tmp4;
4289 
4290   bool isL = ae == StrIntrinsicNode::LL;
4291 
4292   bool str1_isL = ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL;
4293   bool str2_isL = ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::LU;
4294   int str1_chr_shift = str1_isL ? 0:1;
4295   int str2_chr_shift = str2_isL ? 0:1;
4296   int str1_chr_size = str1_isL ? 1:2;
4297   int str2_chr_size = str2_isL ? 1:2;
4298   chr_insn str1_load_1chr = str1_isL ? (chr_insn)&MacroAssembler::ldrb :
4299                                       (chr_insn)&MacroAssembler::ldrh;
4300   chr_insn str2_load_1chr = str2_isL ? (chr_insn)&MacroAssembler::ldrb :
4301                                       (chr_insn)&MacroAssembler::ldrh;
4302   chr_insn load_2chr = isL ? (chr_insn)&MacroAssembler::ldrh : (chr_insn)&MacroAssembler::ldrw;
4303   chr_insn load_4chr = isL ? (chr_insn)&MacroAssembler::ldrw : (chr_insn)&MacroAssembler::ldr;
4304 
4305   // Note, inline_string_indexOf() generates checks:
4306   // if (substr.count > string.count) return -1;
4307   // if (substr.count == 0) return 0;
4308 
4309 // We have two strings, a source string in str2, cnt2 and a pattern string
4310 // in str1, cnt1. Find the 1st occurence of pattern in source or return -1.
4311 
4312 // For larger pattern and source we use a simplified Boyer Moore algorithm.
4313 // With a small pattern and source we use linear scan.
4314 
4315   if (icnt1 == -1) {
4316     cmp(cnt1, 256);             // Use Linear Scan if cnt1 < 8 || cnt1 >= 256
4317     ccmp(cnt1, 8, 0b0000, LO);  // Can't handle skip >= 256 because we use
4318     br(LO, LINEARSEARCH);       // a byte array.
4319     cmp(cnt1, cnt2, LSR, 2);    // Source must be 4 * pattern for BM
4320     br(HS, LINEARSEARCH);
4321   }
4322 
4323 // The Boyer Moore alogorithm is based on the description here:-
4324 //
4325 // http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm
4326 //
4327 // This describes and algorithm with 2 shift rules. The 'Bad Character' rule
4328 // and the 'Good Suffix' rule.
4329 //
4330 // These rules are essentially heuristics for how far we can shift the
4331 // pattern along the search string.
4332 //
4333 // The implementation here uses the 'Bad Character' rule only because of the
4334 // complexity of initialisation for the 'Good Suffix' rule.
4335 //
4336 // This is also known as the Boyer-Moore-Horspool algorithm:-
4337 //
4338 // http://en.wikipedia.org/wiki/Boyer-Moore-Horspool_algorithm
4339 //
4340 // #define ASIZE 128
4341 //
4342 //    int bm(unsigned char *x, int m, unsigned char *y, int n) {
4343 //       int i, j;
4344 //       unsigned c;
4345 //       unsigned char bc[ASIZE];
4346 //
4347 //       /* Preprocessing */
4348 //       for (i = 0; i < ASIZE; ++i)
4349 //          bc[i] = 0;
4350 //       for (i = 0; i < m - 1; ) {
4351 //          c = x[i];
4352 //          ++i;
4353 //          if (c < ASIZE) bc[c] = i;
4354 //       }
4355 //
4356 //       /* Searching */
4357 //       j = 0;
4358 //       while (j <= n - m) {
4359 //          c = y[i+j];
4360 //          if (x[m-1] == c)
4361 //            for (i = m - 2; i >= 0 && x[i] == y[i + j]; --i);
4362 //          if (i < 0) return j;
4363 //          if (c < ASIZE)
4364 //            j = j - bc[y[j+m-1]] + m;
4365 //          else
4366 //            j += 1; // Advance by 1 only if char >= ASIZE
4367 //       }
4368 //    }
4369 
4370   if (icnt1 == -1) {
4371     BIND(BM);
4372 
4373     Label ZLOOP, BCLOOP, BCSKIP, BMLOOPSTR2, BMLOOPSTR1, BMSKIP;
4374     Label BMADV, BMMATCH, BMCHECKEND;
4375 
4376     Register cnt1end = tmp2;
4377     Register str2end = cnt2;
4378     Register skipch = tmp2;
4379 
4380     // Restrict ASIZE to 128 to reduce stack space/initialisation.
4381     // The presence of chars >= ASIZE in the target string does not affect
4382     // performance, but we must be careful not to initialise them in the stack
4383     // array.
4384     // The presence of chars >= ASIZE in the source string may adversely affect
4385     // performance since we can only advance by one when we encounter one.
4386 
4387       stp(zr, zr, pre(sp, -128));
4388       for (int i = 1; i < 8; i++)
4389           stp(zr, zr, Address(sp, i*16));
4390 
4391       mov(cnt1tmp, 0);
4392       sub(cnt1end, cnt1, 1);
4393     BIND(BCLOOP);
4394       (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp, Address::lsl(str1_chr_shift)));
4395       cmp(ch1, 128);
4396       add(cnt1tmp, cnt1tmp, 1);
4397       br(HS, BCSKIP);
4398       strb(cnt1tmp, Address(sp, ch1));
4399     BIND(BCSKIP);
4400       cmp(cnt1tmp, cnt1end);
4401       br(LT, BCLOOP);
4402 
4403       mov(result_tmp, str2);
4404 
4405       sub(cnt2, cnt2, cnt1);
4406       add(str2end, str2, cnt2, LSL, str2_chr_shift);
4407     BIND(BMLOOPSTR2);
4408       sub(cnt1tmp, cnt1, 1);
4409       (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp, Address::lsl(str1_chr_shift)));
4410       (this->*str2_load_1chr)(skipch, Address(str2, cnt1tmp, Address::lsl(str2_chr_shift)));
4411       cmp(ch1, skipch);
4412       br(NE, BMSKIP);
4413       subs(cnt1tmp, cnt1tmp, 1);
4414       br(LT, BMMATCH);
4415     BIND(BMLOOPSTR1);
4416       (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp, Address::lsl(str1_chr_shift)));
4417       (this->*str2_load_1chr)(ch2, Address(str2, cnt1tmp, Address::lsl(str2_chr_shift)));
4418       cmp(ch1, ch2);
4419       br(NE, BMSKIP);
4420       subs(cnt1tmp, cnt1tmp, 1);
4421       br(GE, BMLOOPSTR1);
4422     BIND(BMMATCH);
4423       sub(result, str2, result_tmp);
4424       if (!str2_isL) lsr(result, result, 1);
4425       add(sp, sp, 128);
4426       b(DONE);
4427     BIND(BMADV);
4428       add(str2, str2, str2_chr_size);
4429       b(BMCHECKEND);
4430     BIND(BMSKIP);
4431       cmp(skipch, 128);
4432       br(HS, BMADV);
4433       ldrb(ch2, Address(sp, skipch));
4434       add(str2, str2, cnt1, LSL, str2_chr_shift);
4435       sub(str2, str2, ch2, LSL, str2_chr_shift);
4436     BIND(BMCHECKEND);
4437       cmp(str2, str2end);
4438       br(LE, BMLOOPSTR2);
4439       add(sp, sp, 128);
4440       b(NOMATCH);
4441   }
4442 
4443   BIND(LINEARSEARCH);
4444   {
4445     Label DO1, DO2, DO3;
4446 
4447     Register str2tmp = tmp2;
4448     Register first = tmp3;
4449 
4450     if (icnt1 == -1)
4451     {
4452         Label DOSHORT, FIRST_LOOP, STR2_NEXT, STR1_LOOP, STR1_NEXT;
4453 
4454         cmp(cnt1, str1_isL == str2_isL ? 4 : 2);
4455         br(LT, DOSHORT);
4456 
4457         sub(cnt2, cnt2, cnt1);
4458         mov(result_tmp, cnt2);
4459 
4460         lea(str1, Address(str1, cnt1, Address::lsl(str1_chr_shift)));
4461         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4462         sub(cnt1_neg, zr, cnt1, LSL, str1_chr_shift);
4463         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4464         (this->*str1_load_1chr)(first, Address(str1, cnt1_neg));
4465 
4466       BIND(FIRST_LOOP);
4467         (this->*str2_load_1chr)(ch2, Address(str2, cnt2_neg));
4468         cmp(first, ch2);
4469         br(EQ, STR1_LOOP);
4470       BIND(STR2_NEXT);
4471         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4472         br(LE, FIRST_LOOP);
4473         b(NOMATCH);
4474 
4475       BIND(STR1_LOOP);
4476         adds(cnt1tmp, cnt1_neg, str1_chr_size);
4477         add(cnt2tmp, cnt2_neg, str2_chr_size);
4478         br(GE, MATCH);
4479 
4480       BIND(STR1_NEXT);
4481         (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp));
4482         (this->*str2_load_1chr)(ch2, Address(str2, cnt2tmp));
4483         cmp(ch1, ch2);
4484         br(NE, STR2_NEXT);
4485         adds(cnt1tmp, cnt1tmp, str1_chr_size);
4486         add(cnt2tmp, cnt2tmp, str2_chr_size);
4487         br(LT, STR1_NEXT);
4488         b(MATCH);
4489 
4490       BIND(DOSHORT);
4491       if (str1_isL == str2_isL) {
4492         cmp(cnt1, 2);
4493         br(LT, DO1);
4494         br(GT, DO3);
4495       }
4496     }
4497 
4498     if (icnt1 == 4) {
4499       Label CH1_LOOP;
4500 
4501         (this->*load_4chr)(ch1, str1);
4502         sub(cnt2, cnt2, 4);
4503         mov(result_tmp, cnt2);
4504         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4505         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4506 
4507       BIND(CH1_LOOP);
4508         (this->*load_4chr)(ch2, Address(str2, cnt2_neg));
4509         cmp(ch1, ch2);
4510         br(EQ, MATCH);
4511         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4512         br(LE, CH1_LOOP);
4513         b(NOMATCH);
4514     }
4515 
4516     if ((icnt1 == -1 && str1_isL == str2_isL) || icnt1 == 2) {
4517       Label CH1_LOOP;
4518 
4519       BIND(DO2);
4520         (this->*load_2chr)(ch1, str1);
4521         sub(cnt2, cnt2, 2);
4522         mov(result_tmp, cnt2);
4523         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4524         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4525 
4526       BIND(CH1_LOOP);
4527         (this->*load_2chr)(ch2, Address(str2, cnt2_neg));
4528         cmp(ch1, ch2);
4529         br(EQ, MATCH);
4530         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4531         br(LE, CH1_LOOP);
4532         b(NOMATCH);
4533     }
4534 
4535     if ((icnt1 == -1 && str1_isL == str2_isL) || icnt1 == 3) {
4536       Label FIRST_LOOP, STR2_NEXT, STR1_LOOP;
4537 
4538       BIND(DO3);
4539         (this->*load_2chr)(first, str1);
4540         (this->*str1_load_1chr)(ch1, Address(str1, 2*str1_chr_size));
4541 
4542         sub(cnt2, cnt2, 3);
4543         mov(result_tmp, cnt2);
4544         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4545         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4546 
4547       BIND(FIRST_LOOP);
4548         (this->*load_2chr)(ch2, Address(str2, cnt2_neg));
4549         cmpw(first, ch2);
4550         br(EQ, STR1_LOOP);
4551       BIND(STR2_NEXT);
4552         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4553         br(LE, FIRST_LOOP);
4554         b(NOMATCH);
4555 
4556       BIND(STR1_LOOP);
4557         add(cnt2tmp, cnt2_neg, 2*str2_chr_size);
4558         (this->*str2_load_1chr)(ch2, Address(str2, cnt2tmp));
4559         cmp(ch1, ch2);
4560         br(NE, STR2_NEXT);
4561         b(MATCH);
4562     }
4563 
4564     if (icnt1 == -1 || icnt1 == 1) {
4565       Label CH1_LOOP, HAS_ZERO;
4566       Label DO1_SHORT, DO1_LOOP;
4567 
4568       BIND(DO1);
4569         (this->*str1_load_1chr)(ch1, str1);
4570         cmp(cnt2, 8);
4571         br(LT, DO1_SHORT);
4572 
4573         if (str2_isL) {
4574           if (!str1_isL) {
4575             tst(ch1, 0xff00);
4576             br(NE, NOMATCH);
4577           }
4578           orr(ch1, ch1, ch1, LSL, 8);
4579         }
4580         orr(ch1, ch1, ch1, LSL, 16);
4581         orr(ch1, ch1, ch1, LSL, 32);
4582 
4583         sub(cnt2, cnt2, 8/str2_chr_size);
4584         mov(result_tmp, cnt2);
4585         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4586         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4587 
4588         mov(tmp3, str2_isL ? 0x0101010101010101 : 0x0001000100010001);
4589       BIND(CH1_LOOP);
4590         ldr(ch2, Address(str2, cnt2_neg));
4591         eor(ch2, ch1, ch2);
4592         sub(tmp1, ch2, tmp3);
4593         orr(tmp2, ch2, str2_isL ? 0x7f7f7f7f7f7f7f7f : 0x7fff7fff7fff7fff);
4594         bics(tmp1, tmp1, tmp2);
4595         br(NE, HAS_ZERO);
4596         adds(cnt2_neg, cnt2_neg, 8);
4597         br(LT, CH1_LOOP);
4598 
4599         cmp(cnt2_neg, 8);
4600         mov(cnt2_neg, 0);
4601         br(LT, CH1_LOOP);
4602         b(NOMATCH);
4603 
4604       BIND(HAS_ZERO);
4605         rev(tmp1, tmp1);
4606         clz(tmp1, tmp1);
4607         add(cnt2_neg, cnt2_neg, tmp1, LSR, 3);
4608         b(MATCH);
4609 
4610       BIND(DO1_SHORT);
4611         mov(result_tmp, cnt2);
4612         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4613         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4614       BIND(DO1_LOOP);
4615         (this->*str2_load_1chr)(ch2, Address(str2, cnt2_neg));
4616         cmpw(ch1, ch2);
4617         br(EQ, MATCH);
4618         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4619         br(LT, DO1_LOOP);
4620     }
4621   }
4622   BIND(NOMATCH);
4623     mov(result, -1);
4624     b(DONE);
4625   BIND(MATCH);
4626     add(result, result_tmp, cnt2_neg, ASR, str2_chr_shift);
4627   BIND(DONE);
4628 }
4629 
4630 typedef void (MacroAssembler::* chr_insn)(Register Rt, const Address &adr);
4631 typedef void (MacroAssembler::* uxt_insn)(Register Rd, Register Rn);
4632 
4633 // Compare strings.
4634 void MacroAssembler::string_compare(Register str1, Register str2,
4635                                     Register cnt1, Register cnt2, Register result,
4636                                     Register tmp1,
4637                                     FloatRegister vtmp, FloatRegister vtmpZ, int ae) {
4638   Label LENGTH_DIFF, DONE, SHORT_LOOP, SHORT_STRING,
4639     NEXT_WORD, DIFFERENCE;
4640 
4641   bool isLL = ae == StrIntrinsicNode::LL;
4642   bool isLU = ae == StrIntrinsicNode::LU;
4643   bool isUL = ae == StrIntrinsicNode::UL;
4644 
4645   bool str1_isL = isLL || isLU;
4646   bool str2_isL = isLL || isUL;
4647 
4648   int str1_chr_shift = str1_isL ? 0 : 1;
4649   int str2_chr_shift = str2_isL ? 0 : 1;
4650   int str1_chr_size = str1_isL ? 1 : 2;
4651   int str2_chr_size = str2_isL ? 1 : 2;
4652 
4653   chr_insn str1_load_chr = str1_isL ? (chr_insn)&MacroAssembler::ldrb :
4654                                       (chr_insn)&MacroAssembler::ldrh;
4655   chr_insn str2_load_chr = str2_isL ? (chr_insn)&MacroAssembler::ldrb :
4656                                       (chr_insn)&MacroAssembler::ldrh;
4657   uxt_insn ext_chr = isLL ? (uxt_insn)&MacroAssembler::uxtbw :
4658                             (uxt_insn)&MacroAssembler::uxthw;
4659 
4660   BLOCK_COMMENT("string_compare {");
4661 
4662   // Bizzarely, the counts are passed in bytes, regardless of whether they
4663   // are L or U strings, however the result is always in characters.
4664   if (!str1_isL) asrw(cnt1, cnt1, 1);
4665   if (!str2_isL) asrw(cnt2, cnt2, 1);
4666 
4667   // Compute the minimum of the string lengths and save the difference.
4668   subsw(tmp1, cnt1, cnt2);
4669   cselw(cnt2, cnt1, cnt2, Assembler::LE); // min
4670 
4671   // A very short string
4672   cmpw(cnt2, isLL ? 8:4);
4673   br(Assembler::LT, SHORT_STRING);
4674 
4675   // Check if the strings start at the same location.
4676   cmp(str1, str2);
4677   br(Assembler::EQ, LENGTH_DIFF);
4678 
4679   // Compare longwords
4680   {
4681     subw(cnt2, cnt2, isLL ? 8:4); // The last longword is a special case
4682 
4683     // Move both string pointers to the last longword of their
4684     // strings, negate the remaining count, and convert it to bytes.
4685     lea(str1, Address(str1, cnt2, Address::uxtw(str1_chr_shift)));
4686     lea(str2, Address(str2, cnt2, Address::uxtw(str2_chr_shift)));
4687     if (isLU || isUL) {
4688       sub(cnt1, zr, cnt2, LSL, str1_chr_shift);
4689       eor(vtmpZ, T16B, vtmpZ, vtmpZ);
4690     }
4691     sub(cnt2, zr, cnt2, LSL, str2_chr_shift);
4692 
4693     // Loop, loading longwords and comparing them into rscratch2.
4694     bind(NEXT_WORD);
4695     if (isLU) {
4696       ldrs(vtmp, Address(str1, cnt1));
4697       zip1(vtmp, T8B, vtmp, vtmpZ);
4698       umov(result, vtmp, D, 0);
4699     } else {
4700       ldr(result, Address(str1, isUL ? cnt1:cnt2));
4701     }
4702     if (isUL) {
4703       ldrs(vtmp, Address(str2, cnt2));
4704       zip1(vtmp, T8B, vtmp, vtmpZ);
4705       umov(rscratch1, vtmp, D, 0);
4706     } else {
4707       ldr(rscratch1, Address(str2, cnt2));
4708     }
4709     adds(cnt2, cnt2, isUL ? 4:8);
4710     if (isLU || isUL) add(cnt1, cnt1, isLU ? 4:8);
4711     eor(rscratch2, result, rscratch1);
4712     cbnz(rscratch2, DIFFERENCE);
4713     br(Assembler::LT, NEXT_WORD);
4714 
4715     // Last longword.  In the case where length == 4 we compare the
4716     // same longword twice, but that's still faster than another
4717     // conditional branch.
4718 
4719     if (isLU) {
4720       ldrs(vtmp, Address(str1));
4721       zip1(vtmp, T8B, vtmp, vtmpZ);
4722       umov(result, vtmp, D, 0);
4723     } else {
4724       ldr(result, Address(str1));
4725     }
4726     if (isUL) {
4727       ldrs(vtmp, Address(str2));
4728       zip1(vtmp, T8B, vtmp, vtmpZ);
4729       umov(rscratch1, vtmp, D, 0);
4730     } else {
4731       ldr(rscratch1, Address(str2));
4732     }
4733     eor(rscratch2, result, rscratch1);
4734     cbz(rscratch2, LENGTH_DIFF);
4735 
4736     // Find the first different characters in the longwords and
4737     // compute their difference.
4738     bind(DIFFERENCE);
4739     rev(rscratch2, rscratch2);
4740     clz(rscratch2, rscratch2);
4741     andr(rscratch2, rscratch2, isLL ? -8 : -16);
4742     lsrv(result, result, rscratch2);
4743     (this->*ext_chr)(result, result);
4744     lsrv(rscratch1, rscratch1, rscratch2);
4745     (this->*ext_chr)(rscratch1, rscratch1);
4746     subw(result, result, rscratch1);
4747     b(DONE);
4748   }
4749 
4750   bind(SHORT_STRING);
4751   // Is the minimum length zero?
4752   cbz(cnt2, LENGTH_DIFF);
4753 
4754   bind(SHORT_LOOP);
4755   (this->*str1_load_chr)(result, Address(post(str1, str1_chr_size)));
4756   (this->*str2_load_chr)(cnt1, Address(post(str2, str2_chr_size)));
4757   subw(result, result, cnt1);
4758   cbnz(result, DONE);
4759   sub(cnt2, cnt2, 1);
4760   cbnz(cnt2, SHORT_LOOP);
4761 
4762   // Strings are equal up to min length.  Return the length difference.
4763   bind(LENGTH_DIFF);
4764   mov(result, tmp1);
4765 
4766   // That's it
4767   bind(DONE);
4768 
4769   BLOCK_COMMENT("} string_compare");
4770 }
4771 
4772 // Compare Strings or char/byte arrays.
4773 
4774 // is_string is true iff this is a string comparison.
4775 
4776 // For Strings we're passed the address of the first characters in a1
4777 // and a2 and the length in cnt1.
4778 
4779 // For byte and char arrays we're passed the arrays themselves and we
4780 // have to extract length fields and do null checks here.
4781 
4782 // elem_size is the element size in bytes: either 1 or 2.
4783 
4784 // There are two implementations.  For arrays >= 8 bytes, all
4785 // comparisons (including the final one, which may overlap) are
4786 // performed 8 bytes at a time.  For arrays < 8 bytes, we compare a
4787 // halfword, then a short, and then a byte.
4788 
4789 void MacroAssembler::arrays_equals(Register a1, Register a2,
4790                                    Register result, Register cnt1,
4791                                    int elem_size, bool is_string)
4792 {
4793   Label SAME, DONE, SHORT, NEXT_WORD, ONE;
4794   Register tmp1 = rscratch1;
4795   Register tmp2 = rscratch2;
4796   Register cnt2 = tmp2;  // cnt2 only used in array length compare
4797   int elem_per_word = wordSize/elem_size;
4798   int log_elem_size = exact_log2(elem_size);
4799   int length_offset = arrayOopDesc::length_offset_in_bytes();
4800   int base_offset
4801     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
4802 
4803   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
4804   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
4805 
4806 #ifndef PRODUCT
4807   {
4808     const char kind = (elem_size == 2) ? 'U' : 'L';
4809     char comment[64];
4810     snprintf(comment, sizeof comment, "%s%c%s {",
4811              is_string ? "string_equals" : "array_equals",
4812              kind, "{");
4813     BLOCK_COMMENT(comment);
4814   }
4815 #endif
4816 
4817   mov(result, false);
4818 
4819   if (!is_string) {
4820     // if (a==a2)
4821     //     return true;
4822     eor(rscratch1, a1, a2);
4823     cbz(rscratch1, SAME);
4824     // if (a==null || a2==null)
4825     //     return false;
4826     cbz(a1, DONE);
4827     cbz(a2, DONE);
4828     // if (a1.length != a2.length)
4829     //      return false;
4830     ldrw(cnt1, Address(a1, length_offset));
4831     ldrw(cnt2, Address(a2, length_offset));
4832     eorw(tmp1, cnt1, cnt2);
4833     cbnzw(tmp1, DONE);
4834 
4835     lea(a1, Address(a1, base_offset));
4836     lea(a2, Address(a2, base_offset));
4837   }
4838 
4839   // Check for short strings, i.e. smaller than wordSize.
4840   subs(cnt1, cnt1, elem_per_word);
4841   br(Assembler::LT, SHORT);
4842   // Main 8 byte comparison loop.
4843   bind(NEXT_WORD); {
4844     ldr(tmp1, Address(post(a1, wordSize)));
4845     ldr(tmp2, Address(post(a2, wordSize)));
4846     subs(cnt1, cnt1, elem_per_word);
4847     eor(tmp1, tmp1, tmp2);
4848     cbnz(tmp1, DONE);
4849   } br(GT, NEXT_WORD);
4850   // Last longword.  In the case where length == 4 we compare the
4851   // same longword twice, but that's still faster than another
4852   // conditional branch.
4853   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
4854   // length == 4.
4855   if (log_elem_size > 0)
4856     lsl(cnt1, cnt1, log_elem_size);
4857   ldr(tmp1, Address(a1, cnt1));
4858   ldr(tmp2, Address(a2, cnt1));
4859   eor(tmp1, tmp1, tmp2);
4860   cbnz(tmp1, DONE);
4861   b(SAME);
4862 
4863   bind(SHORT);
4864   Label TAIL03, TAIL01;
4865 
4866   tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
4867   {
4868     ldrw(tmp1, Address(post(a1, 4)));
4869     ldrw(tmp2, Address(post(a2, 4)));
4870     eorw(tmp1, tmp1, tmp2);
4871     cbnzw(tmp1, DONE);
4872   }
4873   bind(TAIL03);
4874   tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
4875   {
4876     ldrh(tmp1, Address(post(a1, 2)));
4877     ldrh(tmp2, Address(post(a2, 2)));
4878     eorw(tmp1, tmp1, tmp2);
4879     cbnzw(tmp1, DONE);
4880   }
4881   bind(TAIL01);
4882   if (elem_size == 1) { // Only needed when comparing byte arrays.
4883     tbz(cnt1, 0, SAME); // 0-1 bytes left.
4884     {
4885       ldrb(tmp1, a1);
4886       ldrb(tmp2, a2);
4887       eorw(tmp1, tmp1, tmp2);
4888       cbnzw(tmp1, DONE);
4889     }
4890   }
4891   // Arrays are equal.
4892   bind(SAME);
4893   mov(result, true);
4894 
4895   // That's it.
4896   bind(DONE);
4897   BLOCK_COMMENT(is_string ? "} string_equals" : "} array_equals");
4898 }
4899 
4900 
4901 // base:     Address of a buffer to be zeroed, 8 bytes aligned.
4902 // cnt:      Count in HeapWords.
4903 // is_large: True when 'cnt' is known to be >= BlockZeroingLowLimit.
4904 void MacroAssembler::zero_words(Register base, Register cnt)
4905 {
4906   if (UseBlockZeroing) {
4907     block_zero(base, cnt);
4908   } else {
4909     fill_words(base, cnt, zr);
4910   }
4911 }
4912 
4913 // r10 = base:   Address of a buffer to be zeroed, 8 bytes aligned.
4914 // cnt:          Immediate count in HeapWords.
4915 // r11 = tmp:    For use as cnt if we need to call out
4916 #define ShortArraySize (18 * BytesPerLong)
4917 void MacroAssembler::zero_words(Register base, u_int64_t cnt)
4918 {
4919   Register tmp = r11;
4920   int i = cnt & 1;  // store any odd word to start
4921   if (i) str(zr, Address(base));
4922 
4923   if (cnt <= ShortArraySize / BytesPerLong) {
4924     for (; i < (int)cnt; i += 2)
4925       stp(zr, zr, Address(base, i * wordSize));
4926   } else if (UseBlockZeroing && cnt >= (u_int64_t)(BlockZeroingLowLimit >> LogBytesPerWord)) {
4927     mov(tmp, cnt);
4928     block_zero(base, tmp, true);
4929   } else {
4930     const int unroll = 4; // Number of stp(zr, zr) instructions we'll unroll
4931     int remainder = cnt % (2 * unroll);
4932     for (; i < remainder; i += 2)
4933       stp(zr, zr, Address(base, i * wordSize));
4934 
4935     Label loop;
4936     Register cnt_reg = rscratch1;
4937     Register loop_base = rscratch2;
4938     cnt = cnt - remainder;
4939     mov(cnt_reg, cnt);
4940     // adjust base and prebias by -2 * wordSize so we can pre-increment
4941     add(loop_base, base, (remainder - 2) * wordSize);
4942     bind(loop);
4943     sub(cnt_reg, cnt_reg, 2 * unroll);
4944     for (i = 1; i < unroll; i++)
4945       stp(zr, zr, Address(loop_base, 2 * i * wordSize));
4946     stp(zr, zr, Address(pre(loop_base, 2 * unroll * wordSize)));
4947     cbnz(cnt_reg, loop);
4948   }
4949 }
4950 
4951 // base:   Address of a buffer to be filled, 8 bytes aligned.
4952 // cnt:    Count in 8-byte unit.
4953 // value:  Value to be filled with.
4954 // base will point to the end of the buffer after filling.
4955 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
4956 {
4957 //  Algorithm:
4958 //
4959 //    scratch1 = cnt & 7;
4960 //    cnt -= scratch1;
4961 //    p += scratch1;
4962 //    switch (scratch1) {
4963 //      do {
4964 //        cnt -= 8;
4965 //          p[-8] = v;
4966 //        case 7:
4967 //          p[-7] = v;
4968 //        case 6:
4969 //          p[-6] = v;
4970 //          // ...
4971 //        case 1:
4972 //          p[-1] = v;
4973 //        case 0:
4974 //          p += 8;
4975 //      } while (cnt);
4976 //    }
4977 
4978   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
4979 
4980   Label fini, skip, entry, loop;
4981   const int unroll = 8; // Number of stp instructions we'll unroll
4982 
4983   cbz(cnt, fini);
4984   tbz(base, 3, skip);
4985   str(value, Address(post(base, 8)));
4986   sub(cnt, cnt, 1);
4987   bind(skip);
4988 
4989   andr(rscratch1, cnt, (unroll-1) * 2);
4990   sub(cnt, cnt, rscratch1);
4991   add(base, base, rscratch1, Assembler::LSL, 3);
4992   adr(rscratch2, entry);
4993   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
4994   br(rscratch2);
4995 
4996   bind(loop);
4997   add(base, base, unroll * 16);
4998   for (int i = -unroll; i < 0; i++)
4999     stp(value, value, Address(base, i * 16));
5000   bind(entry);
5001   subs(cnt, cnt, unroll * 2);
5002   br(Assembler::GE, loop);
5003 
5004   tbz(cnt, 0, fini);
5005   str(value, Address(post(base, 8)));
5006   bind(fini);
5007 }
5008 
5009 // Use DC ZVA to do fast zeroing.
5010 // base:   Address of a buffer to be zeroed, 8 bytes aligned.
5011 // cnt:    Count in HeapWords.
5012 // is_large: True when 'cnt' is known to be >= BlockZeroingLowLimit.
5013 void MacroAssembler::block_zero(Register base, Register cnt, bool is_large)
5014 {
5015   Label small;
5016   Label store_pair, loop_store_pair, done;
5017   Label base_aligned;
5018 
5019   assert_different_registers(base, cnt, rscratch1);
5020   guarantee(base == r10 && cnt == r11, "fix register usage");
5021 
5022   Register tmp = rscratch1;
5023   Register tmp2 = rscratch2;
5024   int zva_length = VM_Version::zva_length();
5025 
5026   // Ensure ZVA length can be divided by 16. This is required by
5027   // the subsequent operations.
5028   assert (zva_length % 16 == 0, "Unexpected ZVA Length");
5029 
5030   if (!is_large) cbz(cnt, done);
5031   tbz(base, 3, base_aligned);
5032   str(zr, Address(post(base, 8)));
5033   sub(cnt, cnt, 1);
5034   bind(base_aligned);
5035 
5036   // Ensure count >= zva_length * 2 so that it still deserves a zva after
5037   // alignment.
5038   if (!is_large || !(BlockZeroingLowLimit >= zva_length * 2)) {
5039     int low_limit = MAX2(zva_length * 2, (int)BlockZeroingLowLimit);
5040     subs(tmp, cnt, low_limit >> 3);
5041     br(Assembler::LT, small);
5042   }
5043 
5044   far_call(StubRoutines::aarch64::get_zero_longs());
5045 
5046   bind(small);
5047 
5048   const int unroll = 8; // Number of stp instructions we'll unroll
5049   Label small_loop, small_table_end;
5050 
5051   andr(tmp, cnt, (unroll-1) * 2);
5052   sub(cnt, cnt, tmp);
5053   add(base, base, tmp, Assembler::LSL, 3);
5054   adr(tmp2, small_table_end);
5055   sub(tmp2, tmp2, tmp, Assembler::LSL, 1);
5056   br(tmp2);
5057 
5058   bind(small_loop);
5059   add(base, base, unroll * 16);
5060   for (int i = -unroll; i < 0; i++)
5061     stp(zr, zr, Address(base, i * 16));
5062   bind(small_table_end);
5063   subs(cnt, cnt, unroll * 2);
5064   br(Assembler::GE, small_loop);
5065 
5066   tbz(cnt, 0, done);
5067   str(zr, Address(post(base, 8)));
5068 
5069   bind(done);
5070 }
5071 
5072 // Intrinsic for sun/nio/cs/ISO_8859_1$Encoder.implEncodeISOArray and
5073 // java/lang/StringUTF16.compress.
5074 void MacroAssembler::encode_iso_array(Register src, Register dst,
5075                       Register len, Register result,
5076                       FloatRegister Vtmp1, FloatRegister Vtmp2,
5077                       FloatRegister Vtmp3, FloatRegister Vtmp4)
5078 {
5079     Label DONE, NEXT_32, LOOP_8, NEXT_8, LOOP_1, NEXT_1;
5080     Register tmp1 = rscratch1;
5081 
5082       mov(result, len); // Save initial len
5083 
5084 #ifndef BUILTIN_SIM
5085       subs(len, len, 32);
5086       br(LT, LOOP_8);
5087 
5088 // The following code uses the SIMD 'uqxtn' and 'uqxtn2' instructions
5089 // to convert chars to bytes. These set the 'QC' bit in the FPSR if
5090 // any char could not fit in a byte, so clear the FPSR so we can test it.
5091       clear_fpsr();
5092 
5093     BIND(NEXT_32);
5094       ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
5095       uqxtn(Vtmp1, T8B, Vtmp1, T8H);  // uqxtn  - write bottom half
5096       uqxtn(Vtmp1, T16B, Vtmp2, T8H); // uqxtn2 - write top half
5097       uqxtn(Vtmp2, T8B, Vtmp3, T8H);
5098       uqxtn(Vtmp2, T16B, Vtmp4, T8H); // uqxtn2
5099       get_fpsr(tmp1);
5100       cbnzw(tmp1, LOOP_8);
5101       st1(Vtmp1, Vtmp2, T16B, post(dst, 32));
5102       subs(len, len, 32);
5103       add(src, src, 64);
5104       br(GE, NEXT_32);
5105 
5106     BIND(LOOP_8);
5107       adds(len, len, 32-8);
5108       br(LT, LOOP_1);
5109       clear_fpsr(); // QC may be set from loop above, clear again
5110     BIND(NEXT_8);
5111       ld1(Vtmp1, T8H, src);
5112       uqxtn(Vtmp1, T8B, Vtmp1, T8H);
5113       get_fpsr(tmp1);
5114       cbnzw(tmp1, LOOP_1);
5115       st1(Vtmp1, T8B, post(dst, 8));
5116       subs(len, len, 8);
5117       add(src, src, 16);
5118       br(GE, NEXT_8);
5119 
5120     BIND(LOOP_1);
5121       adds(len, len, 8);
5122       br(LE, DONE);
5123 #else
5124       cbz(len, DONE);
5125 #endif
5126     BIND(NEXT_1);
5127       ldrh(tmp1, Address(post(src, 2)));
5128       tst(tmp1, 0xff00);
5129       br(NE, DONE);
5130       strb(tmp1, Address(post(dst, 1)));
5131       subs(len, len, 1);
5132       br(GT, NEXT_1);
5133 
5134     BIND(DONE);
5135       sub(result, result, len); // Return index where we stopped
5136                                 // Return len == 0 if we processed all
5137                                 // characters
5138 }
5139 
5140 
5141 // Inflate byte[] array to char[].
5142 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
5143                                         FloatRegister vtmp1, FloatRegister vtmp2, FloatRegister vtmp3,
5144                                         Register tmp4) {
5145   Label big, done;
5146 
5147   assert_different_registers(src, dst, len, tmp4, rscratch1);
5148 
5149   fmovd(vtmp1 , zr);
5150   lsrw(rscratch1, len, 3);
5151 
5152   cbnzw(rscratch1, big);
5153 
5154   // Short string: less than 8 bytes.
5155   {
5156     Label loop, around, tiny;
5157 
5158     subsw(len, len, 4);
5159     andw(len, len, 3);
5160     br(LO, tiny);
5161 
5162     // Use SIMD to do 4 bytes.
5163     ldrs(vtmp2, post(src, 4));
5164     zip1(vtmp3, T8B, vtmp2, vtmp1);
5165     strd(vtmp3, post(dst, 8));
5166 
5167     cbzw(len, done);
5168 
5169     // Do the remaining bytes by steam.
5170     bind(loop);
5171     ldrb(tmp4, post(src, 1));
5172     strh(tmp4, post(dst, 2));
5173     subw(len, len, 1);
5174 
5175     bind(tiny);
5176     cbnz(len, loop);
5177 
5178     bind(around);
5179     b(done);
5180   }
5181 
5182   // Unpack the bytes 8 at a time.
5183   bind(big);
5184   andw(len, len, 7);
5185 
5186   {
5187     Label loop, around;
5188 
5189     bind(loop);
5190     ldrd(vtmp2, post(src, 8));
5191     sub(rscratch1, rscratch1, 1);
5192     zip1(vtmp3, T16B, vtmp2, vtmp1);
5193     st1(vtmp3, T8H, post(dst, 16));
5194     cbnz(rscratch1, loop);
5195 
5196     bind(around);
5197   }
5198 
5199   // Do the tail of up to 8 bytes.
5200   sub(src, src, 8);
5201   add(src, src, len, ext::uxtw, 0);
5202   ldrd(vtmp2, Address(src));
5203   sub(dst, dst, 16);
5204   add(dst, dst, len, ext::uxtw, 1);
5205   zip1(vtmp3, T16B, vtmp2, vtmp1);
5206   st1(vtmp3, T8H, Address(dst));
5207 
5208   bind(done);
5209 }
5210 
5211 // Compress char[] array to byte[].
5212 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
5213                                          FloatRegister tmp1Reg, FloatRegister tmp2Reg,
5214                                          FloatRegister tmp3Reg, FloatRegister tmp4Reg,
5215                                          Register result) {
5216   encode_iso_array(src, dst, len, result,
5217                    tmp1Reg, tmp2Reg, tmp3Reg, tmp4Reg);
5218   cmp(len, zr);
5219   csel(result, result, zr, EQ);
5220 }
5221 
5222 // get_thread() can be called anywhere inside generated code so we
5223 // need to save whatever non-callee save context might get clobbered
5224 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
5225 // the call setup code.
5226 //
5227 // aarch64_get_thread_helper() clobbers only r0, r1, and flags.
5228 //
5229 void MacroAssembler::get_thread(Register dst) {
5230   RegSet saved_regs = RegSet::range(r0, r1) + lr - dst;
5231   push(saved_regs, sp);
5232 
5233   mov(lr, CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper));
5234   blrt(lr, 1, 0, 1);
5235   if (dst != c_rarg0) {
5236     mov(dst, c_rarg0);
5237   }
5238 
5239   pop(saved_regs, sp);
5240 }
5241 
5242 // Shenandoah requires that all objects are evacuated before being
5243 // written to, and that fromspace pointers are not written into
5244 // objects during concurrent marking.  These methods check for that.
5245 
5246 void MacroAssembler::in_heap_check(Register r, Register tmp, Label &nope) {
5247   ShenandoahHeap *h = (ShenandoahHeap *)Universe::heap();
5248 
5249   HeapWord* first_region_bottom = h->first_region_bottom();
5250   HeapWord* last_region_end = first_region_bottom + (ShenandoahHeapRegion::RegionSizeBytes / HeapWordSize) * h->max_regions();
5251 
5252   mov(tmp, (uintptr_t)first_region_bottom);
5253   cmp(r, tmp);
5254   br(Assembler::LO, nope);
5255   mov(tmp, (uintptr_t)last_region_end);
5256   cmp(r, tmp);
5257   br(Assembler::HS, nope);
5258 }
5259 
5260 void MacroAssembler::shenandoah_cset_check(Register obj, Register tmp1, Register tmp2, Label& done) {
5261 
5262   // Test that oop is not in to-space.
5263   lsr(tmp1, obj, ShenandoahHeapRegion::RegionSizeShift);
5264   assert(ShenandoahHeap::in_cset_fast_test_addr() != 0, "sanity");
5265   mov(tmp2, ShenandoahHeap::in_cset_fast_test_addr());
5266   ldrb(tmp2, Address(tmp2, tmp1));
5267   tbz(tmp2, 0, done);
5268 
5269   // Check for cancelled GC.
5270   assert(ShenandoahHeap::cancelled_concgc_addr() != 0, "sanity");
5271   mov(tmp2, ShenandoahHeap::cancelled_concgc_addr());
5272   ldrb(tmp2, Address(tmp2));
5273   cbnz(tmp2, done);
5274 }
5275 
5276 void MacroAssembler::_shenandoah_store_check(Address addr, Register value, const char* msg, const char* file, int line) {
5277   _shenandoah_store_check(addr.base(), value, msg, file, line);
5278 }
5279 
5280 void MacroAssembler::_shenandoah_store_check(Register addr, Register value, const char* msg, const char* file, int line) {
5281 
5282   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
5283   if (addr == r31_sp || addr == sp) return; // Stack-based target
5284 
5285   Register raddr = r8;
5286   Register rval = r9;
5287   Register tmp1 = r10;
5288   Register tmp2 = r11;
5289 
5290   RegSet to_save = RegSet::of(raddr, rval, tmp1, tmp2);
5291 
5292   // Push tmp regs and flags.
5293   push(to_save, sp);
5294   get_nzcv(tmp1);
5295   push(RegSet::of(tmp1), sp);
5296 
5297   mov(rval, value);
5298   mov(raddr, addr);
5299 
5300   Label done;
5301 
5302   // If not in-heap target, skip check.
5303   in_heap_check(raddr, tmp1, done);
5304 
5305   // Test that target oop is not in to-space.
5306   shenandoah_cset_check(raddr, tmp1, tmp2, done);
5307 
5308   // Do value-check only when concurrent mark is in progress.
5309   mov(tmp1, ShenandoahHeap::concurrent_mark_in_progress_addr());
5310   ldrw(tmp1, Address(tmp1));
5311   cbzw(tmp1, done);
5312 
5313   // Null-check value.
5314   cbz(rval, done);
5315 
5316   // Test that value oop is not in to-space.
5317   shenandoah_cset_check(rval, tmp1, tmp2, done);
5318 
5319   // Failure.
5320   // Pop tmp regs and flags.
5321   pop(RegSet::of(tmp1), sp);
5322   set_nzcv(tmp1);
5323   pop(to_save, sp);
5324   const char* b = NULL;
5325   {
5326     ResourceMark rm;
5327     stringStream ss;
5328     ss.print("shenandoah_store_check: %s in file: %s line: %i", msg, file, line);
5329     b = code_string(ss.as_string());
5330   }
5331   // hlt(0);
5332 
5333   stop(b);
5334 
5335   bind(done);
5336   // Pop tmp regs and flags.
5337   pop(RegSet::of(tmp1), sp);
5338   set_nzcv(tmp1);
5339   pop(to_save, sp);
5340 }
5341 
5342 void MacroAssembler::_shenandoah_store_addr_check(Address addr, const char* msg, const char* file, int line) {
5343   _shenandoah_store_addr_check(addr.base(), msg, file, line);
5344 }
5345 
5346 void MacroAssembler::_shenandoah_store_addr_check(Register dst, const char* msg, const char* file, int line) {
5347 
5348   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
5349   if (dst == r31_sp || dst == sp) return; // Stack-based target
5350 
5351   Register addr = r8;
5352   Register tmp1 = r9;
5353   Register tmp2 = r10;
5354 
5355   Label done;
5356   RegSet to_save = RegSet::of(addr, tmp1, tmp2);
5357 
5358   // Push tmp regs and flags.
5359   push(to_save, sp);
5360   get_nzcv(tmp1);
5361   push(RegSet::of(tmp1), sp);
5362 
5363   orr(addr, zr, dst);
5364   // mov(addr, dst);
5365 
5366   // Check null.
5367   cbz(addr, done);
5368 
5369   in_heap_check(addr, tmp1, done);
5370 
5371   shenandoah_cset_check(addr, tmp1, tmp2, done);
5372 
5373   // Fail.
5374   // Pop tmp regs and flags.
5375   pop(RegSet::of(tmp1), sp);
5376   set_nzcv(tmp1);
5377   pop(to_save, sp);
5378   const char* b = NULL;
5379   {
5380     ResourceMark rm;
5381     stringStream ss;
5382     ss.print("shenandoah_store_check: %s in file: %s line: %i", msg, file, line);
5383     b = code_string(ss.as_string());
5384   }
5385   // hlt(0);
5386   stop(b);
5387   // should_not_reach_here();
5388 
5389   bind(done);
5390   // Pop tmp regs and flags.
5391   pop(RegSet::of(tmp1), sp);
5392   set_nzcv(tmp1);
5393   pop(to_save, sp);
5394 
5395 }