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