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