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