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