1 /*
   2  * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2014, 2021, Red Hat Inc. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include <sys/types.h>
  27 
  28 #include "precompiled.hpp"
  29 #include "jvm.h"
  30 #include "asm/assembler.hpp"
  31 #include "asm/assembler.inline.hpp"
  32 #include "ci/ciEnv.hpp"

  33 #include "gc/shared/barrierSet.hpp"
  34 #include "gc/shared/barrierSetAssembler.hpp"
  35 #include "gc/shared/cardTableBarrierSet.hpp"
  36 #include "gc/shared/cardTable.hpp"
  37 #include "gc/shared/collectedHeap.hpp"
  38 #include "gc/shared/tlab_globals.hpp"
  39 #include "interpreter/bytecodeHistogram.hpp"
  40 #include "interpreter/interpreter.hpp"
  41 #include "compiler/compileTask.hpp"
  42 #include "compiler/disassembler.hpp"
  43 #include "memory/resourceArea.hpp"
  44 #include "memory/universe.hpp"
  45 #include "nativeInst_aarch64.hpp"
  46 #include "oops/accessDecorators.hpp"
  47 #include "oops/compressedOops.inline.hpp"
  48 #include "oops/klass.inline.hpp"
  49 #include "runtime/icache.hpp"
  50 #include "runtime/interfaceSupport.inline.hpp"
  51 #include "runtime/jniHandles.inline.hpp"
  52 #include "runtime/sharedRuntime.hpp"
  53 #include "runtime/stubRoutines.hpp"
  54 #include "runtime/thread.hpp"
  55 #include "utilities/powerOfTwo.hpp"
  56 #ifdef COMPILER1
  57 #include "c1/c1_LIRAssembler.hpp"
  58 #endif
  59 #ifdef COMPILER2
  60 #include "oops/oop.hpp"
  61 #include "opto/compile.hpp"
  62 #include "opto/node.hpp"
  63 #include "opto/output.hpp"
  64 #endif
  65 
  66 #ifdef PRODUCT
  67 #define BLOCK_COMMENT(str) /* nothing */
  68 #else
  69 #define BLOCK_COMMENT(str) block_comment(str)
  70 #endif
  71 #define STOP(str) stop(str);
  72 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  73 
  74 // Patch any kind of instruction; there may be several instructions.
  75 // Return the total length (in bytes) of the instructions.
  76 int MacroAssembler::pd_patch_instruction_size(address branch, address target) {
  77   int instructions = 1;
  78   assert((uint64_t)target < (1ull << 48), "48-bit overflow in address constant");
  79   intptr_t offset = (target - branch) >> 2;
  80   unsigned insn = *(unsigned*)branch;
  81   if ((Instruction_aarch64::extract(insn, 29, 24) & 0b111011) == 0b011000) {
  82     // Load register (literal)
  83     Instruction_aarch64::spatch(branch, 23, 5, offset);
  84   } else if (Instruction_aarch64::extract(insn, 30, 26) == 0b00101) {
  85     // Unconditional branch (immediate)
  86     Instruction_aarch64::spatch(branch, 25, 0, offset);
  87   } else if (Instruction_aarch64::extract(insn, 31, 25) == 0b0101010) {
  88     // Conditional branch (immediate)
  89     Instruction_aarch64::spatch(branch, 23, 5, offset);
  90   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011010) {
  91     // Compare & branch (immediate)
  92     Instruction_aarch64::spatch(branch, 23, 5, offset);
  93   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011011) {
  94     // Test & branch (immediate)
  95     Instruction_aarch64::spatch(branch, 18, 5, offset);
  96   } else if (Instruction_aarch64::extract(insn, 28, 24) == 0b10000) {
  97     // PC-rel. addressing
  98     offset = target-branch;
  99     int shift = Instruction_aarch64::extract(insn, 31, 31);
 100     if (shift) {
 101       uint64_t dest = (uint64_t)target;
 102       uint64_t pc_page = (uint64_t)branch >> 12;
 103       uint64_t adr_page = (uint64_t)target >> 12;
 104       unsigned offset_lo = dest & 0xfff;
 105       offset = adr_page - pc_page;
 106 
 107       // We handle 4 types of PC relative addressing
 108       //   1 - adrp    Rx, target_page
 109       //       ldr/str Ry, [Rx, #offset_in_page]
 110       //   2 - adrp    Rx, target_page
 111       //       add     Ry, Rx, #offset_in_page
 112       //   3 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 113       //       movk    Rx, #imm16<<32
 114       //   4 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 115       // In the first 3 cases we must check that Rx is the same in the adrp and the
 116       // subsequent ldr/str, add or movk instruction. Otherwise we could accidentally end
 117       // up treating a type 4 relocation as a type 1, 2 or 3 just because it happened
 118       // to be followed by a random unrelated ldr/str, add or movk instruction.
 119       //
 120       unsigned insn2 = ((unsigned*)branch)[1];
 121       if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
 122                 Instruction_aarch64::extract(insn, 4, 0) ==
 123                         Instruction_aarch64::extract(insn2, 9, 5)) {
 124         // Load/store register (unsigned immediate)
 125         unsigned size = Instruction_aarch64::extract(insn2, 31, 30);
 126         Instruction_aarch64::patch(branch + sizeof (unsigned),
 127                                     21, 10, offset_lo >> size);
 128         guarantee(((dest >> size) << size) == dest, "misaligned target");
 129         instructions = 2;
 130       } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
 131                 Instruction_aarch64::extract(insn, 4, 0) ==
 132                         Instruction_aarch64::extract(insn2, 4, 0)) {
 133         // add (immediate)
 134         Instruction_aarch64::patch(branch + sizeof (unsigned),
 135                                    21, 10, offset_lo);
 136         instructions = 2;
 137       } else if (Instruction_aarch64::extract(insn2, 31, 21) == 0b11110010110 &&
 138                    Instruction_aarch64::extract(insn, 4, 0) ==
 139                      Instruction_aarch64::extract(insn2, 4, 0)) {
 140         // movk #imm16<<32
 141         Instruction_aarch64::patch(branch + 4, 20, 5, (uint64_t)target >> 32);
 142         uintptr_t dest = ((uintptr_t)target & 0xffffffffULL) | ((uintptr_t)branch & 0xffff00000000ULL);
 143         uintptr_t pc_page = (uintptr_t)branch >> 12;
 144         uintptr_t adr_page = (uintptr_t)dest >> 12;
 145         offset = adr_page - pc_page;
 146         instructions = 2;
 147       }
 148     }
 149     int offset_lo = offset & 3;
 150     offset >>= 2;
 151     Instruction_aarch64::spatch(branch, 23, 5, offset);
 152     Instruction_aarch64::patch(branch, 30, 29, offset_lo);
 153   } else if (Instruction_aarch64::extract(insn, 31, 21) == 0b11010010100) {
 154     uint64_t dest = (uint64_t)target;
 155     // Move wide constant
 156     assert(nativeInstruction_at(branch+4)->is_movk(), "wrong insns in patch");
 157     assert(nativeInstruction_at(branch+8)->is_movk(), "wrong insns in patch");
 158     Instruction_aarch64::patch(branch, 20, 5, dest & 0xffff);
 159     Instruction_aarch64::patch(branch+4, 20, 5, (dest >>= 16) & 0xffff);
 160     Instruction_aarch64::patch(branch+8, 20, 5, (dest >>= 16) & 0xffff);
 161     assert(target_addr_for_insn(branch) == target, "should be");
 162     instructions = 3;
 163   } else if (NativeInstruction::is_ldrw_to_zr(address(&insn))) {
 164     // nothing to do
 165     assert(target == 0, "did not expect to relocate target for polling page load");
 166   } else {
 167     ShouldNotReachHere();
 168   }
 169   return instructions * NativeInstruction::instruction_size;
 170 }
 171 
 172 int MacroAssembler::patch_oop(address insn_addr, address o) {
 173   int instructions;
 174   unsigned insn = *(unsigned*)insn_addr;
 175   assert(nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 176 
 177   // OOPs are either narrow (32 bits) or wide (48 bits).  We encode
 178   // narrow OOPs by setting the upper 16 bits in the first
 179   // instruction.
 180   if (Instruction_aarch64::extract(insn, 31, 21) == 0b11010010101) {
 181     // Move narrow OOP
 182     uint32_t n = CompressedOops::narrow_oop_value(cast_to_oop(o));
 183     Instruction_aarch64::patch(insn_addr, 20, 5, n >> 16);
 184     Instruction_aarch64::patch(insn_addr+4, 20, 5, n & 0xffff);
 185     instructions = 2;
 186   } else {
 187     // Move wide OOP
 188     assert(nativeInstruction_at(insn_addr+8)->is_movk(), "wrong insns in patch");
 189     uintptr_t dest = (uintptr_t)o;
 190     Instruction_aarch64::patch(insn_addr, 20, 5, dest & 0xffff);
 191     Instruction_aarch64::patch(insn_addr+4, 20, 5, (dest >>= 16) & 0xffff);
 192     Instruction_aarch64::patch(insn_addr+8, 20, 5, (dest >>= 16) & 0xffff);
 193     instructions = 3;
 194   }
 195   return instructions * NativeInstruction::instruction_size;
 196 }
 197 
 198 int MacroAssembler::patch_narrow_klass(address insn_addr, narrowKlass n) {
 199   // Metatdata pointers are either narrow (32 bits) or wide (48 bits).
 200   // We encode narrow ones by setting the upper 16 bits in the first
 201   // instruction.
 202   NativeInstruction *insn = nativeInstruction_at(insn_addr);
 203   assert(Instruction_aarch64::extract(insn->encoding(), 31, 21) == 0b11010010101 &&
 204          nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 205 
 206   Instruction_aarch64::patch(insn_addr, 20, 5, n >> 16);
 207   Instruction_aarch64::patch(insn_addr+4, 20, 5, n & 0xffff);
 208   return 2 * NativeInstruction::instruction_size;
 209 }
 210 
 211 address MacroAssembler::target_addr_for_insn(address insn_addr, unsigned insn) {
 212   intptr_t offset = 0;
 213   if ((Instruction_aarch64::extract(insn, 29, 24) & 0b011011) == 0b00011000) {
 214     // Load register (literal)
 215     offset = Instruction_aarch64::sextract(insn, 23, 5);
 216     return address(((uint64_t)insn_addr + (offset << 2)));
 217   } else if (Instruction_aarch64::extract(insn, 30, 26) == 0b00101) {
 218     // Unconditional branch (immediate)
 219     offset = Instruction_aarch64::sextract(insn, 25, 0);
 220   } else if (Instruction_aarch64::extract(insn, 31, 25) == 0b0101010) {
 221     // Conditional branch (immediate)
 222     offset = Instruction_aarch64::sextract(insn, 23, 5);
 223   } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011010) {
 224     // Compare & branch (immediate)
 225     offset = Instruction_aarch64::sextract(insn, 23, 5);
 226    } else if (Instruction_aarch64::extract(insn, 30, 25) == 0b011011) {
 227     // Test & branch (immediate)
 228     offset = Instruction_aarch64::sextract(insn, 18, 5);
 229   } else if (Instruction_aarch64::extract(insn, 28, 24) == 0b10000) {
 230     // PC-rel. addressing
 231     offset = Instruction_aarch64::extract(insn, 30, 29);
 232     offset |= Instruction_aarch64::sextract(insn, 23, 5) << 2;
 233     int shift = Instruction_aarch64::extract(insn, 31, 31) ? 12 : 0;
 234     if (shift) {
 235       offset <<= shift;
 236       uint64_t target_page = ((uint64_t)insn_addr) + offset;
 237       target_page &= ((uint64_t)-1) << shift;
 238       // Return the target address for the following sequences
 239       //   1 - adrp    Rx, target_page
 240       //       ldr/str Ry, [Rx, #offset_in_page]
 241       //   2 - adrp    Rx, target_page
 242       //       add     Ry, Rx, #offset_in_page
 243       //   3 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 244       //       movk    Rx, #imm12<<32
 245       //   4 - adrp    Rx, target_page (page aligned reloc, offset == 0)
 246       //
 247       // In the first two cases  we check that the register is the same and
 248       // return the target_page + the offset within the page.
 249       // Otherwise we assume it is a page aligned relocation and return
 250       // the target page only.
 251       //
 252       unsigned insn2 = ((unsigned*)insn_addr)[1];
 253       if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
 254                 Instruction_aarch64::extract(insn, 4, 0) ==
 255                         Instruction_aarch64::extract(insn2, 9, 5)) {
 256         // Load/store register (unsigned immediate)
 257         unsigned int byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 258         unsigned int size = Instruction_aarch64::extract(insn2, 31, 30);
 259         return address(target_page + (byte_offset << size));
 260       } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
 261                 Instruction_aarch64::extract(insn, 4, 0) ==
 262                         Instruction_aarch64::extract(insn2, 4, 0)) {
 263         // add (immediate)
 264         unsigned int byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 265         return address(target_page + byte_offset);
 266       } else {
 267         if (Instruction_aarch64::extract(insn2, 31, 21) == 0b11110010110  &&
 268                Instruction_aarch64::extract(insn, 4, 0) ==
 269                  Instruction_aarch64::extract(insn2, 4, 0)) {
 270           target_page = (target_page & 0xffffffff) |
 271                          ((uint64_t)Instruction_aarch64::extract(insn2, 20, 5) << 32);
 272         }
 273         return (address)target_page;
 274       }
 275     } else {
 276       ShouldNotReachHere();
 277     }
 278   } else if (Instruction_aarch64::extract(insn, 31, 23) == 0b110100101) {
 279     uint32_t *insns = (uint32_t *)insn_addr;
 280     // Move wide constant: movz, movk, movk.  See movptr().
 281     assert(nativeInstruction_at(insns+1)->is_movk(), "wrong insns in patch");
 282     assert(nativeInstruction_at(insns+2)->is_movk(), "wrong insns in patch");
 283     return address(uint64_t(Instruction_aarch64::extract(insns[0], 20, 5))
 284                    + (uint64_t(Instruction_aarch64::extract(insns[1], 20, 5)) << 16)
 285                    + (uint64_t(Instruction_aarch64::extract(insns[2], 20, 5)) << 32));
 286   } else {
 287     ShouldNotReachHere();
 288   }
 289   return address(((uint64_t)insn_addr + (offset << 2)));
 290 }
 291 
 292 address MacroAssembler::target_addr_for_insn_or_null(address insn_addr, unsigned insn) {
 293   if (NativeInstruction::is_ldrw_to_zr(address(&insn))) {
 294     return 0;
 295   }
 296   return MacroAssembler::target_addr_for_insn(insn_addr, insn);
 297 }
 298 
 299 void MacroAssembler::safepoint_poll(Label& slow_path, bool at_return, bool acquire, bool in_nmethod) {
 300   if (acquire) {
 301     lea(rscratch1, Address(rthread, JavaThread::polling_word_offset()));
 302     ldar(rscratch1, rscratch1);
 303   } else {
 304     ldr(rscratch1, Address(rthread, JavaThread::polling_word_offset()));
 305   }
 306   if (at_return) {
 307     // Note that when in_nmethod is set, the stack pointer is incremented before the poll. Therefore,
 308     // we may safely use the sp instead to perform the stack watermark check.
 309     cmp(in_nmethod ? sp : rfp, rscratch1);
 310     br(Assembler::HI, slow_path);
 311   } else {
 312     tbnz(rscratch1, log2i_exact(SafepointMechanism::poll_bit()), slow_path);










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
















































































































































































--- EOF ---