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