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