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