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