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