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