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