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