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