rev 12409 : 8169177: aarch64: SIGSEGV when "-XX:+ZeroTLAB" is specified along with GC options
Summary: Add zero-initialization to C1 for fast TLAB refills
Reviewed-by: aph, drwhite
Contributed-by: kavitha.natarajan@linaro.org

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








3947   verify_tlab();
3948   b(retry);
3949 
3950   return rthread; // for use by caller






























































3951 }
3952 
3953 // Defines obj, preserves var_size_in_bytes
3954 void MacroAssembler::eden_allocate(Register obj,
3955                                    Register var_size_in_bytes,
3956                                    int con_size_in_bytes,
3957                                    Register t1,
3958                                    Label& slow_case) {
3959   assert_different_registers(obj, var_size_in_bytes, t1);
3960   if (!Universe::heap()->supports_inline_contig_alloc()) {
3961     b(slow_case);
3962   } else {
3963     Register end = t1;
3964     Register heap_end = rscratch2;
3965     Label retry;
3966     bind(retry);
3967     {
3968       unsigned long offset;
3969       adrp(rscratch1, ExternalAddress((address) Universe::heap()->end_addr()), offset);
3970       ldr(heap_end, Address(rscratch1, offset));
3971     }
3972 
3973     ExternalAddress heap_top((address) Universe::heap()->top_addr());
3974 
3975     // Get the current top of the heap
3976     {
3977       unsigned long offset;
3978       adrp(rscratch1, heap_top, offset);
3979       // Use add() here after ARDP, rather than lea().
3980       // lea() does not generate anything if its offset is zero.
3981       // However, relocs expect to find either an ADD or a load/store
3982       // insn after an ADRP.  add() always generates an ADD insn, even
3983       // for add(Rn, Rn, 0).
3984       add(rscratch1, rscratch1, offset);
3985       ldaxr(obj, rscratch1);
3986     }
3987 
3988     // Adjust it my the size of our new object
3989     if (var_size_in_bytes == noreg) {
3990       lea(end, Address(obj, con_size_in_bytes));
3991     } else {
3992       lea(end, Address(obj, var_size_in_bytes));
3993     }
3994 
3995     // if end < obj then we wrapped around high memory
3996     cmp(end, obj);
3997     br(Assembler::LO, slow_case);
3998 
3999     cmp(end, heap_end);
4000     br(Assembler::HI, slow_case);
4001 
4002     // If heap_top hasn't been changed by some other thread, update it.
4003     stlxr(rscratch2, end, rscratch1);
4004     cbnzw(rscratch2, retry);
4005   }
4006 }
4007 
4008 void MacroAssembler::verify_tlab() {
4009 #ifdef ASSERT
4010   if (UseTLAB && VerifyOops) {
4011     Label next, ok;
4012 
4013     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
4014 
4015     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4016     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
4017     cmp(rscratch2, rscratch1);
4018     br(Assembler::HS, next);
4019     STOP("assert(top >= start)");
4020     should_not_reach_here();
4021 
4022     bind(next);
4023     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
4024     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4025     cmp(rscratch2, rscratch1);
4026     br(Assembler::HS, ok);
4027     STOP("assert(top <= end)");
4028     should_not_reach_here();
4029 
4030     bind(ok);
4031     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
4032   }
4033 #endif
4034 }
4035 
4036 // Writes to stack successive pages until offset reached to check for
4037 // stack overflow + shadow pages.  This clobbers tmp.
4038 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
4039   assert_different_registers(tmp, size, rscratch1);
4040   mov(tmp, sp);
4041   // Bang stack for total size given plus shadow page size.
4042   // Bang one page at a time because large size can bang beyond yellow and
4043   // red zones.
4044   Label loop;
4045   mov(rscratch1, os::vm_page_size());
4046   bind(loop);
4047   lea(tmp, Address(tmp, -os::vm_page_size()));
4048   subsw(size, size, rscratch1);
4049   str(size, Address(tmp));
4050   br(Assembler::GT, loop);
4051 
4052   // Bang down shadow pages too.
4053   // At this point, (tmp-0) is the last address touched, so don't
4054   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
4055   // was post-decremented.)  Skip this address by starting at i=1, and
4056   // touch a few more pages below.  N.B.  It is important to touch all
4057   // the way down to and including i=StackShadowPages.
4058   for (int i = 0; i < (int)(JavaThread::stack_shadow_zone_size() / os::vm_page_size()) - 1; i++) {
4059     // this could be any sized move but this is can be a debugging crumb
4060     // so the bigger the better.
4061     lea(tmp, Address(tmp, -os::vm_page_size()));
4062     str(size, Address(tmp));
4063   }
4064 }
4065 
4066 
4067 address MacroAssembler::read_polling_page(Register r, address page, relocInfo::relocType rtype) {
4068   unsigned long off;
4069   adrp(r, Address(page, rtype), off);
4070   InstructionMark im(this);
4071   code_section()->relocate(inst_mark(), rtype);
4072   ldrw(zr, Address(r, off));
4073   return inst_mark();
4074 }
4075 
4076 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
4077   InstructionMark im(this);
4078   code_section()->relocate(inst_mark(), rtype);
4079   ldrw(zr, Address(r, 0));
4080   return inst_mark();
4081 }
4082 
4083 void MacroAssembler::adrp(Register reg1, const Address &dest, unsigned long &byte_offset) {
4084   relocInfo::relocType rtype = dest.rspec().reloc()->type();
4085   unsigned long low_page = (unsigned long)CodeCache::low_bound() >> 12;
4086   unsigned long high_page = (unsigned long)(CodeCache::high_bound()-1) >> 12;
4087   unsigned long dest_page = (unsigned long)dest.target() >> 12;
4088   long offset_low = dest_page - low_page;
4089   long offset_high = dest_page - high_page;
4090 
4091   assert(is_valid_AArch64_address(dest.target()), "bad address");
4092   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
4093 
4094   InstructionMark im(this);
4095   code_section()->relocate(inst_mark(), dest.rspec());
4096   // 8143067: Ensure that the adrp can reach the dest from anywhere within
4097   // the code cache so that if it is relocated we know it will still reach
4098   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
4099     _adrp(reg1, dest.target());
4100   } else {
4101     unsigned long target = (unsigned long)dest.target();
4102     unsigned long adrp_target
4103       = (target & 0xffffffffUL) | ((unsigned long)pc() & 0xffff00000000UL);
4104 
4105     _adrp(reg1, (address)adrp_target);
4106     movk(reg1, target >> 32, 32);
4107   }
4108   byte_offset = (unsigned long)dest.target() & 0xfff;
4109 }
4110 
4111 void MacroAssembler::load_byte_map_base(Register reg) {
4112   jbyte *byte_map_base =
4113     ((CardTableModRefBS*)(Universe::heap()->barrier_set()))->byte_map_base;
4114 
4115   if (is_valid_AArch64_address((address)byte_map_base)) {
4116     // Strictly speaking the byte_map_base isn't an address at all,
4117     // and it might even be negative.
4118     unsigned long offset;
4119     adrp(reg, ExternalAddress((address)byte_map_base), offset);
4120     // We expect offset to be zero with most collectors.
4121     if (offset != 0) {
4122       add(reg, reg, offset);
4123     }
4124   } else {
4125     mov(reg, (uint64_t)byte_map_base);
4126   }
4127 }
4128 
4129 void MacroAssembler::build_frame(int framesize) {
4130   assert(framesize > 0, "framesize must be > 0");
4131   if (framesize < ((1 << 9) + 2 * wordSize)) {
4132     sub(sp, sp, framesize);
4133     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4134     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
4135   } else {
4136     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
4137     if (PreserveFramePointer) mov(rfp, sp);
4138     if (framesize < ((1 << 12) + 2 * wordSize))
4139       sub(sp, sp, framesize - 2 * wordSize);
4140     else {
4141       mov(rscratch1, framesize - 2 * wordSize);
4142       sub(sp, sp, rscratch1);
4143     }
4144   }
4145 }
4146 
4147 void MacroAssembler::remove_frame(int framesize) {
4148   assert(framesize > 0, "framesize must be > 0");
4149   if (framesize < ((1 << 9) + 2 * wordSize)) {
4150     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
4151     add(sp, sp, framesize);
4152   } else {
4153     if (framesize < ((1 << 12) + 2 * wordSize))
4154       add(sp, sp, framesize - 2 * wordSize);
4155     else {
4156       mov(rscratch1, framesize - 2 * wordSize);
4157       add(sp, sp, rscratch1);
4158     }
4159     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
4160   }
4161 }
4162 
4163 typedef void (MacroAssembler::* chr_insn)(Register Rt, const Address &adr);
4164 
4165 // Search for str1 in str2 and return index or -1
4166 void MacroAssembler::string_indexof(Register str2, Register str1,
4167                                     Register cnt2, Register cnt1,
4168                                     Register tmp1, Register tmp2,
4169                                     Register tmp3, Register tmp4,
4170                                     int icnt1, Register result, int ae) {
4171   Label BM, LINEARSEARCH, DONE, NOMATCH, MATCH;
4172 
4173   Register ch1 = rscratch1;
4174   Register ch2 = rscratch2;
4175   Register cnt1tmp = tmp1;
4176   Register cnt2tmp = tmp2;
4177   Register cnt1_neg = cnt1;
4178   Register cnt2_neg = cnt2;
4179   Register result_tmp = tmp4;
4180 
4181   bool isL = ae == StrIntrinsicNode::LL;
4182 
4183   bool str1_isL = ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL;
4184   bool str2_isL = ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::LU;
4185   int str1_chr_shift = str1_isL ? 0:1;
4186   int str2_chr_shift = str2_isL ? 0:1;
4187   int str1_chr_size = str1_isL ? 1:2;
4188   int str2_chr_size = str2_isL ? 1:2;
4189   chr_insn str1_load_1chr = str1_isL ? (chr_insn)&MacroAssembler::ldrb :
4190                                       (chr_insn)&MacroAssembler::ldrh;
4191   chr_insn str2_load_1chr = str2_isL ? (chr_insn)&MacroAssembler::ldrb :
4192                                       (chr_insn)&MacroAssembler::ldrh;
4193   chr_insn load_2chr = isL ? (chr_insn)&MacroAssembler::ldrh : (chr_insn)&MacroAssembler::ldrw;
4194   chr_insn load_4chr = isL ? (chr_insn)&MacroAssembler::ldrw : (chr_insn)&MacroAssembler::ldr;
4195 
4196   // Note, inline_string_indexOf() generates checks:
4197   // if (substr.count > string.count) return -1;
4198   // if (substr.count == 0) return 0;
4199 
4200 // We have two strings, a source string in str2, cnt2 and a pattern string
4201 // in str1, cnt1. Find the 1st occurence of pattern in source or return -1.
4202 
4203 // For larger pattern and source we use a simplified Boyer Moore algorithm.
4204 // With a small pattern and source we use linear scan.
4205 
4206   if (icnt1 == -1) {
4207     cmp(cnt1, 256);             // Use Linear Scan if cnt1 < 8 || cnt1 >= 256
4208     ccmp(cnt1, 8, 0b0000, LO);  // Can't handle skip >= 256 because we use
4209     br(LO, LINEARSEARCH);       // a byte array.
4210     cmp(cnt1, cnt2, LSR, 2);    // Source must be 4 * pattern for BM
4211     br(HS, LINEARSEARCH);
4212   }
4213 
4214 // The Boyer Moore alogorithm is based on the description here:-
4215 //
4216 // http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm
4217 //
4218 // This describes and algorithm with 2 shift rules. The 'Bad Character' rule
4219 // and the 'Good Suffix' rule.
4220 //
4221 // These rules are essentially heuristics for how far we can shift the
4222 // pattern along the search string.
4223 //
4224 // The implementation here uses the 'Bad Character' rule only because of the
4225 // complexity of initialisation for the 'Good Suffix' rule.
4226 //
4227 // This is also known as the Boyer-Moore-Horspool algorithm:-
4228 //
4229 // http://en.wikipedia.org/wiki/Boyer-Moore-Horspool_algorithm
4230 //
4231 // #define ASIZE 128
4232 //
4233 //    int bm(unsigned char *x, int m, unsigned char *y, int n) {
4234 //       int i, j;
4235 //       unsigned c;
4236 //       unsigned char bc[ASIZE];
4237 //
4238 //       /* Preprocessing */
4239 //       for (i = 0; i < ASIZE; ++i)
4240 //          bc[i] = 0;
4241 //       for (i = 0; i < m - 1; ) {
4242 //          c = x[i];
4243 //          ++i;
4244 //          if (c < ASIZE) bc[c] = i;
4245 //       }
4246 //
4247 //       /* Searching */
4248 //       j = 0;
4249 //       while (j <= n - m) {
4250 //          c = y[i+j];
4251 //          if (x[m-1] == c)
4252 //            for (i = m - 2; i >= 0 && x[i] == y[i + j]; --i);
4253 //          if (i < 0) return j;
4254 //          if (c < ASIZE)
4255 //            j = j - bc[y[j+m-1]] + m;
4256 //          else
4257 //            j += 1; // Advance by 1 only if char >= ASIZE
4258 //       }
4259 //    }
4260 
4261   if (icnt1 == -1) {
4262     BIND(BM);
4263 
4264     Label ZLOOP, BCLOOP, BCSKIP, BMLOOPSTR2, BMLOOPSTR1, BMSKIP;
4265     Label BMADV, BMMATCH, BMCHECKEND;
4266 
4267     Register cnt1end = tmp2;
4268     Register str2end = cnt2;
4269     Register skipch = tmp2;
4270 
4271     // Restrict ASIZE to 128 to reduce stack space/initialisation.
4272     // The presence of chars >= ASIZE in the target string does not affect
4273     // performance, but we must be careful not to initialise them in the stack
4274     // array.
4275     // The presence of chars >= ASIZE in the source string may adversely affect
4276     // performance since we can only advance by one when we encounter one.
4277 
4278       stp(zr, zr, pre(sp, -128));
4279       for (int i = 1; i < 8; i++)
4280           stp(zr, zr, Address(sp, i*16));
4281 
4282       mov(cnt1tmp, 0);
4283       sub(cnt1end, cnt1, 1);
4284     BIND(BCLOOP);
4285       (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp, Address::lsl(str1_chr_shift)));
4286       cmp(ch1, 128);
4287       add(cnt1tmp, cnt1tmp, 1);
4288       br(HS, BCSKIP);
4289       strb(cnt1tmp, Address(sp, ch1));
4290     BIND(BCSKIP);
4291       cmp(cnt1tmp, cnt1end);
4292       br(LT, BCLOOP);
4293 
4294       mov(result_tmp, str2);
4295 
4296       sub(cnt2, cnt2, cnt1);
4297       add(str2end, str2, cnt2, LSL, str2_chr_shift);
4298     BIND(BMLOOPSTR2);
4299       sub(cnt1tmp, cnt1, 1);
4300       (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp, Address::lsl(str1_chr_shift)));
4301       (this->*str2_load_1chr)(skipch, Address(str2, cnt1tmp, Address::lsl(str2_chr_shift)));
4302       cmp(ch1, skipch);
4303       br(NE, BMSKIP);
4304       subs(cnt1tmp, cnt1tmp, 1);
4305       br(LT, BMMATCH);
4306     BIND(BMLOOPSTR1);
4307       (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp, Address::lsl(str1_chr_shift)));
4308       (this->*str2_load_1chr)(ch2, Address(str2, cnt1tmp, Address::lsl(str2_chr_shift)));
4309       cmp(ch1, ch2);
4310       br(NE, BMSKIP);
4311       subs(cnt1tmp, cnt1tmp, 1);
4312       br(GE, BMLOOPSTR1);
4313     BIND(BMMATCH);
4314       sub(result, str2, result_tmp);
4315       if (!str2_isL) lsr(result, result, 1);
4316       add(sp, sp, 128);
4317       b(DONE);
4318     BIND(BMADV);
4319       add(str2, str2, str2_chr_size);
4320       b(BMCHECKEND);
4321     BIND(BMSKIP);
4322       cmp(skipch, 128);
4323       br(HS, BMADV);
4324       ldrb(ch2, Address(sp, skipch));
4325       add(str2, str2, cnt1, LSL, str2_chr_shift);
4326       sub(str2, str2, ch2, LSL, str2_chr_shift);
4327     BIND(BMCHECKEND);
4328       cmp(str2, str2end);
4329       br(LE, BMLOOPSTR2);
4330       add(sp, sp, 128);
4331       b(NOMATCH);
4332   }
4333 
4334   BIND(LINEARSEARCH);
4335   {
4336     Label DO1, DO2, DO3;
4337 
4338     Register str2tmp = tmp2;
4339     Register first = tmp3;
4340 
4341     if (icnt1 == -1)
4342     {
4343         Label DOSHORT, FIRST_LOOP, STR2_NEXT, STR1_LOOP, STR1_NEXT;
4344 
4345         cmp(cnt1, str1_isL == str2_isL ? 4 : 2);
4346         br(LT, DOSHORT);
4347 
4348         sub(cnt2, cnt2, cnt1);
4349         mov(result_tmp, cnt2);
4350 
4351         lea(str1, Address(str1, cnt1, Address::lsl(str1_chr_shift)));
4352         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4353         sub(cnt1_neg, zr, cnt1, LSL, str1_chr_shift);
4354         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4355         (this->*str1_load_1chr)(first, Address(str1, cnt1_neg));
4356 
4357       BIND(FIRST_LOOP);
4358         (this->*str2_load_1chr)(ch2, Address(str2, cnt2_neg));
4359         cmp(first, ch2);
4360         br(EQ, STR1_LOOP);
4361       BIND(STR2_NEXT);
4362         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4363         br(LE, FIRST_LOOP);
4364         b(NOMATCH);
4365 
4366       BIND(STR1_LOOP);
4367         adds(cnt1tmp, cnt1_neg, str1_chr_size);
4368         add(cnt2tmp, cnt2_neg, str2_chr_size);
4369         br(GE, MATCH);
4370 
4371       BIND(STR1_NEXT);
4372         (this->*str1_load_1chr)(ch1, Address(str1, cnt1tmp));
4373         (this->*str2_load_1chr)(ch2, Address(str2, cnt2tmp));
4374         cmp(ch1, ch2);
4375         br(NE, STR2_NEXT);
4376         adds(cnt1tmp, cnt1tmp, str1_chr_size);
4377         add(cnt2tmp, cnt2tmp, str2_chr_size);
4378         br(LT, STR1_NEXT);
4379         b(MATCH);
4380 
4381       BIND(DOSHORT);
4382       if (str1_isL == str2_isL) {
4383         cmp(cnt1, 2);
4384         br(LT, DO1);
4385         br(GT, DO3);
4386       }
4387     }
4388 
4389     if (icnt1 == 4) {
4390       Label CH1_LOOP;
4391 
4392         (this->*load_4chr)(ch1, str1);
4393         sub(cnt2, cnt2, 4);
4394         mov(result_tmp, cnt2);
4395         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4396         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4397 
4398       BIND(CH1_LOOP);
4399         (this->*load_4chr)(ch2, Address(str2, cnt2_neg));
4400         cmp(ch1, ch2);
4401         br(EQ, MATCH);
4402         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4403         br(LE, CH1_LOOP);
4404         b(NOMATCH);
4405     }
4406 
4407     if ((icnt1 == -1 && str1_isL == str2_isL) || icnt1 == 2) {
4408       Label CH1_LOOP;
4409 
4410       BIND(DO2);
4411         (this->*load_2chr)(ch1, str1);
4412         sub(cnt2, cnt2, 2);
4413         mov(result_tmp, cnt2);
4414         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4415         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4416 
4417       BIND(CH1_LOOP);
4418         (this->*load_2chr)(ch2, Address(str2, cnt2_neg));
4419         cmp(ch1, ch2);
4420         br(EQ, MATCH);
4421         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4422         br(LE, CH1_LOOP);
4423         b(NOMATCH);
4424     }
4425 
4426     if ((icnt1 == -1 && str1_isL == str2_isL) || icnt1 == 3) {
4427       Label FIRST_LOOP, STR2_NEXT, STR1_LOOP;
4428 
4429       BIND(DO3);
4430         (this->*load_2chr)(first, str1);
4431         (this->*str1_load_1chr)(ch1, Address(str1, 2*str1_chr_size));
4432 
4433         sub(cnt2, cnt2, 3);
4434         mov(result_tmp, cnt2);
4435         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4436         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4437 
4438       BIND(FIRST_LOOP);
4439         (this->*load_2chr)(ch2, Address(str2, cnt2_neg));
4440         cmpw(first, ch2);
4441         br(EQ, STR1_LOOP);
4442       BIND(STR2_NEXT);
4443         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4444         br(LE, FIRST_LOOP);
4445         b(NOMATCH);
4446 
4447       BIND(STR1_LOOP);
4448         add(cnt2tmp, cnt2_neg, 2*str2_chr_size);
4449         (this->*str2_load_1chr)(ch2, Address(str2, cnt2tmp));
4450         cmp(ch1, ch2);
4451         br(NE, STR2_NEXT);
4452         b(MATCH);
4453     }
4454 
4455     if (icnt1 == -1 || icnt1 == 1) {
4456       Label CH1_LOOP, HAS_ZERO;
4457       Label DO1_SHORT, DO1_LOOP;
4458 
4459       BIND(DO1);
4460         (this->*str1_load_1chr)(ch1, str1);
4461         cmp(cnt2, 8);
4462         br(LT, DO1_SHORT);
4463 
4464         if (str2_isL) {
4465           if (!str1_isL) {
4466             tst(ch1, 0xff00);
4467             br(NE, NOMATCH);
4468           }
4469           orr(ch1, ch1, ch1, LSL, 8);
4470         }
4471         orr(ch1, ch1, ch1, LSL, 16);
4472         orr(ch1, ch1, ch1, LSL, 32);
4473 
4474         sub(cnt2, cnt2, 8/str2_chr_size);
4475         mov(result_tmp, cnt2);
4476         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4477         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4478 
4479         mov(tmp3, str2_isL ? 0x0101010101010101 : 0x0001000100010001);
4480       BIND(CH1_LOOP);
4481         ldr(ch2, Address(str2, cnt2_neg));
4482         eor(ch2, ch1, ch2);
4483         sub(tmp1, ch2, tmp3);
4484         orr(tmp2, ch2, str2_isL ? 0x7f7f7f7f7f7f7f7f : 0x7fff7fff7fff7fff);
4485         bics(tmp1, tmp1, tmp2);
4486         br(NE, HAS_ZERO);
4487         adds(cnt2_neg, cnt2_neg, 8);
4488         br(LT, CH1_LOOP);
4489 
4490         cmp(cnt2_neg, 8);
4491         mov(cnt2_neg, 0);
4492         br(LT, CH1_LOOP);
4493         b(NOMATCH);
4494 
4495       BIND(HAS_ZERO);
4496         rev(tmp1, tmp1);
4497         clz(tmp1, tmp1);
4498         add(cnt2_neg, cnt2_neg, tmp1, LSR, 3);
4499         b(MATCH);
4500 
4501       BIND(DO1_SHORT);
4502         mov(result_tmp, cnt2);
4503         lea(str2, Address(str2, cnt2, Address::lsl(str2_chr_shift)));
4504         sub(cnt2_neg, zr, cnt2, LSL, str2_chr_shift);
4505       BIND(DO1_LOOP);
4506         (this->*str2_load_1chr)(ch2, Address(str2, cnt2_neg));
4507         cmpw(ch1, ch2);
4508         br(EQ, MATCH);
4509         adds(cnt2_neg, cnt2_neg, str2_chr_size);
4510         br(LT, DO1_LOOP);
4511     }
4512   }
4513   BIND(NOMATCH);
4514     mov(result, -1);
4515     b(DONE);
4516   BIND(MATCH);
4517     add(result, result_tmp, cnt2_neg, ASR, str2_chr_shift);
4518   BIND(DONE);
4519 }
4520 
4521 typedef void (MacroAssembler::* chr_insn)(Register Rt, const Address &adr);
4522 typedef void (MacroAssembler::* uxt_insn)(Register Rd, Register Rn);
4523 
4524 void MacroAssembler::string_indexof_char(Register str1, Register cnt1,
4525                                          Register ch, Register result,
4526                                          Register tmp1, Register tmp2, Register tmp3)
4527 {
4528   Label CH1_LOOP, HAS_ZERO, DO1_SHORT, DO1_LOOP, MATCH, NOMATCH, DONE;
4529   Register cnt1_neg = cnt1;
4530   Register ch1 = rscratch1;
4531   Register result_tmp = rscratch2;
4532 
4533   cmp(cnt1, 4);
4534   br(LT, DO1_SHORT);
4535 
4536   orr(ch, ch, ch, LSL, 16);
4537   orr(ch, ch, ch, LSL, 32);
4538 
4539   sub(cnt1, cnt1, 4);
4540   mov(result_tmp, cnt1);
4541   lea(str1, Address(str1, cnt1, Address::uxtw(1)));
4542   sub(cnt1_neg, zr, cnt1, LSL, 1);
4543 
4544   mov(tmp3, 0x0001000100010001);
4545 
4546   BIND(CH1_LOOP);
4547     ldr(ch1, Address(str1, cnt1_neg));
4548     eor(ch1, ch, ch1);
4549     sub(tmp1, ch1, tmp3);
4550     orr(tmp2, ch1, 0x7fff7fff7fff7fff);
4551     bics(tmp1, tmp1, tmp2);
4552     br(NE, HAS_ZERO);
4553     adds(cnt1_neg, cnt1_neg, 8);
4554     br(LT, CH1_LOOP);
4555 
4556     cmp(cnt1_neg, 8);
4557     mov(cnt1_neg, 0);
4558     br(LT, CH1_LOOP);
4559     b(NOMATCH);
4560 
4561   BIND(HAS_ZERO);
4562     rev(tmp1, tmp1);
4563     clz(tmp1, tmp1);
4564     add(cnt1_neg, cnt1_neg, tmp1, LSR, 3);
4565     b(MATCH);
4566 
4567   BIND(DO1_SHORT);
4568     mov(result_tmp, cnt1);
4569     lea(str1, Address(str1, cnt1, Address::uxtw(1)));
4570     sub(cnt1_neg, zr, cnt1, LSL, 1);
4571   BIND(DO1_LOOP);
4572     ldrh(ch1, Address(str1, cnt1_neg));
4573     cmpw(ch, ch1);
4574     br(EQ, MATCH);
4575     adds(cnt1_neg, cnt1_neg, 2);
4576     br(LT, DO1_LOOP);
4577   BIND(NOMATCH);
4578     mov(result, -1);
4579     b(DONE);
4580   BIND(MATCH);
4581     add(result, result_tmp, cnt1_neg, ASR, 1);
4582   BIND(DONE);
4583 }
4584 
4585 // Compare strings.
4586 void MacroAssembler::string_compare(Register str1, Register str2,
4587                                     Register cnt1, Register cnt2, Register result,
4588                                     Register tmp1,
4589                                     FloatRegister vtmp, FloatRegister vtmpZ, int ae) {
4590   Label LENGTH_DIFF, DONE, SHORT_LOOP, SHORT_STRING,
4591     NEXT_WORD, DIFFERENCE;
4592 
4593   bool isLL = ae == StrIntrinsicNode::LL;
4594   bool isLU = ae == StrIntrinsicNode::LU;
4595   bool isUL = ae == StrIntrinsicNode::UL;
4596 
4597   bool str1_isL = isLL || isLU;
4598   bool str2_isL = isLL || isUL;
4599 
4600   int str1_chr_shift = str1_isL ? 0 : 1;
4601   int str2_chr_shift = str2_isL ? 0 : 1;
4602   int str1_chr_size = str1_isL ? 1 : 2;
4603   int str2_chr_size = str2_isL ? 1 : 2;
4604 
4605   chr_insn str1_load_chr = str1_isL ? (chr_insn)&MacroAssembler::ldrb :
4606                                       (chr_insn)&MacroAssembler::ldrh;
4607   chr_insn str2_load_chr = str2_isL ? (chr_insn)&MacroAssembler::ldrb :
4608                                       (chr_insn)&MacroAssembler::ldrh;
4609   uxt_insn ext_chr = isLL ? (uxt_insn)&MacroAssembler::uxtbw :
4610                             (uxt_insn)&MacroAssembler::uxthw;
4611 
4612   BLOCK_COMMENT("string_compare {");
4613 
4614   // Bizzarely, the counts are passed in bytes, regardless of whether they
4615   // are L or U strings, however the result is always in characters.
4616   if (!str1_isL) asrw(cnt1, cnt1, 1);
4617   if (!str2_isL) asrw(cnt2, cnt2, 1);
4618 
4619   // Compute the minimum of the string lengths and save the difference.
4620   subsw(tmp1, cnt1, cnt2);
4621   cselw(cnt2, cnt1, cnt2, Assembler::LE); // min
4622 
4623   // A very short string
4624   cmpw(cnt2, isLL ? 8:4);
4625   br(Assembler::LT, SHORT_STRING);
4626 
4627   // Check if the strings start at the same location.
4628   cmp(str1, str2);
4629   br(Assembler::EQ, LENGTH_DIFF);
4630 
4631   // Compare longwords
4632   {
4633     subw(cnt2, cnt2, isLL ? 8:4); // The last longword is a special case
4634 
4635     // Move both string pointers to the last longword of their
4636     // strings, negate the remaining count, and convert it to bytes.
4637     lea(str1, Address(str1, cnt2, Address::uxtw(str1_chr_shift)));
4638     lea(str2, Address(str2, cnt2, Address::uxtw(str2_chr_shift)));
4639     if (isLU || isUL) {
4640       sub(cnt1, zr, cnt2, LSL, str1_chr_shift);
4641       eor(vtmpZ, T16B, vtmpZ, vtmpZ);
4642     }
4643     sub(cnt2, zr, cnt2, LSL, str2_chr_shift);
4644 
4645     // Loop, loading longwords and comparing them into rscratch2.
4646     bind(NEXT_WORD);
4647     if (isLU) {
4648       ldrs(vtmp, Address(str1, cnt1));
4649       zip1(vtmp, T8B, vtmp, vtmpZ);
4650       umov(result, vtmp, D, 0);
4651     } else {
4652       ldr(result, Address(str1, isUL ? cnt1:cnt2));
4653     }
4654     if (isUL) {
4655       ldrs(vtmp, Address(str2, cnt2));
4656       zip1(vtmp, T8B, vtmp, vtmpZ);
4657       umov(rscratch1, vtmp, D, 0);
4658     } else {
4659       ldr(rscratch1, Address(str2, cnt2));
4660     }
4661     adds(cnt2, cnt2, isUL ? 4:8);
4662     if (isLU || isUL) add(cnt1, cnt1, isLU ? 4:8);
4663     eor(rscratch2, result, rscratch1);
4664     cbnz(rscratch2, DIFFERENCE);
4665     br(Assembler::LT, NEXT_WORD);
4666 
4667     // Last longword.  In the case where length == 4 we compare the
4668     // same longword twice, but that's still faster than another
4669     // conditional branch.
4670 
4671     if (isLU) {
4672       ldrs(vtmp, Address(str1));
4673       zip1(vtmp, T8B, vtmp, vtmpZ);
4674       umov(result, vtmp, D, 0);
4675     } else {
4676       ldr(result, Address(str1));
4677     }
4678     if (isUL) {
4679       ldrs(vtmp, Address(str2));
4680       zip1(vtmp, T8B, vtmp, vtmpZ);
4681       umov(rscratch1, vtmp, D, 0);
4682     } else {
4683       ldr(rscratch1, Address(str2));
4684     }
4685     eor(rscratch2, result, rscratch1);
4686     cbz(rscratch2, LENGTH_DIFF);
4687 
4688     // Find the first different characters in the longwords and
4689     // compute their difference.
4690     bind(DIFFERENCE);
4691     rev(rscratch2, rscratch2);
4692     clz(rscratch2, rscratch2);
4693     andr(rscratch2, rscratch2, isLL ? -8 : -16);
4694     lsrv(result, result, rscratch2);
4695     (this->*ext_chr)(result, result);
4696     lsrv(rscratch1, rscratch1, rscratch2);
4697     (this->*ext_chr)(rscratch1, rscratch1);
4698     subw(result, result, rscratch1);
4699     b(DONE);
4700   }
4701 
4702   bind(SHORT_STRING);
4703   // Is the minimum length zero?
4704   cbz(cnt2, LENGTH_DIFF);
4705 
4706   bind(SHORT_LOOP);
4707   (this->*str1_load_chr)(result, Address(post(str1, str1_chr_size)));
4708   (this->*str2_load_chr)(cnt1, Address(post(str2, str2_chr_size)));
4709   subw(result, result, cnt1);
4710   cbnz(result, DONE);
4711   sub(cnt2, cnt2, 1);
4712   cbnz(cnt2, SHORT_LOOP);
4713 
4714   // Strings are equal up to min length.  Return the length difference.
4715   bind(LENGTH_DIFF);
4716   mov(result, tmp1);
4717 
4718   // That's it
4719   bind(DONE);
4720 
4721   BLOCK_COMMENT("} string_compare");
4722 }
4723 
4724 // Compare Strings or char/byte arrays.
4725 
4726 // is_string is true iff this is a string comparison.
4727 
4728 // For Strings we're passed the address of the first characters in a1
4729 // and a2 and the length in cnt1.
4730 
4731 // For byte and char arrays we're passed the arrays themselves and we
4732 // have to extract length fields and do null checks here.
4733 
4734 // elem_size is the element size in bytes: either 1 or 2.
4735 
4736 // There are two implementations.  For arrays >= 8 bytes, all
4737 // comparisons (including the final one, which may overlap) are
4738 // performed 8 bytes at a time.  For arrays < 8 bytes, we compare a
4739 // halfword, then a short, and then a byte.
4740 
4741 void MacroAssembler::arrays_equals(Register a1, Register a2,
4742                                    Register result, Register cnt1,
4743                                    int elem_size, bool is_string)
4744 {
4745   Label SAME, DONE, SHORT, NEXT_WORD, ONE;
4746   Register tmp1 = rscratch1;
4747   Register tmp2 = rscratch2;
4748   Register cnt2 = tmp2;  // cnt2 only used in array length compare
4749   int elem_per_word = wordSize/elem_size;
4750   int log_elem_size = exact_log2(elem_size);
4751   int length_offset = arrayOopDesc::length_offset_in_bytes();
4752   int base_offset
4753     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
4754 
4755   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
4756   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
4757 
4758 #ifndef PRODUCT
4759   {
4760     const char kind = (elem_size == 2) ? 'U' : 'L';
4761     char comment[64];
4762     snprintf(comment, sizeof comment, "%s%c%s {",
4763              is_string ? "string_equals" : "array_equals",
4764              kind, "{");
4765     BLOCK_COMMENT(comment);
4766   }
4767 #endif
4768 
4769   mov(result, false);
4770 
4771   if (!is_string) {
4772     // if (a==a2)
4773     //     return true;
4774     eor(rscratch1, a1, a2);
4775     cbz(rscratch1, SAME);
4776     // if (a==null || a2==null)
4777     //     return false;
4778     cbz(a1, DONE);
4779     cbz(a2, DONE);
4780     // if (a1.length != a2.length)
4781     //      return false;
4782     ldrw(cnt1, Address(a1, length_offset));
4783     ldrw(cnt2, Address(a2, length_offset));
4784     eorw(tmp1, cnt1, cnt2);
4785     cbnzw(tmp1, DONE);
4786 
4787     lea(a1, Address(a1, base_offset));
4788     lea(a2, Address(a2, base_offset));
4789   }
4790 
4791   // Check for short strings, i.e. smaller than wordSize.
4792   subs(cnt1, cnt1, elem_per_word);
4793   br(Assembler::LT, SHORT);
4794   // Main 8 byte comparison loop.
4795   bind(NEXT_WORD); {
4796     ldr(tmp1, Address(post(a1, wordSize)));
4797     ldr(tmp2, Address(post(a2, wordSize)));
4798     subs(cnt1, cnt1, elem_per_word);
4799     eor(tmp1, tmp1, tmp2);
4800     cbnz(tmp1, DONE);
4801   } br(GT, NEXT_WORD);
4802   // Last longword.  In the case where length == 4 we compare the
4803   // same longword twice, but that's still faster than another
4804   // conditional branch.
4805   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
4806   // length == 4.
4807   if (log_elem_size > 0)
4808     lsl(cnt1, cnt1, log_elem_size);
4809   ldr(tmp1, Address(a1, cnt1));
4810   ldr(tmp2, Address(a2, cnt1));
4811   eor(tmp1, tmp1, tmp2);
4812   cbnz(tmp1, DONE);
4813   b(SAME);
4814 
4815   bind(SHORT);
4816   Label TAIL03, TAIL01;
4817 
4818   tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
4819   {
4820     ldrw(tmp1, Address(post(a1, 4)));
4821     ldrw(tmp2, Address(post(a2, 4)));
4822     eorw(tmp1, tmp1, tmp2);
4823     cbnzw(tmp1, DONE);
4824   }
4825   bind(TAIL03);
4826   tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
4827   {
4828     ldrh(tmp1, Address(post(a1, 2)));
4829     ldrh(tmp2, Address(post(a2, 2)));
4830     eorw(tmp1, tmp1, tmp2);
4831     cbnzw(tmp1, DONE);
4832   }
4833   bind(TAIL01);
4834   if (elem_size == 1) { // Only needed when comparing byte arrays.
4835     tbz(cnt1, 0, SAME); // 0-1 bytes left.
4836     {
4837       ldrb(tmp1, a1);
4838       ldrb(tmp2, a2);
4839       eorw(tmp1, tmp1, tmp2);
4840       cbnzw(tmp1, DONE);
4841     }
4842   }
4843   // Arrays are equal.
4844   bind(SAME);
4845   mov(result, true);
4846 
4847   // That's it.
4848   bind(DONE);
4849   BLOCK_COMMENT(is_string ? "} string_equals" : "} array_equals");
4850 }
4851 
4852 
4853 // base:     Address of a buffer to be zeroed, 8 bytes aligned.
4854 // cnt:      Count in HeapWords.
4855 // is_large: True when 'cnt' is known to be >= BlockZeroingLowLimit.
4856 void MacroAssembler::zero_words(Register base, Register cnt)
4857 {
4858   if (UseBlockZeroing) {
4859     block_zero(base, cnt);
4860   } else {
4861     fill_words(base, cnt, zr);
4862   }
4863 }
4864 
4865 // r10 = base:   Address of a buffer to be zeroed, 8 bytes aligned.
4866 // cnt:          Immediate count in HeapWords.
4867 // r11 = tmp:    For use as cnt if we need to call out
4868 #define ShortArraySize (18 * BytesPerLong)
4869 void MacroAssembler::zero_words(Register base, u_int64_t cnt)
4870 {
4871   Register tmp = r11;
4872   int i = cnt & 1;  // store any odd word to start
4873   if (i) str(zr, Address(base));
4874 
4875   if (cnt <= ShortArraySize / BytesPerLong) {
4876     for (; i < (int)cnt; i += 2)
4877       stp(zr, zr, Address(base, i * wordSize));
4878   } else if (UseBlockZeroing && cnt >= (u_int64_t)(BlockZeroingLowLimit >> LogBytesPerWord)) {
4879     mov(tmp, cnt);
4880     block_zero(base, tmp, true);
4881   } else {
4882     const int unroll = 4; // Number of stp(zr, zr) instructions we'll unroll
4883     int remainder = cnt % (2 * unroll);
4884     for (; i < remainder; i += 2)
4885       stp(zr, zr, Address(base, i * wordSize));
4886 
4887     Label loop;
4888     Register cnt_reg = rscratch1;
4889     Register loop_base = rscratch2;
4890     cnt = cnt - remainder;
4891     mov(cnt_reg, cnt);
4892     // adjust base and prebias by -2 * wordSize so we can pre-increment
4893     add(loop_base, base, (remainder - 2) * wordSize);
4894     bind(loop);
4895     sub(cnt_reg, cnt_reg, 2 * unroll);
4896     for (i = 1; i < unroll; i++)
4897       stp(zr, zr, Address(loop_base, 2 * i * wordSize));
4898     stp(zr, zr, Address(pre(loop_base, 2 * unroll * wordSize)));
4899     cbnz(cnt_reg, loop);
4900   }
4901 }
4902 
4903 // base:   Address of a buffer to be filled, 8 bytes aligned.
4904 // cnt:    Count in 8-byte unit.
4905 // value:  Value to be filled with.
4906 // base will point to the end of the buffer after filling.
4907 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
4908 {
4909 //  Algorithm:
4910 //
4911 //    scratch1 = cnt & 7;
4912 //    cnt -= scratch1;
4913 //    p += scratch1;
4914 //    switch (scratch1) {
4915 //      do {
4916 //        cnt -= 8;
4917 //          p[-8] = v;
4918 //        case 7:
4919 //          p[-7] = v;
4920 //        case 6:
4921 //          p[-6] = v;
4922 //          // ...
4923 //        case 1:
4924 //          p[-1] = v;
4925 //        case 0:
4926 //          p += 8;
4927 //      } while (cnt);
4928 //    }
4929 
4930   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
4931 
4932   Label fini, skip, entry, loop;
4933   const int unroll = 8; // Number of stp instructions we'll unroll
4934 
4935   cbz(cnt, fini);
4936   tbz(base, 3, skip);
4937   str(value, Address(post(base, 8)));
4938   sub(cnt, cnt, 1);
4939   bind(skip);
4940 
4941   andr(rscratch1, cnt, (unroll-1) * 2);
4942   sub(cnt, cnt, rscratch1);
4943   add(base, base, rscratch1, Assembler::LSL, 3);
4944   adr(rscratch2, entry);
4945   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
4946   br(rscratch2);
4947 
4948   bind(loop);
4949   add(base, base, unroll * 16);
4950   for (int i = -unroll; i < 0; i++)
4951     stp(value, value, Address(base, i * 16));
4952   bind(entry);
4953   subs(cnt, cnt, unroll * 2);
4954   br(Assembler::GE, loop);
4955 
4956   tbz(cnt, 0, fini);
4957   str(value, Address(post(base, 8)));
4958   bind(fini);
4959 }
4960 
4961 // Use DC ZVA to do fast zeroing.
4962 // base:   Address of a buffer to be zeroed, 8 bytes aligned.
4963 // cnt:    Count in HeapWords.
4964 // is_large: True when 'cnt' is known to be >= BlockZeroingLowLimit.
4965 void MacroAssembler::block_zero(Register base, Register cnt, bool is_large)
4966 {
4967   Label small;
4968   Label store_pair, loop_store_pair, done;
4969   Label base_aligned;
4970 
4971   assert_different_registers(base, cnt, rscratch1);
4972   guarantee(base == r10 && cnt == r11, "fix register usage");
4973 
4974   Register tmp = rscratch1;
4975   Register tmp2 = rscratch2;
4976   int zva_length = VM_Version::zva_length();
4977 
4978   // Ensure ZVA length can be divided by 16. This is required by
4979   // the subsequent operations.
4980   assert (zva_length % 16 == 0, "Unexpected ZVA Length");
4981 
4982   if (!is_large) cbz(cnt, done);
4983   tbz(base, 3, base_aligned);
4984   str(zr, Address(post(base, 8)));
4985   sub(cnt, cnt, 1);
4986   bind(base_aligned);
4987 
4988   // Ensure count >= zva_length * 2 so that it still deserves a zva after
4989   // alignment.
4990   if (!is_large || !(BlockZeroingLowLimit >= zva_length * 2)) {
4991     int low_limit = MAX2(zva_length * 2, (int)BlockZeroingLowLimit);
4992     subs(tmp, cnt, low_limit >> 3);
4993     br(Assembler::LT, small);
4994   }
4995 
4996   far_call(StubRoutines::aarch64::get_zero_longs());
4997 
4998   bind(small);
4999 
5000   const int unroll = 8; // Number of stp instructions we'll unroll
5001   Label small_loop, small_table_end;
5002 
5003   andr(tmp, cnt, (unroll-1) * 2);
5004   sub(cnt, cnt, tmp);
5005   add(base, base, tmp, Assembler::LSL, 3);
5006   adr(tmp2, small_table_end);
5007   sub(tmp2, tmp2, tmp, Assembler::LSL, 1);
5008   br(tmp2);
5009 
5010   bind(small_loop);
5011   add(base, base, unroll * 16);
5012   for (int i = -unroll; i < 0; i++)
5013     stp(zr, zr, Address(base, i * 16));
5014   bind(small_table_end);
5015   subs(cnt, cnt, unroll * 2);
5016   br(Assembler::GE, small_loop);
5017 
5018   tbz(cnt, 0, done);
5019   str(zr, Address(post(base, 8)));
5020 
5021   bind(done);
5022 }
5023 
5024 // Intrinsic for sun/nio/cs/ISO_8859_1$Encoder.implEncodeISOArray and
5025 // java/lang/StringUTF16.compress.
5026 void MacroAssembler::encode_iso_array(Register src, Register dst,
5027                       Register len, Register result,
5028                       FloatRegister Vtmp1, FloatRegister Vtmp2,
5029                       FloatRegister Vtmp3, FloatRegister Vtmp4)
5030 {
5031     Label DONE, NEXT_32, LOOP_8, NEXT_8, LOOP_1, NEXT_1;
5032     Register tmp1 = rscratch1;
5033 
5034       mov(result, len); // Save initial len
5035 
5036 #ifndef BUILTIN_SIM
5037       subs(len, len, 32);
5038       br(LT, LOOP_8);
5039 
5040 // The following code uses the SIMD 'uqxtn' and 'uqxtn2' instructions
5041 // to convert chars to bytes. These set the 'QC' bit in the FPSR if
5042 // any char could not fit in a byte, so clear the FPSR so we can test it.
5043       clear_fpsr();
5044 
5045     BIND(NEXT_32);
5046       ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
5047       uqxtn(Vtmp1, T8B, Vtmp1, T8H);  // uqxtn  - write bottom half
5048       uqxtn(Vtmp1, T16B, Vtmp2, T8H); // uqxtn2 - write top half
5049       uqxtn(Vtmp2, T8B, Vtmp3, T8H);
5050       uqxtn(Vtmp2, T16B, Vtmp4, T8H); // uqxtn2
5051       get_fpsr(tmp1);
5052       cbnzw(tmp1, LOOP_8);
5053       st1(Vtmp1, Vtmp2, T16B, post(dst, 32));
5054       subs(len, len, 32);
5055       add(src, src, 64);
5056       br(GE, NEXT_32);
5057 
5058     BIND(LOOP_8);
5059       adds(len, len, 32-8);
5060       br(LT, LOOP_1);
5061       clear_fpsr(); // QC may be set from loop above, clear again
5062     BIND(NEXT_8);
5063       ld1(Vtmp1, T8H, src);
5064       uqxtn(Vtmp1, T8B, Vtmp1, T8H);
5065       get_fpsr(tmp1);
5066       cbnzw(tmp1, LOOP_1);
5067       st1(Vtmp1, T8B, post(dst, 8));
5068       subs(len, len, 8);
5069       add(src, src, 16);
5070       br(GE, NEXT_8);
5071 
5072     BIND(LOOP_1);
5073       adds(len, len, 8);
5074       br(LE, DONE);
5075 #else
5076       cbz(len, DONE);
5077 #endif
5078     BIND(NEXT_1);
5079       ldrh(tmp1, Address(post(src, 2)));
5080       tst(tmp1, 0xff00);
5081       br(NE, DONE);
5082       strb(tmp1, Address(post(dst, 1)));
5083       subs(len, len, 1);
5084       br(GT, NEXT_1);
5085 
5086     BIND(DONE);
5087       sub(result, result, len); // Return index where we stopped
5088                                 // Return len == 0 if we processed all
5089                                 // characters
5090 }
5091 
5092 
5093 // Inflate byte[] array to char[].
5094 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
5095                                         FloatRegister vtmp1, FloatRegister vtmp2, FloatRegister vtmp3,
5096                                         Register tmp4) {
5097   Label big, done;
5098 
5099   assert_different_registers(src, dst, len, tmp4, rscratch1);
5100 
5101   fmovd(vtmp1 , zr);
5102   lsrw(rscratch1, len, 3);
5103 
5104   cbnzw(rscratch1, big);
5105 
5106   // Short string: less than 8 bytes.
5107   {
5108     Label loop, around, tiny;
5109 
5110     subsw(len, len, 4);
5111     andw(len, len, 3);
5112     br(LO, tiny);
5113 
5114     // Use SIMD to do 4 bytes.
5115     ldrs(vtmp2, post(src, 4));
5116     zip1(vtmp3, T8B, vtmp2, vtmp1);
5117     strd(vtmp3, post(dst, 8));
5118 
5119     cbzw(len, done);
5120 
5121     // Do the remaining bytes by steam.
5122     bind(loop);
5123     ldrb(tmp4, post(src, 1));
5124     strh(tmp4, post(dst, 2));
5125     subw(len, len, 1);
5126 
5127     bind(tiny);
5128     cbnz(len, loop);
5129 
5130     bind(around);
5131     b(done);
5132   }
5133 
5134   // Unpack the bytes 8 at a time.
5135   bind(big);
5136   andw(len, len, 7);
5137 
5138   {
5139     Label loop, around;
5140 
5141     bind(loop);
5142     ldrd(vtmp2, post(src, 8));
5143     sub(rscratch1, rscratch1, 1);
5144     zip1(vtmp3, T16B, vtmp2, vtmp1);
5145     st1(vtmp3, T8H, post(dst, 16));
5146     cbnz(rscratch1, loop);
5147 
5148     bind(around);
5149   }
5150 
5151   // Do the tail of up to 8 bytes.
5152   sub(src, src, 8);
5153   add(src, src, len, ext::uxtw, 0);
5154   ldrd(vtmp2, Address(src));
5155   sub(dst, dst, 16);
5156   add(dst, dst, len, ext::uxtw, 1);
5157   zip1(vtmp3, T16B, vtmp2, vtmp1);
5158   st1(vtmp3, T8H, Address(dst));
5159 
5160   bind(done);
5161 }
5162 
5163 // Compress char[] array to byte[].
5164 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
5165                                          FloatRegister tmp1Reg, FloatRegister tmp2Reg,
5166                                          FloatRegister tmp3Reg, FloatRegister tmp4Reg,
5167                                          Register result) {
5168   encode_iso_array(src, dst, len, result,
5169                    tmp1Reg, tmp2Reg, tmp3Reg, tmp4Reg);
5170   cmp(len, zr);
5171   csel(result, result, zr, EQ);
5172 }
5173 
5174 // get_thread() can be called anywhere inside generated code so we
5175 // need to save whatever non-callee save context might get clobbered
5176 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
5177 // the call setup code.
5178 //
5179 // aarch64_get_thread_helper() clobbers only r0, r1, and flags.
5180 //
5181 void MacroAssembler::get_thread(Register dst) {
5182   RegSet saved_regs = RegSet::range(r0, r1) + lr - dst;
5183   push(saved_regs, sp);
5184 
5185   mov(lr, CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper));
5186   blrt(lr, 1, 0, 1);
5187   if (dst != c_rarg0) {
5188     mov(dst, c_rarg0);
5189   }
5190 
5191   pop(saved_regs, sp);
5192 }
--- EOF ---