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(bool save_vectors) {
2290   push(0x3fffffff, sp);         // integer registers except lr & sp
2291 
2292   if (!save_vectors) {
2293     for (int i = 30; i >= 0; i -= 2)
2294       stpd(as_FloatRegister(i), as_FloatRegister(i+1),
2295            Address(pre(sp, -2 * wordSize)));
2296   } else {
2297     for (int i = 30; i >= 0; i -= 2)
2298       stpq(as_FloatRegister(i), as_FloatRegister(i+1),
2299            Address(pre(sp, -4 * wordSize)));
2300   }
2301 }
2302 
2303 void MacroAssembler::pop_CPU_state(bool restore_vectors) {
2304   if (!restore_vectors) {
2305     for (int i = 0; i < 32; i += 2)
2306       ldpd(as_FloatRegister(i), as_FloatRegister(i+1),
2307            Address(post(sp, 2 * wordSize)));
2308   } else {
2309     for (int i = 0; i < 32; i += 2)
2310       ldpq(as_FloatRegister(i), as_FloatRegister(i+1),
2311            Address(post(sp, 4 * wordSize)));
2312   }
2313 
2314   pop(0x3fffffff, sp);         // integer registers except lr & sp
2315 }
2316 
2317 /**
2318  * Helpers for multiply_to_len().
2319  */
2320 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
2321                                      Register src1, Register src2) {
2322   adds(dest_lo, dest_lo, src1);
2323   adc(dest_hi, dest_hi, zr);
2324   adds(dest_lo, dest_lo, src2);
2325   adc(final_dest_hi, dest_hi, zr);
2326 }
2327 
2328 // Generate an address from (r + r1 extend offset).  "size" is the
2329 // size of the operand.  The result may be in rscratch2.
2330 Address MacroAssembler::offsetted_address(Register r, Register r1,
2331                                           Address::extend ext, int offset, int size) {
2332   if (offset || (ext.shift() % size != 0)) {
2333     lea(rscratch2, Address(r, r1, ext));
2334     return Address(rscratch2, offset);
2335   } else {
2336     return Address(r, r1, ext);
2337   }
2338 }
2339 
2340 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
2341 {
2342   assert(offset >= 0, "spill to negative address?");
2343   // Offset reachable ?
2344   //   Not aligned - 9 bits signed offset
2345   //   Aligned - 12 bits unsigned offset shifted
2346   Register base = sp;
2347   if ((offset & (size-1)) && offset >= (1<<8)) {
2348     add(tmp, base, offset & ((1<<12)-1));
2349     base = tmp;
2350     offset &= -1<<12;
2351   }
2352 
2353   if (offset >= (1<<12) * size) {
2354     add(tmp, base, offset & (((1<<12)-1)<<12));
2355     base = tmp;
2356     offset &= ~(((1<<12)-1)<<12);
2357   }
2358 
2359   return Address(base, offset);
2360 }
2361 
2362 /**
2363  * Multiply 64 bit by 64 bit first loop.
2364  */
2365 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
2366                                            Register y, Register y_idx, Register z,
2367                                            Register carry, Register product,
2368                                            Register idx, Register kdx) {
2369   //
2370   //  jlong carry, x[], y[], z[];
2371   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2372   //    huge_128 product = y[idx] * x[xstart] + carry;
2373   //    z[kdx] = (jlong)product;
2374   //    carry  = (jlong)(product >>> 64);
2375   //  }
2376   //  z[xstart] = carry;
2377   //
2378 
2379   Label L_first_loop, L_first_loop_exit;
2380   Label L_one_x, L_one_y, L_multiply;
2381 
2382   subsw(xstart, xstart, 1);
2383   br(Assembler::MI, L_one_x);
2384 
2385   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
2386   ldr(x_xstart, Address(rscratch1));
2387   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
2388 
2389   bind(L_first_loop);
2390   subsw(idx, idx, 1);
2391   br(Assembler::MI, L_first_loop_exit);
2392   subsw(idx, idx, 1);
2393   br(Assembler::MI, L_one_y);
2394   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2395   ldr(y_idx, Address(rscratch1));
2396   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
2397   bind(L_multiply);
2398 
2399   // AArch64 has a multiply-accumulate instruction that we can't use
2400   // here because it has no way to process carries, so we have to use
2401   // separate add and adc instructions.  Bah.
2402   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
2403   mul(product, x_xstart, y_idx);
2404   adds(product, product, carry);
2405   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
2406 
2407   subw(kdx, kdx, 2);
2408   ror(product, product, 32); // back to big-endian
2409   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
2410 
2411   b(L_first_loop);
2412 
2413   bind(L_one_y);
2414   ldrw(y_idx, Address(y,  0));
2415   b(L_multiply);
2416 
2417   bind(L_one_x);
2418   ldrw(x_xstart, Address(x,  0));
2419   b(L_first_loop);
2420 
2421   bind(L_first_loop_exit);
2422 }
2423 
2424 /**
2425  * Multiply 128 bit by 128. Unrolled inner loop.
2426  *
2427  */
2428 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
2429                                              Register carry, Register carry2,
2430                                              Register idx, Register jdx,
2431                                              Register yz_idx1, Register yz_idx2,
2432                                              Register tmp, Register tmp3, Register tmp4,
2433                                              Register tmp6, Register product_hi) {
2434 
2435   //   jlong carry, x[], y[], z[];
2436   //   int kdx = ystart+1;
2437   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
2438   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
2439   //     jlong carry2  = (jlong)(tmp3 >>> 64);
2440   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
2441   //     carry  = (jlong)(tmp4 >>> 64);
2442   //     z[kdx+idx+1] = (jlong)tmp3;
2443   //     z[kdx+idx] = (jlong)tmp4;
2444   //   }
2445   //   idx += 2;
2446   //   if (idx > 0) {
2447   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
2448   //     z[kdx+idx] = (jlong)yz_idx1;
2449   //     carry  = (jlong)(yz_idx1 >>> 64);
2450   //   }
2451   //
2452 
2453   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
2454 
2455   lsrw(jdx, idx, 2);
2456 
2457   bind(L_third_loop);
2458 
2459   subsw(jdx, jdx, 1);
2460   br(Assembler::MI, L_third_loop_exit);
2461   subw(idx, idx, 4);
2462 
2463   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2464 
2465   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
2466 
2467   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2468 
2469   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
2470   ror(yz_idx2, yz_idx2, 32);
2471 
2472   ldp(rscratch2, rscratch1, Address(tmp6, 0));
2473 
2474   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2475   umulh(tmp4, product_hi, yz_idx1);
2476 
2477   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
2478   ror(rscratch2, rscratch2, 32);
2479 
2480   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
2481   umulh(carry2, product_hi, yz_idx2);
2482 
2483   // propagate sum of both multiplications into carry:tmp4:tmp3
2484   adds(tmp3, tmp3, carry);
2485   adc(tmp4, tmp4, zr);
2486   adds(tmp3, tmp3, rscratch1);
2487   adcs(tmp4, tmp4, tmp);
2488   adc(carry, carry2, zr);
2489   adds(tmp4, tmp4, rscratch2);
2490   adc(carry, carry, zr);
2491 
2492   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
2493   ror(tmp4, tmp4, 32);
2494   stp(tmp4, tmp3, Address(tmp6, 0));
2495 
2496   b(L_third_loop);
2497   bind (L_third_loop_exit);
2498 
2499   andw (idx, idx, 0x3);
2500   cbz(idx, L_post_third_loop_done);
2501 
2502   Label L_check_1;
2503   subsw(idx, idx, 2);
2504   br(Assembler::MI, L_check_1);
2505 
2506   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2507   ldr(yz_idx1, Address(rscratch1, 0));
2508   ror(yz_idx1, yz_idx1, 32);
2509   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
2510   umulh(tmp4, product_hi, yz_idx1);
2511   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2512   ldr(yz_idx2, Address(rscratch1, 0));
2513   ror(yz_idx2, yz_idx2, 32);
2514 
2515   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
2516 
2517   ror(tmp3, tmp3, 32);
2518   str(tmp3, Address(rscratch1, 0));
2519 
2520   bind (L_check_1);
2521 
2522   andw (idx, idx, 0x1);
2523   subsw(idx, idx, 1);
2524   br(Assembler::MI, L_post_third_loop_done);
2525   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
2526   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
2527   umulh(carry2, tmp4, product_hi);
2528   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2529 
2530   add2_with_carry(carry2, tmp3, tmp4, carry);
2531 
2532   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
2533   extr(carry, carry2, tmp3, 32);
2534 
2535   bind(L_post_third_loop_done);
2536 }
2537 
2538 /**
2539  * Code for BigInteger::multiplyToLen() instrinsic.
2540  *
2541  * r0: x
2542  * r1: xlen
2543  * r2: y
2544  * r3: ylen
2545  * r4:  z
2546  * r5: zlen
2547  * r10: tmp1
2548  * r11: tmp2
2549  * r12: tmp3
2550  * r13: tmp4
2551  * r14: tmp5
2552  * r15: tmp6
2553  * r16: tmp7
2554  *
2555  */
2556 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
2557                                      Register z, Register zlen,
2558                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
2559                                      Register tmp5, Register tmp6, Register product_hi) {
2560 
2561   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6);
2562 
2563   const Register idx = tmp1;
2564   const Register kdx = tmp2;
2565   const Register xstart = tmp3;
2566 
2567   const Register y_idx = tmp4;
2568   const Register carry = tmp5;
2569   const Register product  = xlen;
2570   const Register x_xstart = zlen;  // reuse register
2571 
2572   // First Loop.
2573   //
2574   //  final static long LONG_MASK = 0xffffffffL;
2575   //  int xstart = xlen - 1;
2576   //  int ystart = ylen - 1;
2577   //  long carry = 0;
2578   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
2579   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
2580   //    z[kdx] = (int)product;
2581   //    carry = product >>> 32;
2582   //  }
2583   //  z[xstart] = (int)carry;
2584   //
2585 
2586   movw(idx, ylen);      // idx = ylen;
2587   movw(kdx, zlen);      // kdx = xlen+ylen;
2588   mov(carry, zr);       // carry = 0;
2589 
2590   Label L_done;
2591 
2592   movw(xstart, xlen);
2593   subsw(xstart, xstart, 1);
2594   br(Assembler::MI, L_done);
2595 
2596   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
2597 
2598   Label L_second_loop;
2599   cbzw(kdx, L_second_loop);
2600 
2601   Label L_carry;
2602   subw(kdx, kdx, 1);
2603   cbzw(kdx, L_carry);
2604 
2605   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
2606   lsr(carry, carry, 32);
2607   subw(kdx, kdx, 1);
2608 
2609   bind(L_carry);
2610   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
2611 
2612   // Second and third (nested) loops.
2613   //
2614   // for (int i = xstart-1; i >= 0; i--) { // Second loop
2615   //   carry = 0;
2616   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
2617   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
2618   //                    (z[k] & LONG_MASK) + carry;
2619   //     z[k] = (int)product;
2620   //     carry = product >>> 32;
2621   //   }
2622   //   z[i] = (int)carry;
2623   // }
2624   //
2625   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
2626 
2627   const Register jdx = tmp1;
2628 
2629   bind(L_second_loop);
2630   mov(carry, zr);                // carry = 0;
2631   movw(jdx, ylen);               // j = ystart+1
2632 
2633   subsw(xstart, xstart, 1);      // i = xstart-1;
2634   br(Assembler::MI, L_done);
2635 
2636   str(z, Address(pre(sp, -4 * wordSize)));
2637 
2638   Label L_last_x;
2639   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
2640   subsw(xstart, xstart, 1);       // i = xstart-1;
2641   br(Assembler::MI, L_last_x);
2642 
2643   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
2644   ldr(product_hi, Address(rscratch1));
2645   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
2646 
2647   Label L_third_loop_prologue;
2648   bind(L_third_loop_prologue);
2649 
2650   str(ylen, Address(sp, wordSize));
2651   stp(x, xstart, Address(sp, 2 * wordSize));
2652   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
2653                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
2654   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
2655   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
2656 
2657   addw(tmp3, xlen, 1);
2658   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
2659   subsw(tmp3, tmp3, 1);
2660   br(Assembler::MI, L_done);
2661 
2662   lsr(carry, carry, 32);
2663   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
2664   b(L_second_loop);
2665 
2666   // Next infrequent code is moved outside loops.
2667   bind(L_last_x);
2668   ldrw(product_hi, Address(x,  0));
2669   b(L_third_loop_prologue);
2670 
2671   bind(L_done);
2672 }
2673 
2674 /**
2675  * Emits code to update CRC-32 with a byte value according to constants in table
2676  *
2677  * @param [in,out]crc   Register containing the crc.
2678  * @param [in]val       Register containing the byte to fold into the CRC.
2679  * @param [in]table     Register containing the table of crc constants.
2680  *
2681  * uint32_t crc;
2682  * val = crc_table[(val ^ crc) & 0xFF];
2683  * crc = val ^ (crc >> 8);
2684  *
2685  */
2686 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
2687   eor(val, val, crc);
2688   andr(val, val, 0xff);
2689   ldrw(val, Address(table, val, Address::lsl(2)));
2690   eor(crc, val, crc, Assembler::LSR, 8);
2691 }
2692 
2693 /**
2694  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
2695  *
2696  * @param [in,out]crc   Register containing the crc.
2697  * @param [in]v         Register containing the 32-bit to fold into the CRC.
2698  * @param [in]table0    Register containing table 0 of crc constants.
2699  * @param [in]table1    Register containing table 1 of crc constants.
2700  * @param [in]table2    Register containing table 2 of crc constants.
2701  * @param [in]table3    Register containing table 3 of crc constants.
2702  *
2703  * uint32_t crc;
2704  *   v = crc ^ v
2705  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
2706  *
2707  */
2708 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
2709         Register table0, Register table1, Register table2, Register table3,
2710         bool upper) {
2711   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
2712   uxtb(tmp, v);
2713   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
2714   ubfx(tmp, v, 8, 8);
2715   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
2716   eor(crc, crc, tmp);
2717   ubfx(tmp, v, 16, 8);
2718   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
2719   eor(crc, crc, tmp);
2720   ubfx(tmp, v, 24, 8);
2721   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
2722   eor(crc, crc, tmp);
2723 }
2724 
2725 /**
2726  * @param crc   register containing existing CRC (32-bit)
2727  * @param buf   register pointing to input byte buffer (byte*)
2728  * @param len   register containing number of bytes
2729  * @param table register that will contain address of CRC table
2730  * @param tmp   scratch register
2731  */
2732 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
2733         Register table0, Register table1, Register table2, Register table3,
2734         Register tmp, Register tmp2, Register tmp3) {
2735   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
2736   unsigned long offset;
2737 
2738     ornw(crc, zr, crc);
2739 
2740   if (UseCRC32) {
2741     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop;
2742 
2743       subs(len, len, 64);
2744       br(Assembler::GE, CRC_by64_loop);
2745       adds(len, len, 64-4);
2746       br(Assembler::GE, CRC_by4_loop);
2747       adds(len, len, 4);
2748       br(Assembler::GT, CRC_by1_loop);
2749       b(L_exit);
2750 
2751     BIND(CRC_by4_loop);
2752       ldrw(tmp, Address(post(buf, 4)));
2753       subs(len, len, 4);
2754       crc32w(crc, crc, tmp);
2755       br(Assembler::GE, CRC_by4_loop);
2756       adds(len, len, 4);
2757       br(Assembler::LE, L_exit);
2758     BIND(CRC_by1_loop);
2759       ldrb(tmp, Address(post(buf, 1)));
2760       subs(len, len, 1);
2761       crc32b(crc, crc, tmp);
2762       br(Assembler::GT, CRC_by1_loop);
2763       b(L_exit);
2764 
2765       align(CodeEntryAlignment);
2766     BIND(CRC_by64_loop);
2767       subs(len, len, 64);
2768       ldp(tmp, tmp3, Address(post(buf, 16)));
2769       crc32x(crc, crc, tmp);
2770       crc32x(crc, crc, tmp3);
2771       ldp(tmp, tmp3, Address(post(buf, 16)));
2772       crc32x(crc, crc, tmp);
2773       crc32x(crc, crc, tmp3);
2774       ldp(tmp, tmp3, Address(post(buf, 16)));
2775       crc32x(crc, crc, tmp);
2776       crc32x(crc, crc, tmp3);
2777       ldp(tmp, tmp3, Address(post(buf, 16)));
2778       crc32x(crc, crc, tmp);
2779       crc32x(crc, crc, tmp3);
2780       br(Assembler::GE, CRC_by64_loop);
2781       adds(len, len, 64-4);
2782       br(Assembler::GE, CRC_by4_loop);
2783       adds(len, len, 4);
2784       br(Assembler::GT, CRC_by1_loop);
2785     BIND(L_exit);
2786       ornw(crc, zr, crc);
2787       return;
2788   }
2789 
2790     adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
2791     if (offset) add(table0, table0, offset);
2792     add(table1, table0, 1*256*sizeof(juint));
2793     add(table2, table0, 2*256*sizeof(juint));
2794     add(table3, table0, 3*256*sizeof(juint));
2795 
2796   if (UseNeon) {
2797       cmp(len, 64);
2798       br(Assembler::LT, L_by16);
2799       eor(v16, T16B, v16, v16);
2800 
2801     Label L_fold;
2802 
2803       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
2804 
2805       ld1(v0, v1, T2D, post(buf, 32));
2806       ld1r(v4, T2D, post(tmp, 8));
2807       ld1r(v5, T2D, post(tmp, 8));
2808       ld1r(v6, T2D, post(tmp, 8));
2809       ld1r(v7, T2D, post(tmp, 8));
2810       mov(v16, T4S, 0, crc);
2811 
2812       eor(v0, T16B, v0, v16);
2813       sub(len, len, 64);
2814 
2815     BIND(L_fold);
2816       pmull(v22, T8H, v0, v5, T8B);
2817       pmull(v20, T8H, v0, v7, T8B);
2818       pmull(v23, T8H, v0, v4, T8B);
2819       pmull(v21, T8H, v0, v6, T8B);
2820 
2821       pmull2(v18, T8H, v0, v5, T16B);
2822       pmull2(v16, T8H, v0, v7, T16B);
2823       pmull2(v19, T8H, v0, v4, T16B);
2824       pmull2(v17, T8H, v0, v6, T16B);
2825 
2826       uzp1(v24, v20, v22, T8H);
2827       uzp2(v25, v20, v22, T8H);
2828       eor(v20, T16B, v24, v25);
2829 
2830       uzp1(v26, v16, v18, T8H);
2831       uzp2(v27, v16, v18, T8H);
2832       eor(v16, T16B, v26, v27);
2833 
2834       ushll2(v22, T4S, v20, T8H, 8);
2835       ushll(v20, T4S, v20, T4H, 8);
2836 
2837       ushll2(v18, T4S, v16, T8H, 8);
2838       ushll(v16, T4S, v16, T4H, 8);
2839 
2840       eor(v22, T16B, v23, v22);
2841       eor(v18, T16B, v19, v18);
2842       eor(v20, T16B, v21, v20);
2843       eor(v16, T16B, v17, v16);
2844 
2845       uzp1(v17, v16, v20, T2D);
2846       uzp2(v21, v16, v20, T2D);
2847       eor(v17, T16B, v17, v21);
2848 
2849       ushll2(v20, T2D, v17, T4S, 16);
2850       ushll(v16, T2D, v17, T2S, 16);
2851 
2852       eor(v20, T16B, v20, v22);
2853       eor(v16, T16B, v16, v18);
2854 
2855       uzp1(v17, v20, v16, T2D);
2856       uzp2(v21, v20, v16, T2D);
2857       eor(v28, T16B, v17, v21);
2858 
2859       pmull(v22, T8H, v1, v5, T8B);
2860       pmull(v20, T8H, v1, v7, T8B);
2861       pmull(v23, T8H, v1, v4, T8B);
2862       pmull(v21, T8H, v1, v6, T8B);
2863 
2864       pmull2(v18, T8H, v1, v5, T16B);
2865       pmull2(v16, T8H, v1, v7, T16B);
2866       pmull2(v19, T8H, v1, v4, T16B);
2867       pmull2(v17, T8H, v1, v6, T16B);
2868 
2869       ld1(v0, v1, T2D, post(buf, 32));
2870 
2871       uzp1(v24, v20, v22, T8H);
2872       uzp2(v25, v20, v22, T8H);
2873       eor(v20, T16B, v24, v25);
2874 
2875       uzp1(v26, v16, v18, T8H);
2876       uzp2(v27, v16, v18, T8H);
2877       eor(v16, T16B, v26, v27);
2878 
2879       ushll2(v22, T4S, v20, T8H, 8);
2880       ushll(v20, T4S, v20, T4H, 8);
2881 
2882       ushll2(v18, T4S, v16, T8H, 8);
2883       ushll(v16, T4S, v16, T4H, 8);
2884 
2885       eor(v22, T16B, v23, v22);
2886       eor(v18, T16B, v19, v18);
2887       eor(v20, T16B, v21, v20);
2888       eor(v16, T16B, v17, v16);
2889 
2890       uzp1(v17, v16, v20, T2D);
2891       uzp2(v21, v16, v20, T2D);
2892       eor(v16, T16B, v17, v21);
2893 
2894       ushll2(v20, T2D, v16, T4S, 16);
2895       ushll(v16, T2D, v16, T2S, 16);
2896 
2897       eor(v20, T16B, v22, v20);
2898       eor(v16, T16B, v16, v18);
2899 
2900       uzp1(v17, v20, v16, T2D);
2901       uzp2(v21, v20, v16, T2D);
2902       eor(v20, T16B, v17, v21);
2903 
2904       shl(v16, T2D, v28, 1);
2905       shl(v17, T2D, v20, 1);
2906 
2907       eor(v0, T16B, v0, v16);
2908       eor(v1, T16B, v1, v17);
2909 
2910       subs(len, len, 32);
2911       br(Assembler::GE, L_fold);
2912 
2913       mov(crc, 0);
2914       mov(tmp, v0, T1D, 0);
2915       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
2916       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
2917       mov(tmp, v0, T1D, 1);
2918       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
2919       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
2920       mov(tmp, v1, T1D, 0);
2921       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
2922       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
2923       mov(tmp, v1, T1D, 1);
2924       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
2925       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
2926 
2927       add(len, len, 32);
2928   }
2929 
2930   BIND(L_by16);
2931     subs(len, len, 16);
2932     br(Assembler::GE, L_by16_loop);
2933     adds(len, len, 16-4);
2934     br(Assembler::GE, L_by4_loop);
2935     adds(len, len, 4);
2936     br(Assembler::GT, L_by1_loop);
2937     b(L_exit);
2938 
2939   BIND(L_by4_loop);
2940     ldrw(tmp, Address(post(buf, 4)));
2941     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
2942     subs(len, len, 4);
2943     br(Assembler::GE, L_by4_loop);
2944     adds(len, len, 4);
2945     br(Assembler::LE, L_exit);
2946   BIND(L_by1_loop);
2947     subs(len, len, 1);
2948     ldrb(tmp, Address(post(buf, 1)));
2949     update_byte_crc32(crc, tmp, table0);
2950     br(Assembler::GT, L_by1_loop);
2951     b(L_exit);
2952 
2953     align(CodeEntryAlignment);
2954   BIND(L_by16_loop);
2955     subs(len, len, 16);
2956     ldp(tmp, tmp3, Address(post(buf, 16)));
2957     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
2958     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
2959     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
2960     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
2961     br(Assembler::GE, L_by16_loop);
2962     adds(len, len, 16-4);
2963     br(Assembler::GE, L_by4_loop);
2964     adds(len, len, 4);
2965     br(Assembler::GT, L_by1_loop);
2966   BIND(L_exit);
2967     ornw(crc, zr, crc);
2968 }
2969 
2970 /**
2971  * @param crc   register containing existing CRC (32-bit)
2972  * @param buf   register pointing to input byte buffer (byte*)
2973  * @param len   register containing number of bytes
2974  * @param table register that will contain address of CRC table
2975  * @param tmp   scratch register
2976  */
2977 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
2978         Register table0, Register table1, Register table2, Register table3,
2979         Register tmp, Register tmp2, Register tmp3) {
2980   Label L_exit;
2981   Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop;
2982 
2983     subs(len, len, 64);
2984     br(Assembler::GE, CRC_by64_loop);
2985     adds(len, len, 64-4);
2986     br(Assembler::GE, CRC_by4_loop);
2987     adds(len, len, 4);
2988     br(Assembler::GT, CRC_by1_loop);
2989     b(L_exit);
2990 
2991   BIND(CRC_by4_loop);
2992     ldrw(tmp, Address(post(buf, 4)));
2993     subs(len, len, 4);
2994     crc32cw(crc, crc, tmp);
2995     br(Assembler::GE, CRC_by4_loop);
2996     adds(len, len, 4);
2997     br(Assembler::LE, L_exit);
2998   BIND(CRC_by1_loop);
2999     ldrb(tmp, Address(post(buf, 1)));
3000     subs(len, len, 1);
3001     crc32cb(crc, crc, tmp);
3002     br(Assembler::GT, CRC_by1_loop);
3003     b(L_exit);
3004 
3005     align(CodeEntryAlignment);
3006   BIND(CRC_by64_loop);
3007     subs(len, len, 64);
3008     ldp(tmp, tmp3, Address(post(buf, 16)));
3009     crc32cx(crc, crc, tmp);
3010     crc32cx(crc, crc, tmp3);
3011     ldp(tmp, tmp3, Address(post(buf, 16)));
3012     crc32cx(crc, crc, tmp);
3013     crc32cx(crc, crc, tmp3);
3014     ldp(tmp, tmp3, Address(post(buf, 16)));
3015     crc32cx(crc, crc, tmp);
3016     crc32cx(crc, crc, tmp3);
3017     ldp(tmp, tmp3, Address(post(buf, 16)));
3018     crc32cx(crc, crc, tmp);
3019     crc32cx(crc, crc, tmp3);
3020     br(Assembler::GE, CRC_by64_loop);
3021     adds(len, len, 64-4);
3022     br(Assembler::GE, CRC_by4_loop);
3023     adds(len, len, 4);
3024     br(Assembler::GT, CRC_by1_loop);
3025   BIND(L_exit);
3026     return;
3027 }
3028 
3029 SkipIfEqual::SkipIfEqual(
3030     MacroAssembler* masm, const bool* flag_addr, bool value) {
3031   _masm = masm;
3032   unsigned long offset;
3033   _masm->adrp(rscratch1, ExternalAddress((address)flag_addr), offset);
3034   _masm->ldrb(rscratch1, Address(rscratch1, offset));
3035   _masm->cbzw(rscratch1, _label);
3036 }
3037 
3038 SkipIfEqual::~SkipIfEqual() {
3039   _masm->bind(_label);
3040 }
3041 
3042 void MacroAssembler::cmpptr(Register src1, Address src2) {
3043   unsigned long offset;
3044   adrp(rscratch1, src2, offset);
3045   ldr(rscratch1, Address(rscratch1, offset));
3046   cmp(src1, rscratch1);
3047 }
3048 
3049 void MacroAssembler::store_check(Register obj, Address dst) {
3050   store_check(obj);
3051 }
3052 
3053 void MacroAssembler::store_check(Register obj) {
3054   // Does a store check for the oop in register obj. The content of
3055   // register obj is destroyed afterwards.
3056 
3057   BarrierSet* bs = Universe::heap()->barrier_set();
3058   assert(bs->kind() == BarrierSet::CardTableForRS ||
3059          bs->kind() == BarrierSet::CardTableExtension,
3060          "Wrong barrier set kind");
3061 
3062   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
3063   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3064 
3065   lsr(obj, obj, CardTableModRefBS::card_shift);
3066 
3067   assert(CardTableModRefBS::dirty_card_val() == 0, "must be");
3068 
3069   {
3070     ExternalAddress cardtable((address) ct->byte_map_base);
3071     unsigned long offset;
3072     adrp(rscratch1, cardtable, offset);
3073     assert(offset == 0, "byte_map_base is misaligned");
3074   }
3075 
3076   if (UseCondCardMark) {
3077     Label L_already_dirty;
3078     ldrb(rscratch2,  Address(obj, rscratch1));
3079     cbz(rscratch2, L_already_dirty);
3080     strb(zr, Address(obj, rscratch1));
3081     bind(L_already_dirty);
3082   } else {
3083     strb(zr, Address(obj, rscratch1));
3084   }
3085 }
3086 
3087 void MacroAssembler::load_klass(Register dst, Register src) {
3088   if (UseCompressedClassPointers) {
3089     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3090     decode_klass_not_null(dst);
3091   } else {
3092     ldr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
3093   }
3094 }
3095 
3096 void MacroAssembler::cmp_klass(Register oop, Register trial_klass, Register tmp) {
3097   if (UseCompressedClassPointers) {
3098     ldrw(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3099     if (Universe::narrow_klass_base() == NULL) {
3100       cmp(trial_klass, tmp, LSL, Universe::narrow_klass_shift());
3101       return;
3102     } else if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3103                && Universe::narrow_klass_shift() == 0) {
3104       // Only the bottom 32 bits matter
3105       cmpw(trial_klass, tmp);
3106       return;
3107     }
3108     decode_klass_not_null(tmp);
3109   } else {
3110     ldr(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
3111   }
3112   cmp(trial_klass, tmp);
3113 }
3114 
3115 void MacroAssembler::load_prototype_header(Register dst, Register src) {
3116   load_klass(dst, src);
3117   ldr(dst, Address(dst, Klass::prototype_header_offset()));
3118 }
3119 
3120 void MacroAssembler::store_klass(Register dst, Register src) {
3121   // FIXME: Should this be a store release?  concurrent gcs assumes
3122   // klass length is valid if klass field is not null.
3123   if (UseCompressedClassPointers) {
3124     encode_klass_not_null(src);
3125     strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3126   } else {
3127     str(src, Address(dst, oopDesc::klass_offset_in_bytes()));
3128   }
3129 }
3130 
3131 void MacroAssembler::store_klass_gap(Register dst, Register src) {
3132   if (UseCompressedClassPointers) {
3133     // Store to klass gap in destination
3134     strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
3135   }
3136 }
3137 
3138 // Algorithm must match oop.inline.hpp encode_heap_oop.
3139 void MacroAssembler::encode_heap_oop(Register d, Register s) {
3140 #ifdef ASSERT
3141   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
3142 #endif
3143   verify_oop(s, "broken oop in encode_heap_oop");
3144   if (Universe::narrow_oop_base() == NULL) {
3145     if (Universe::narrow_oop_shift() != 0) {
3146       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3147       lsr(d, s, LogMinObjAlignmentInBytes);
3148     } else {
3149       mov(d, s);
3150     }
3151   } else {
3152     subs(d, s, rheapbase);
3153     csel(d, d, zr, Assembler::HS);
3154     lsr(d, d, LogMinObjAlignmentInBytes);
3155 
3156     /*  Old algorithm: is this any worse?
3157     Label nonnull;
3158     cbnz(r, nonnull);
3159     sub(r, r, rheapbase);
3160     bind(nonnull);
3161     lsr(r, r, LogMinObjAlignmentInBytes);
3162     */
3163   }
3164 }
3165 
3166 void MacroAssembler::encode_heap_oop_not_null(Register r) {
3167 #ifdef ASSERT
3168   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
3169   if (CheckCompressedOops) {
3170     Label ok;
3171     cbnz(r, ok);
3172     stop("null oop passed to encode_heap_oop_not_null");
3173     bind(ok);
3174   }
3175 #endif
3176   verify_oop(r, "broken oop in encode_heap_oop_not_null");
3177   if (Universe::narrow_oop_base() != NULL) {
3178     sub(r, r, rheapbase);
3179   }
3180   if (Universe::narrow_oop_shift() != 0) {
3181     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3182     lsr(r, r, LogMinObjAlignmentInBytes);
3183   }
3184 }
3185 
3186 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
3187 #ifdef ASSERT
3188   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
3189   if (CheckCompressedOops) {
3190     Label ok;
3191     cbnz(src, ok);
3192     stop("null oop passed to encode_heap_oop_not_null2");
3193     bind(ok);
3194   }
3195 #endif
3196   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
3197 
3198   Register data = src;
3199   if (Universe::narrow_oop_base() != NULL) {
3200     sub(dst, src, rheapbase);
3201     data = dst;
3202   }
3203   if (Universe::narrow_oop_shift() != 0) {
3204     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3205     lsr(dst, data, LogMinObjAlignmentInBytes);
3206     data = dst;
3207   }
3208   if (data == src)
3209     mov(dst, src);
3210 }
3211 
3212 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
3213 #ifdef ASSERT
3214   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
3215 #endif
3216   if (Universe::narrow_oop_base() == NULL) {
3217     if (Universe::narrow_oop_shift() != 0 || d != s) {
3218       lsl(d, s, Universe::narrow_oop_shift());
3219     }
3220   } else {
3221     Label done;
3222     if (d != s)
3223       mov(d, s);
3224     cbz(s, done);
3225     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
3226     bind(done);
3227   }
3228   verify_oop(d, "broken oop in decode_heap_oop");
3229 }
3230 
3231 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
3232   assert (UseCompressedOops, "should only be used for compressed headers");
3233   assert (Universe::heap() != NULL, "java heap should be initialized");
3234   // Cannot assert, unverified entry point counts instructions (see .ad file)
3235   // vtableStubs also counts instructions in pd_code_size_limit.
3236   // Also do not verify_oop as this is called by verify_oop.
3237   if (Universe::narrow_oop_shift() != 0) {
3238     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3239     if (Universe::narrow_oop_base() != NULL) {
3240       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3241     } else {
3242       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
3243     }
3244   } else {
3245     assert (Universe::narrow_oop_base() == NULL, "sanity");
3246   }
3247 }
3248 
3249 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
3250   assert (UseCompressedOops, "should only be used for compressed headers");
3251   assert (Universe::heap() != NULL, "java heap should be initialized");
3252   // Cannot assert, unverified entry point counts instructions (see .ad file)
3253   // vtableStubs also counts instructions in pd_code_size_limit.
3254   // Also do not verify_oop as this is called by verify_oop.
3255   if (Universe::narrow_oop_shift() != 0) {
3256     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
3257     if (Universe::narrow_oop_base() != NULL) {
3258       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3259     } else {
3260       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
3261     }
3262   } else {
3263     assert (Universe::narrow_oop_base() == NULL, "sanity");
3264     if (dst != src) {
3265       mov(dst, src);
3266     }
3267   }
3268 }
3269 
3270 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
3271   if (Universe::narrow_klass_base() == NULL) {
3272     if (Universe::narrow_klass_shift() != 0) {
3273       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3274       lsr(dst, src, LogKlassAlignmentInBytes);
3275     } else {
3276       if (dst != src) mov(dst, src);
3277     }
3278     return;
3279   }
3280 
3281   if (use_XOR_for_compressed_class_base) {
3282     if (Universe::narrow_klass_shift() != 0) {
3283       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3284       lsr(dst, dst, LogKlassAlignmentInBytes);
3285     } else {
3286       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3287     }
3288     return;
3289   }
3290 
3291   if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3292       && Universe::narrow_klass_shift() == 0) {
3293     movw(dst, src);
3294     return;
3295   }
3296 
3297 #ifdef ASSERT
3298   verify_heapbase("MacroAssembler::encode_klass_not_null2: heap base corrupted?");
3299 #endif
3300 
3301   Register rbase = dst;
3302   if (dst == src) rbase = rheapbase;
3303   mov(rbase, (uint64_t)Universe::narrow_klass_base());
3304   sub(dst, src, rbase);
3305   if (Universe::narrow_klass_shift() != 0) {
3306     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3307     lsr(dst, dst, LogKlassAlignmentInBytes);
3308   }
3309   if (dst == src) reinit_heapbase();
3310 }
3311 
3312 void MacroAssembler::encode_klass_not_null(Register r) {
3313   encode_klass_not_null(r, r);
3314 }
3315 
3316 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
3317   Register rbase = dst;
3318   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3319 
3320   if (Universe::narrow_klass_base() == NULL) {
3321     if (Universe::narrow_klass_shift() != 0) {
3322       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3323       lsl(dst, src, LogKlassAlignmentInBytes);
3324     } else {
3325       if (dst != src) mov(dst, src);
3326     }
3327     return;
3328   }
3329 
3330   if (use_XOR_for_compressed_class_base) {
3331     if (Universe::narrow_klass_shift() != 0) {
3332       lsl(dst, src, LogKlassAlignmentInBytes);
3333       eor(dst, dst, (uint64_t)Universe::narrow_klass_base());
3334     } else {
3335       eor(dst, src, (uint64_t)Universe::narrow_klass_base());
3336     }
3337     return;
3338   }
3339 
3340   if (((uint64_t)Universe::narrow_klass_base() & 0xffffffff) == 0
3341       && Universe::narrow_klass_shift() == 0) {
3342     if (dst != src)
3343       movw(dst, src);
3344     movk(dst, (uint64_t)Universe::narrow_klass_base() >> 32, 32);
3345     return;
3346   }
3347 
3348   // Cannot assert, unverified entry point counts instructions (see .ad file)
3349   // vtableStubs also counts instructions in pd_code_size_limit.
3350   // Also do not verify_oop as this is called by verify_oop.
3351   if (dst == src) rbase = rheapbase;
3352   mov(rbase, (uint64_t)Universe::narrow_klass_base());
3353   if (Universe::narrow_klass_shift() != 0) {
3354     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
3355     add(dst, rbase, src, Assembler::LSL, LogKlassAlignmentInBytes);
3356   } else {
3357     add(dst, rbase, src);
3358   }
3359   if (dst == src) reinit_heapbase();
3360 }
3361 
3362 void  MacroAssembler::decode_klass_not_null(Register r) {
3363   decode_klass_not_null(r, r);
3364 }
3365 
3366 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
3367   assert (UseCompressedOops, "should only be used for compressed oops");
3368   assert (Universe::heap() != NULL, "java heap should be initialized");
3369   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
3370 
3371   int oop_index = oop_recorder()->find_index(obj);
3372   assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "should be real oop");
3373 
3374   InstructionMark im(this);
3375   RelocationHolder rspec = oop_Relocation::spec(oop_index);
3376   code_section()->relocate(inst_mark(), rspec);
3377   movz(dst, 0xDEAD, 16);
3378   movk(dst, 0xBEEF);
3379 }
3380 
3381 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
3382   assert (UseCompressedClassPointers, "should only be used for compressed headers");
3383   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
3384   int index = oop_recorder()->find_index(k);
3385   assert(! Universe::heap()->is_in_reserved(k), "should not be an oop");
3386 
3387   InstructionMark im(this);
3388   RelocationHolder rspec = metadata_Relocation::spec(index);
3389   code_section()->relocate(inst_mark(), rspec);
3390   narrowKlass nk = Klass::encode_klass(k);
3391   movz(dst, (nk >> 16), 16);
3392   movk(dst, nk & 0xffff);
3393 }
3394 
3395 void MacroAssembler::load_heap_oop(Register dst, Address src)
3396 {
3397   if (UseCompressedOops) {
3398     ldrw(dst, src);
3399     decode_heap_oop(dst);
3400   } else {
3401     ldr(dst, src);
3402   }
3403 }
3404 
3405 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src)
3406 {
3407   if (UseCompressedOops) {
3408     ldrw(dst, src);
3409     decode_heap_oop_not_null(dst);
3410   } else {
3411     ldr(dst, src);
3412   }
3413 }
3414 
3415 void MacroAssembler::store_heap_oop(Address dst, Register src) {
3416   if (UseCompressedOops) {
3417     assert(!dst.uses(src), "not enough registers");
3418     encode_heap_oop(src);
3419     strw(src, dst);
3420   } else
3421     str(src, dst);
3422 }
3423 
3424 // Used for storing NULLs.
3425 void MacroAssembler::store_heap_oop_null(Address dst) {
3426   if (UseCompressedOops) {
3427     strw(zr, dst);
3428   } else
3429     str(zr, dst);
3430 }
3431 
3432 #if INCLUDE_ALL_GCS
3433 void MacroAssembler::g1_write_barrier_pre(Register obj,
3434                                           Register pre_val,
3435                                           Register thread,
3436                                           Register tmp,
3437                                           bool tosca_live,
3438                                           bool expand_call) {
3439   // If expand_call is true then we expand the call_VM_leaf macro
3440   // directly to skip generating the check by
3441   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
3442 
3443   assert(thread == rthread, "must be");
3444 
3445   Label done;
3446   Label runtime;
3447 
3448   assert(pre_val != noreg, "check this code");
3449 
3450   if (obj != noreg)
3451     assert_different_registers(obj, pre_val, tmp);
3452 
3453   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3454                                        PtrQueue::byte_offset_of_active()));
3455   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3456                                        PtrQueue::byte_offset_of_index()));
3457   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
3458                                        PtrQueue::byte_offset_of_buf()));
3459 
3460 
3461   // Is marking active?
3462   if (in_bytes(PtrQueue::byte_width_of_active()) == 4) {
3463     ldrw(tmp, in_progress);
3464   } else {
3465     assert(in_bytes(PtrQueue::byte_width_of_active()) == 1, "Assumption");
3466     ldrb(tmp, in_progress);
3467   }
3468   cbzw(tmp, done);
3469 
3470   // Do we need to load the previous value?
3471   if (obj != noreg) {
3472     load_heap_oop(pre_val, Address(obj, 0));
3473   }
3474 
3475   // Is the previous value null?
3476   cbz(pre_val, done);
3477 
3478   // Can we store original value in the thread's buffer?
3479   // Is index == 0?
3480   // (The index field is typed as size_t.)
3481 
3482   ldr(tmp, index);                      // tmp := *index_adr
3483   cbz(tmp, runtime);                    // tmp == 0?
3484                                         // If yes, goto runtime
3485 
3486   sub(tmp, tmp, wordSize);              // tmp := tmp - wordSize
3487   str(tmp, index);                      // *index_adr := tmp
3488   ldr(rscratch1, buffer);
3489   add(tmp, tmp, rscratch1);             // tmp := tmp + *buffer_adr
3490 
3491   // Record the previous value
3492   str(pre_val, Address(tmp, 0));
3493   b(done);
3494 
3495   bind(runtime);
3496   // save the live input values
3497   push(r0->bit(tosca_live) | obj->bit(obj != noreg) | pre_val->bit(true), sp);
3498 
3499   // Calling the runtime using the regular call_VM_leaf mechanism generates
3500   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
3501   // that checks that the *(rfp+frame::interpreter_frame_last_sp) == NULL.
3502   //
3503   // If we care generating the pre-barrier without a frame (e.g. in the
3504   // intrinsified Reference.get() routine) then ebp might be pointing to
3505   // the caller frame and so this check will most likely fail at runtime.
3506   //
3507   // Expanding the call directly bypasses the generation of the check.
3508   // So when we do not have have a full interpreter frame on the stack
3509   // expand_call should be passed true.
3510 
3511   if (expand_call) {
3512     assert(pre_val != c_rarg1, "smashed arg");
3513     pass_arg1(this, thread);
3514     pass_arg0(this, pre_val);
3515     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
3516   } else {
3517     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
3518   }
3519 
3520   pop(r0->bit(tosca_live) | obj->bit(obj != noreg) | pre_val->bit(true), sp);
3521 
3522   bind(done);
3523 }
3524 
3525 void MacroAssembler::g1_write_barrier_post(Register store_addr,
3526                                            Register new_val,
3527                                            Register thread,
3528                                            Register tmp,
3529                                            Register tmp2) {
3530   assert(thread == rthread, "must be");
3531 
3532   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
3533                                        PtrQueue::byte_offset_of_index()));
3534   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
3535                                        PtrQueue::byte_offset_of_buf()));
3536 
3537   BarrierSet* bs = Universe::heap()->barrier_set();
3538   CardTableModRefBS* ct = (CardTableModRefBS*)bs;
3539   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3540 
3541   Label done;
3542   Label runtime;
3543 
3544   // Does store cross heap regions?
3545 
3546   eor(tmp, store_addr, new_val);
3547   lsr(tmp, tmp, HeapRegion::LogOfHRGrainBytes);
3548   cbz(tmp, done);
3549 
3550   // crosses regions, storing NULL?
3551 
3552   cbz(new_val, done);
3553 
3554   // storing region crossing non-NULL, is card already dirty?
3555 
3556   ExternalAddress cardtable((address) ct->byte_map_base);
3557   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
3558   const Register card_addr = tmp;
3559 
3560   lsr(card_addr, store_addr, CardTableModRefBS::card_shift);
3561 
3562   unsigned long offset;
3563   adrp(tmp2, cardtable, offset);
3564 
3565   // get the address of the card
3566   add(card_addr, card_addr, tmp2);
3567   ldrb(tmp2, Address(card_addr, offset));
3568   cmpw(tmp2, (int)G1SATBCardTableModRefBS::g1_young_card_val());
3569   br(Assembler::EQ, done);
3570 
3571   assert((int)CardTableModRefBS::dirty_card_val() == 0, "must be 0");
3572 
3573   membar(Assembler::StoreLoad);
3574 
3575   ldrb(tmp2, Address(card_addr, offset));
3576   cbzw(tmp2, done);
3577 
3578   // storing a region crossing, non-NULL oop, card is clean.
3579   // dirty card and log.
3580 
3581   strb(zr, Address(card_addr, offset));
3582 
3583   ldr(rscratch1, queue_index);
3584   cbz(rscratch1, runtime);
3585   sub(rscratch1, rscratch1, wordSize);
3586   str(rscratch1, queue_index);
3587 
3588   ldr(tmp2, buffer);
3589   str(card_addr, Address(tmp2, rscratch1));
3590   b(done);
3591 
3592   bind(runtime);
3593   // save the live input values
3594   push(store_addr->bit(true) | new_val->bit(true), sp);
3595   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
3596   pop(store_addr->bit(true) | new_val->bit(true), sp);
3597 
3598   bind(done);
3599 }
3600 
3601 #endif // INCLUDE_ALL_GCS
3602 
3603 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
3604   assert(oop_recorder() != NULL, "this assembler needs a Recorder");
3605   int index = oop_recorder()->allocate_metadata_index(obj);
3606   RelocationHolder rspec = metadata_Relocation::spec(index);
3607   return Address((address)obj, rspec);
3608 }
3609 
3610 // Move an oop into a register.  immediate is true if we want
3611 // immediate instrcutions, i.e. we are not going to patch this
3612 // instruction while the code is being executed by another thread.  In
3613 // that case we can use move immediates rather than the constant pool.
3614 void MacroAssembler::movoop(Register dst, jobject obj, bool immediate) {
3615   int oop_index;
3616   if (obj == NULL) {
3617     oop_index = oop_recorder()->allocate_oop_index(obj);
3618   } else {
3619     oop_index = oop_recorder()->find_index(obj);
3620     assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "should be real oop");
3621   }
3622   RelocationHolder rspec = oop_Relocation::spec(oop_index);
3623   if (! immediate) {
3624     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
3625     ldr_constant(dst, Address(dummy, rspec));
3626   } else
3627     mov(dst, Address((address)obj, rspec));
3628 }
3629 
3630 // Move a metadata address into a register.
3631 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
3632   int oop_index;
3633   if (obj == NULL) {
3634     oop_index = oop_recorder()->allocate_metadata_index(obj);
3635   } else {
3636     oop_index = oop_recorder()->find_index(obj);
3637   }
3638   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
3639   mov(dst, Address((address)obj, rspec));
3640 }
3641 
3642 Address MacroAssembler::constant_oop_address(jobject obj) {
3643   assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
3644   assert(Universe::heap()->is_in_reserved(JNIHandles::resolve(obj)), "not an oop");
3645   int oop_index = oop_recorder()->find_index(obj);
3646   return Address((address)obj, oop_Relocation::spec(oop_index));
3647 }
3648 
3649 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
3650 void MacroAssembler::tlab_allocate(Register obj,
3651                                    Register var_size_in_bytes,
3652                                    int con_size_in_bytes,
3653                                    Register t1,
3654                                    Register t2,
3655                                    Label& slow_case) {
3656   assert_different_registers(obj, t2);
3657   assert_different_registers(obj, var_size_in_bytes);
3658   Register end = t2;
3659 
3660   // verify_tlab();
3661 
3662   ldr(obj, Address(rthread, JavaThread::tlab_top_offset()));
3663   if (var_size_in_bytes == noreg) {
3664     lea(end, Address(obj, con_size_in_bytes));
3665   } else {
3666     lea(end, Address(obj, var_size_in_bytes));
3667   }
3668   ldr(rscratch1, Address(rthread, JavaThread::tlab_end_offset()));
3669   cmp(end, rscratch1);
3670   br(Assembler::HI, slow_case);
3671 
3672   // update the tlab top pointer
3673   str(end, Address(rthread, JavaThread::tlab_top_offset()));
3674 
3675   // recover var_size_in_bytes if necessary
3676   if (var_size_in_bytes == end) {
3677     sub(var_size_in_bytes, var_size_in_bytes, obj);
3678   }
3679   // verify_tlab();
3680 }
3681 
3682 // Preserves r19, and r3.
3683 Register MacroAssembler::tlab_refill(Label& retry,
3684                                      Label& try_eden,
3685                                      Label& slow_case) {
3686   Register top = r0;
3687   Register t1  = r2;
3688   Register t2  = r4;
3689   assert_different_registers(top, rthread, t1, t2, /* preserve: */ r19, r3);
3690   Label do_refill, discard_tlab;
3691 
3692   if (!Universe::heap()->supports_inline_contig_alloc()) {
3693     // No allocation in the shared eden.
3694     b(slow_case);
3695   }
3696 
3697   ldr(top, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3698   ldr(t1,  Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
3699 
3700   // calculate amount of free space
3701   sub(t1, t1, top);
3702   lsr(t1, t1, LogHeapWordSize);
3703 
3704   // Retain tlab and allocate object in shared space if
3705   // the amount free in the tlab is too large to discard.
3706 
3707   ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3708   cmp(t1, rscratch1);
3709   br(Assembler::LE, discard_tlab);
3710 
3711   // Retain
3712   // ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3713   mov(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
3714   add(rscratch1, rscratch1, t2);
3715   str(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
3716 
3717   if (TLABStats) {
3718     // increment number of slow_allocations
3719     addmw(Address(rthread, in_bytes(JavaThread::tlab_slow_allocations_offset())),
3720          1, rscratch1);
3721   }
3722   b(try_eden);
3723 
3724   bind(discard_tlab);
3725   if (TLABStats) {
3726     // increment number of refills
3727     addmw(Address(rthread, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1,
3728          rscratch1);
3729     // accumulate wastage -- t1 is amount free in tlab
3730     addmw(Address(rthread, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1,
3731          rscratch1);
3732   }
3733 
3734   // if tlab is currently allocated (top or end != null) then
3735   // fill [top, end + alignment_reserve) with array object
3736   cbz(top, do_refill);
3737 
3738   // set up the mark word
3739   mov(rscratch1, (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
3740   str(rscratch1, Address(top, oopDesc::mark_offset_in_bytes()));
3741   // set the length to the remaining space
3742   sub(t1, t1, typeArrayOopDesc::header_size(T_INT));
3743   add(t1, t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
3744   lsl(t1, t1, log2_intptr(HeapWordSize/sizeof(jint)));
3745   strw(t1, Address(top, arrayOopDesc::length_offset_in_bytes()));
3746   // set klass to intArrayKlass
3747   {
3748     unsigned long offset;
3749     // dubious reloc why not an oop reloc?
3750     adrp(rscratch1, ExternalAddress((address)Universe::intArrayKlassObj_addr()),
3751          offset);
3752     ldr(t1, Address(rscratch1, offset));
3753   }
3754   // store klass last.  concurrent gcs assumes klass length is valid if
3755   // klass field is not null.
3756   store_klass(top, t1);
3757 
3758   mov(t1, top);
3759   ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
3760   sub(t1, t1, rscratch1);
3761   incr_allocated_bytes(rthread, t1, 0, rscratch1);
3762 
3763   // refill the tlab with an eden allocation
3764   bind(do_refill);
3765   ldr(t1, Address(rthread, in_bytes(JavaThread::tlab_size_offset())));
3766   lsl(t1, t1, LogHeapWordSize);
3767   // allocate new tlab, address returned in top
3768   eden_allocate(top, t1, 0, t2, slow_case);
3769 
3770   // Check that t1 was preserved in eden_allocate.
3771 #ifdef ASSERT
3772   if (UseTLAB) {
3773     Label ok;
3774     Register tsize = r4;
3775     assert_different_registers(tsize, rthread, t1);
3776     str(tsize, Address(pre(sp, -16)));
3777     ldr(tsize, Address(rthread, in_bytes(JavaThread::tlab_size_offset())));
3778     lsl(tsize, tsize, LogHeapWordSize);
3779     cmp(t1, tsize);
3780     br(Assembler::EQ, ok);
3781     STOP("assert(t1 != tlab size)");
3782     should_not_reach_here();
3783 
3784     bind(ok);
3785     ldr(tsize, Address(post(sp, 16)));
3786   }
3787 #endif
3788   str(top, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
3789   str(top, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3790   add(top, top, t1);
3791   sub(top, top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
3792   str(top, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
3793   verify_tlab();
3794   b(retry);
3795 
3796   return rthread; // for use by caller
3797 }
3798 
3799 // Defines obj, preserves var_size_in_bytes
3800 void MacroAssembler::eden_allocate(Register obj,
3801                                    Register var_size_in_bytes,
3802                                    int con_size_in_bytes,
3803                                    Register t1,
3804                                    Label& slow_case) {
3805   assert_different_registers(obj, var_size_in_bytes, t1);
3806   if (!Universe::heap()->supports_inline_contig_alloc()) {
3807     b(slow_case);
3808   } else {
3809     Register end = t1;
3810     Register heap_end = rscratch2;
3811     Label retry;
3812     bind(retry);
3813     {
3814       unsigned long offset;
3815       adrp(rscratch1, ExternalAddress((address) Universe::heap()->end_addr()), offset);
3816       ldr(heap_end, Address(rscratch1, offset));
3817     }
3818 
3819     ExternalAddress heap_top((address) Universe::heap()->top_addr());
3820 
3821     // Get the current top of the heap
3822     {
3823       unsigned long offset;
3824       adrp(rscratch1, heap_top, offset);
3825       // Use add() here after ARDP, rather than lea().
3826       // lea() does not generate anything if its offset is zero.
3827       // However, relocs expect to find either an ADD or a load/store
3828       // insn after an ADRP.  add() always generates an ADD insn, even
3829       // for add(Rn, Rn, 0).
3830       add(rscratch1, rscratch1, offset);
3831       ldaxr(obj, rscratch1);
3832     }
3833 
3834     // Adjust it my the size of our new object
3835     if (var_size_in_bytes == noreg) {
3836       lea(end, Address(obj, con_size_in_bytes));
3837     } else {
3838       lea(end, Address(obj, var_size_in_bytes));
3839     }
3840 
3841     // if end < obj then we wrapped around high memory
3842     cmp(end, obj);
3843     br(Assembler::LO, slow_case);
3844 
3845     cmp(end, heap_end);
3846     br(Assembler::HI, slow_case);
3847 
3848     // If heap_top hasn't been changed by some other thread, update it.
3849     stlxr(rscratch2, end, rscratch1);
3850     cbnzw(rscratch2, retry);
3851   }
3852 }
3853 
3854 void MacroAssembler::verify_tlab() {
3855 #ifdef ASSERT
3856   if (UseTLAB && VerifyOops) {
3857     Label next, ok;
3858 
3859     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
3860 
3861     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3862     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
3863     cmp(rscratch2, rscratch1);
3864     br(Assembler::HS, next);
3865     STOP("assert(top >= start)");
3866     should_not_reach_here();
3867 
3868     bind(next);
3869     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
3870     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
3871     cmp(rscratch2, rscratch1);
3872     br(Assembler::HS, ok);
3873     STOP("assert(top <= end)");
3874     should_not_reach_here();
3875 
3876     bind(ok);
3877     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
3878   }
3879 #endif
3880 }
3881 
3882 // Writes to stack successive pages until offset reached to check for
3883 // stack overflow + shadow pages.  This clobbers tmp.
3884 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
3885   assert_different_registers(tmp, size, rscratch1);
3886   mov(tmp, sp);
3887   // Bang stack for total size given plus shadow page size.
3888   // Bang one page at a time because large size can bang beyond yellow and
3889   // red zones.
3890   Label loop;
3891   mov(rscratch1, os::vm_page_size());
3892   bind(loop);
3893   lea(tmp, Address(tmp, -os::vm_page_size()));
3894   subsw(size, size, rscratch1);
3895   str(size, Address(tmp));
3896   br(Assembler::GT, loop);
3897 
3898   // Bang down shadow pages too.
3899   // At this point, (tmp-0) is the last address touched, so don't
3900   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
3901   // was post-decremented.)  Skip this address by starting at i=1, and
3902   // touch a few more pages below.  N.B.  It is important to touch all
3903   // the way down to and including i=StackShadowPages.
3904   for (int i = 0; i< StackShadowPages-1; i++) {
3905     // this could be any sized move but this is can be a debugging crumb
3906     // so the bigger the better.
3907     lea(tmp, Address(tmp, -os::vm_page_size()));
3908     str(size, Address(tmp));
3909   }
3910 }
3911 
3912 
3913 address MacroAssembler::read_polling_page(Register r, address page, relocInfo::relocType rtype) {
3914   unsigned long off;
3915   adrp(r, Address(page, rtype), off);
3916   InstructionMark im(this);
3917   code_section()->relocate(inst_mark(), rtype);
3918   ldrw(zr, Address(r, off));
3919   return inst_mark();
3920 }
3921 
3922 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
3923   InstructionMark im(this);
3924   code_section()->relocate(inst_mark(), rtype);
3925   ldrw(zr, Address(r, 0));
3926   return inst_mark();
3927 }
3928 
3929 void MacroAssembler::adrp(Register reg1, const Address &dest, unsigned long &byte_offset) {
3930   relocInfo::relocType rtype = dest.rspec().reloc()->type();
3931   if (uabs(pc() - dest.target()) >= (1LL << 32)) {
3932     guarantee(rtype == relocInfo::none
3933               || rtype == relocInfo::external_word_type
3934               || rtype == relocInfo::poll_type
3935               || rtype == relocInfo::poll_return_type,
3936               "can only use a fixed address with an ADRP");
3937     // Out of range.  This doesn't happen very often, but we have to
3938     // handle it
3939     mov(reg1, dest);
3940     byte_offset = 0;
3941   } else {
3942     InstructionMark im(this);
3943     code_section()->relocate(inst_mark(), dest.rspec());
3944     byte_offset = (uint64_t)dest.target() & 0xfff;
3945     _adrp(reg1, dest.target());
3946   }
3947 }
3948 
3949 void MacroAssembler::build_frame(int framesize) {
3950   assert(framesize > 0, "framesize must be > 0");
3951   if (framesize < ((1 << 9) + 2 * wordSize)) {
3952     sub(sp, sp, framesize);
3953     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
3954     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
3955   } else {
3956     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
3957     if (PreserveFramePointer) mov(rfp, sp);
3958     if (framesize < ((1 << 12) + 2 * wordSize))
3959       sub(sp, sp, framesize - 2 * wordSize);
3960     else {
3961       mov(rscratch1, framesize - 2 * wordSize);
3962       sub(sp, sp, rscratch1);
3963     }
3964   }
3965 }
3966 
3967 void MacroAssembler::remove_frame(int framesize) {
3968   assert(framesize > 0, "framesize must be > 0");
3969   if (framesize < ((1 << 9) + 2 * wordSize)) {
3970     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
3971     add(sp, sp, framesize);
3972   } else {
3973     if (framesize < ((1 << 12) + 2 * wordSize))
3974       add(sp, sp, framesize - 2 * wordSize);
3975     else {
3976       mov(rscratch1, framesize - 2 * wordSize);
3977       add(sp, sp, rscratch1);
3978     }
3979     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
3980   }
3981 }
3982 
3983 
3984 // Search for str1 in str2 and return index or -1
3985 void MacroAssembler::string_indexof(Register str2, Register str1,
3986                                     Register cnt2, Register cnt1,
3987                                     Register tmp1, Register tmp2,
3988                                     Register tmp3, Register tmp4,
3989                                     int icnt1, Register result) {
3990   Label BM, LINEARSEARCH, DONE, NOMATCH, MATCH;
3991 
3992   Register ch1 = rscratch1;
3993   Register ch2 = rscratch2;
3994   Register cnt1tmp = tmp1;
3995   Register cnt2tmp = tmp2;
3996   Register cnt1_neg = cnt1;
3997   Register cnt2_neg = cnt2;
3998   Register result_tmp = tmp4;
3999 
4000   // Note, inline_string_indexOf() generates checks:
4001   // if (substr.count > string.count) return -1;
4002   // if (substr.count == 0) return 0;
4003 
4004 // We have two strings, a source string in str2, cnt2 and a pattern string
4005 // in str1, cnt1. Find the 1st occurence of pattern in source or return -1.
4006 
4007 // For larger pattern and source we use a simplified Boyer Moore algorithm.
4008 // With a small pattern and source we use linear scan.
4009 
4010   if (icnt1 == -1) {
4011     cmp(cnt1, 256);             // Use Linear Scan if cnt1 < 8 || cnt1 >= 256
4012     ccmp(cnt1, 8, 0b0000, LO);  // Can't handle skip >= 256 because we use
4013     br(LO, LINEARSEARCH);       // a byte array.
4014     cmp(cnt1, cnt2, LSR, 2);    // Source must be 4 * pattern for BM
4015     br(HS, LINEARSEARCH);
4016   }
4017 
4018 // The Boyer Moore alogorithm is based on the description here:-
4019 //
4020 // http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm
4021 //
4022 // This describes and algorithm with 2 shift rules. The 'Bad Character' rule
4023 // and the 'Good Suffix' rule.
4024 //
4025 // These rules are essentially heuristics for how far we can shift the
4026 // pattern along the search string.
4027 //
4028 // The implementation here uses the 'Bad Character' rule only because of the
4029 // complexity of initialisation for the 'Good Suffix' rule.
4030 //
4031 // This is also known as the Boyer-Moore-Horspool algorithm:-
4032 //
4033 // http://en.wikipedia.org/wiki/Boyer-Moore-Horspool_algorithm
4034 //
4035 // #define ASIZE 128
4036 //
4037 //    int bm(unsigned char *x, int m, unsigned char *y, int n) {
4038 //       int i, j;
4039 //       unsigned c;
4040 //       unsigned char bc[ASIZE];
4041 //
4042 //       /* Preprocessing */
4043 //       for (i = 0; i < ASIZE; ++i)
4044 //          bc[i] = 0;
4045 //       for (i = 0; i < m - 1; ) {
4046 //          c = x[i];
4047 //          ++i;
4048 //          if (c < ASIZE) bc[c] = i;
4049 //       }
4050 //
4051 //       /* Searching */
4052 //       j = 0;
4053 //       while (j <= n - m) {
4054 //          c = y[i+j];
4055 //          if (x[m-1] == c)
4056 //            for (i = m - 2; i >= 0 && x[i] == y[i + j]; --i);
4057 //          if (i < 0) return j;
4058 //          if (c < ASIZE)
4059 //            j = j - bc[y[j+m-1]] + m;
4060 //          else
4061 //            j += 1; // Advance by 1 only if char >= ASIZE
4062 //       }
4063 //    }
4064 
4065   if (icnt1 == -1) {
4066     BIND(BM);
4067 
4068     Label ZLOOP, BCLOOP, BCSKIP, BMLOOPSTR2, BMLOOPSTR1, BMSKIP;
4069     Label BMADV, BMMATCH, BMCHECKEND;
4070 
4071     Register cnt1end = tmp2;
4072     Register str2end = cnt2;
4073     Register skipch = tmp2;
4074 
4075     // Restrict ASIZE to 128 to reduce stack space/initialisation.
4076     // The presence of chars >= ASIZE in the target string does not affect
4077     // performance, but we must be careful not to initialise them in the stack
4078     // array.
4079     // The presence of chars >= ASIZE in the source string may adversely affect
4080     // performance since we can only advance by one when we encounter one.
4081 
4082       stp(zr, zr, pre(sp, -128));
4083       for (int i = 1; i < 8; i++)
4084           stp(zr, zr, Address(sp, i*16));
4085 
4086       mov(cnt1tmp, 0);
4087       sub(cnt1end, cnt1, 1);
4088     BIND(BCLOOP);
4089       ldrh(ch1, Address(str1, cnt1tmp, Address::lsl(1)));
4090       cmp(ch1, 128);
4091       add(cnt1tmp, cnt1tmp, 1);
4092       br(HS, BCSKIP);
4093       strb(cnt1tmp, Address(sp, ch1));
4094     BIND(BCSKIP);
4095       cmp(cnt1tmp, cnt1end);
4096       br(LT, BCLOOP);
4097 
4098       mov(result_tmp, str2);
4099 
4100       sub(cnt2, cnt2, cnt1);
4101       add(str2end, str2, cnt2, LSL, 1);
4102     BIND(BMLOOPSTR2);
4103       sub(cnt1tmp, cnt1, 1);
4104       ldrh(ch1, Address(str1, cnt1tmp, Address::lsl(1)));
4105       ldrh(skipch, Address(str2, cnt1tmp, Address::lsl(1)));
4106       cmp(ch1, skipch);
4107       br(NE, BMSKIP);
4108       subs(cnt1tmp, cnt1tmp, 1);
4109       br(LT, BMMATCH);
4110     BIND(BMLOOPSTR1);
4111       ldrh(ch1, Address(str1, cnt1tmp, Address::lsl(1)));
4112       ldrh(ch2, Address(str2, cnt1tmp, Address::lsl(1)));
4113       cmp(ch1, ch2);
4114       br(NE, BMSKIP);
4115       subs(cnt1tmp, cnt1tmp, 1);
4116       br(GE, BMLOOPSTR1);
4117     BIND(BMMATCH);
4118       sub(result_tmp, str2, result_tmp);
4119       lsr(result, result_tmp, 1);
4120       add(sp, sp, 128);
4121       b(DONE);
4122     BIND(BMADV);
4123       add(str2, str2, 2);
4124       b(BMCHECKEND);
4125     BIND(BMSKIP);
4126       cmp(skipch, 128);
4127       br(HS, BMADV);
4128       ldrb(ch2, Address(sp, skipch));
4129       add(str2, str2, cnt1, LSL, 1);
4130       sub(str2, str2, ch2, LSL, 1);
4131     BIND(BMCHECKEND);
4132       cmp(str2, str2end);
4133       br(LE, BMLOOPSTR2);
4134       add(sp, sp, 128);
4135       b(NOMATCH);
4136   }
4137 
4138   BIND(LINEARSEARCH);
4139   {
4140     Label DO1, DO2, DO3;
4141 
4142     Register str2tmp = tmp2;
4143     Register first = tmp3;
4144 
4145     if (icnt1 == -1)
4146     {
4147         Label DOSHORT, FIRST_LOOP, STR2_NEXT, STR1_LOOP, STR1_NEXT, LAST_WORD;
4148 
4149         cmp(cnt1, 4);
4150         br(LT, DOSHORT);
4151 
4152         sub(cnt2, cnt2, cnt1);
4153         sub(cnt1, cnt1, 4);
4154         mov(result_tmp, cnt2);
4155 
4156         lea(str1, Address(str1, cnt1, Address::uxtw(1)));
4157         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4158         sub(cnt1_neg, zr, cnt1, LSL, 1);
4159         sub(cnt2_neg, zr, cnt2, LSL, 1);
4160         ldr(first, Address(str1, cnt1_neg));
4161 
4162       BIND(FIRST_LOOP);
4163         ldr(ch2, Address(str2, cnt2_neg));
4164         cmp(first, ch2);
4165         br(EQ, STR1_LOOP);
4166       BIND(STR2_NEXT);
4167         adds(cnt2_neg, cnt2_neg, 2);
4168         br(LE, FIRST_LOOP);
4169         b(NOMATCH);
4170 
4171       BIND(STR1_LOOP);
4172         adds(cnt1tmp, cnt1_neg, 8);
4173         add(cnt2tmp, cnt2_neg, 8);
4174         br(GE, LAST_WORD);
4175 
4176       BIND(STR1_NEXT);
4177         ldr(ch1, Address(str1, cnt1tmp));
4178         ldr(ch2, Address(str2, cnt2tmp));
4179         cmp(ch1, ch2);
4180         br(NE, STR2_NEXT);
4181         adds(cnt1tmp, cnt1tmp, 8);
4182         add(cnt2tmp, cnt2tmp, 8);
4183         br(LT, STR1_NEXT);
4184 
4185       BIND(LAST_WORD);
4186         ldr(ch1, Address(str1));
4187         sub(str2tmp, str2, cnt1_neg);         // adjust to corresponding
4188         ldr(ch2, Address(str2tmp, cnt2_neg)); // word in str2
4189         cmp(ch1, ch2);
4190         br(NE, STR2_NEXT);
4191         b(MATCH);
4192 
4193       BIND(DOSHORT);
4194         cmp(cnt1, 2);
4195         br(LT, DO1);
4196         br(GT, DO3);
4197     }
4198 
4199     if (icnt1 == 4) {
4200       Label CH1_LOOP;
4201 
4202         ldr(ch1, str1);
4203         sub(cnt2, cnt2, 4);
4204         mov(result_tmp, cnt2);
4205         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4206         sub(cnt2_neg, zr, cnt2, LSL, 1);
4207 
4208       BIND(CH1_LOOP);
4209         ldr(ch2, Address(str2, cnt2_neg));
4210         cmp(ch1, ch2);
4211         br(EQ, MATCH);
4212         adds(cnt2_neg, cnt2_neg, 2);
4213         br(LE, CH1_LOOP);
4214         b(NOMATCH);
4215     }
4216 
4217     if (icnt1 == -1 || icnt1 == 2) {
4218       Label CH1_LOOP;
4219 
4220       BIND(DO2);
4221         ldrw(ch1, str1);
4222         sub(cnt2, cnt2, 2);
4223         mov(result_tmp, cnt2);
4224         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4225         sub(cnt2_neg, zr, cnt2, LSL, 1);
4226 
4227       BIND(CH1_LOOP);
4228         ldrw(ch2, Address(str2, cnt2_neg));
4229         cmp(ch1, ch2);
4230         br(EQ, MATCH);
4231         adds(cnt2_neg, cnt2_neg, 2);
4232         br(LE, CH1_LOOP);
4233         b(NOMATCH);
4234     }
4235 
4236     if (icnt1 == -1 || icnt1 == 3) {
4237       Label FIRST_LOOP, STR2_NEXT, STR1_LOOP;
4238 
4239       BIND(DO3);
4240         ldrw(first, str1);
4241         ldrh(ch1, Address(str1, 4));
4242 
4243         sub(cnt2, cnt2, 3);
4244         mov(result_tmp, cnt2);
4245         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4246         sub(cnt2_neg, zr, cnt2, LSL, 1);
4247 
4248       BIND(FIRST_LOOP);
4249         ldrw(ch2, Address(str2, cnt2_neg));
4250         cmpw(first, ch2);
4251         br(EQ, STR1_LOOP);
4252       BIND(STR2_NEXT);
4253         adds(cnt2_neg, cnt2_neg, 2);
4254         br(LE, FIRST_LOOP);
4255         b(NOMATCH);
4256 
4257       BIND(STR1_LOOP);
4258         add(cnt2tmp, cnt2_neg, 4);
4259         ldrh(ch2, Address(str2, cnt2tmp));
4260         cmp(ch1, ch2);
4261         br(NE, STR2_NEXT);
4262         b(MATCH);
4263     }
4264 
4265     if (icnt1 == -1 || icnt1 == 1) {
4266       Label CH1_LOOP, HAS_ZERO;
4267       Label DO1_SHORT, DO1_LOOP;
4268 
4269       BIND(DO1);
4270         ldrh(ch1, str1);
4271         cmp(cnt2, 4);
4272         br(LT, DO1_SHORT);
4273 
4274         orr(ch1, ch1, ch1, LSL, 16);
4275         orr(ch1, ch1, ch1, LSL, 32);
4276 
4277         sub(cnt2, cnt2, 4);
4278         mov(result_tmp, cnt2);
4279         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4280         sub(cnt2_neg, zr, cnt2, LSL, 1);
4281 
4282         mov(tmp3, 0x0001000100010001);
4283       BIND(CH1_LOOP);
4284         ldr(ch2, Address(str2, cnt2_neg));
4285         eor(ch2, ch1, ch2);
4286         sub(tmp1, ch2, tmp3);
4287         orr(tmp2, ch2, 0x7fff7fff7fff7fff);
4288         bics(tmp1, tmp1, tmp2);
4289         br(NE, HAS_ZERO);
4290         adds(cnt2_neg, cnt2_neg, 8);
4291         br(LT, CH1_LOOP);
4292 
4293         cmp(cnt2_neg, 8);
4294         mov(cnt2_neg, 0);
4295         br(LT, CH1_LOOP);
4296         b(NOMATCH);
4297 
4298       BIND(HAS_ZERO);
4299         rev(tmp1, tmp1);
4300         clz(tmp1, tmp1);
4301         add(cnt2_neg, cnt2_neg, tmp1, LSR, 3);
4302         b(MATCH);
4303 
4304       BIND(DO1_SHORT);
4305         mov(result_tmp, cnt2);
4306         lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4307         sub(cnt2_neg, zr, cnt2, LSL, 1);
4308       BIND(DO1_LOOP);
4309         ldrh(ch2, Address(str2, cnt2_neg));
4310         cmpw(ch1, ch2);
4311         br(EQ, MATCH);
4312         adds(cnt2_neg, cnt2_neg, 2);
4313         br(LT, DO1_LOOP);
4314     }
4315   }
4316   BIND(NOMATCH);
4317     mov(result, -1);
4318     b(DONE);
4319   BIND(MATCH);
4320     add(result, result_tmp, cnt2_neg, ASR, 1);
4321   BIND(DONE);
4322 }
4323 
4324 // Compare strings.
4325 void MacroAssembler::string_compare(Register str1, Register str2,
4326                                     Register cnt1, Register cnt2, Register result,
4327                                     Register tmp1) {
4328   Label LENGTH_DIFF, DONE, SHORT_LOOP, SHORT_STRING,
4329     NEXT_WORD, DIFFERENCE;
4330 
4331   BLOCK_COMMENT("string_compare {");
4332 
4333   // Compute the minimum of the string lengths and save the difference.
4334   subsw(tmp1, cnt1, cnt2);
4335   cselw(cnt2, cnt1, cnt2, Assembler::LE); // min
4336 
4337   // A very short string
4338   cmpw(cnt2, 4);
4339   br(Assembler::LT, SHORT_STRING);
4340 
4341   // Check if the strings start at the same location.
4342   cmp(str1, str2);
4343   br(Assembler::EQ, LENGTH_DIFF);
4344 
4345   // Compare longwords
4346   {
4347     subw(cnt2, cnt2, 4); // The last longword is a special case
4348 
4349     // Move both string pointers to the last longword of their
4350     // strings, negate the remaining count, and convert it to bytes.
4351     lea(str1, Address(str1, cnt2, Address::uxtw(1)));
4352     lea(str2, Address(str2, cnt2, Address::uxtw(1)));
4353     sub(cnt2, zr, cnt2, LSL, 1);
4354 
4355     // Loop, loading longwords and comparing them into rscratch2.
4356     bind(NEXT_WORD);
4357     ldr(result, Address(str1, cnt2));
4358     ldr(cnt1, Address(str2, cnt2));
4359     adds(cnt2, cnt2, wordSize);
4360     eor(rscratch2, result, cnt1);
4361     cbnz(rscratch2, DIFFERENCE);
4362     br(Assembler::LT, NEXT_WORD);
4363 
4364     // Last longword.  In the case where length == 4 we compare the
4365     // same longword twice, but that's still faster than another
4366     // conditional branch.
4367 
4368     ldr(result, Address(str1));
4369     ldr(cnt1, Address(str2));
4370     eor(rscratch2, result, cnt1);
4371     cbz(rscratch2, LENGTH_DIFF);
4372 
4373     // Find the first different characters in the longwords and
4374     // compute their difference.
4375     bind(DIFFERENCE);
4376     rev(rscratch2, rscratch2);
4377     clz(rscratch2, rscratch2);
4378     andr(rscratch2, rscratch2, -16);
4379     lsrv(result, result, rscratch2);
4380     uxthw(result, result);
4381     lsrv(cnt1, cnt1, rscratch2);
4382     uxthw(cnt1, cnt1);
4383     subw(result, result, cnt1);
4384     b(DONE);
4385   }
4386 
4387   bind(SHORT_STRING);
4388   // Is the minimum length zero?
4389   cbz(cnt2, LENGTH_DIFF);
4390 
4391   bind(SHORT_LOOP);
4392   load_unsigned_short(result, Address(post(str1, 2)));
4393   load_unsigned_short(cnt1, Address(post(str2, 2)));
4394   subw(result, result, cnt1);
4395   cbnz(result, DONE);
4396   sub(cnt2, cnt2, 1);
4397   cbnz(cnt2, SHORT_LOOP);
4398 
4399   // Strings are equal up to min length.  Return the length difference.
4400   bind(LENGTH_DIFF);
4401   mov(result, tmp1);
4402 
4403   // That's it
4404   bind(DONE);
4405 
4406   BLOCK_COMMENT("} string_compare");
4407 }
4408 
4409 
4410 void MacroAssembler::string_equals(Register str1, Register str2,
4411                                    Register cnt, Register result,
4412                                    Register tmp1) {
4413   Label SAME_CHARS, DONE, SHORT_LOOP, SHORT_STRING,
4414     NEXT_WORD;
4415 
4416   const Register tmp2 = rscratch1;
4417   assert_different_registers(str1, str2, cnt, result, tmp1, tmp2, rscratch2);
4418 
4419   BLOCK_COMMENT("string_equals {");
4420 
4421   // Start by assuming that the strings are not equal.
4422   mov(result, zr);
4423 
4424   // A very short string
4425   cmpw(cnt, 4);
4426   br(Assembler::LT, SHORT_STRING);
4427 
4428   // Check if the strings start at the same location.
4429   cmp(str1, str2);
4430   br(Assembler::EQ, SAME_CHARS);
4431 
4432   // Compare longwords
4433   {
4434     subw(cnt, cnt, 4); // The last longword is a special case
4435 
4436     // Move both string pointers to the last longword of their
4437     // strings, negate the remaining count, and convert it to bytes.
4438     lea(str1, Address(str1, cnt, Address::uxtw(1)));
4439     lea(str2, Address(str2, cnt, Address::uxtw(1)));
4440     sub(cnt, zr, cnt, LSL, 1);
4441 
4442     // Loop, loading longwords and comparing them into rscratch2.
4443     bind(NEXT_WORD);
4444     ldr(tmp1, Address(str1, cnt));
4445     ldr(tmp2, Address(str2, cnt));
4446     adds(cnt, cnt, wordSize);
4447     eor(rscratch2, tmp1, tmp2);
4448     cbnz(rscratch2, DONE);
4449     br(Assembler::LT, NEXT_WORD);
4450 
4451     // Last longword.  In the case where length == 4 we compare the
4452     // same longword twice, but that's still faster than another
4453     // conditional branch.
4454 
4455     ldr(tmp1, Address(str1));
4456     ldr(tmp2, Address(str2));
4457     eor(rscratch2, tmp1, tmp2);
4458     cbz(rscratch2, SAME_CHARS);
4459     b(DONE);
4460   }
4461 
4462   bind(SHORT_STRING);
4463   // Is the length zero?
4464   cbz(cnt, SAME_CHARS);
4465 
4466   bind(SHORT_LOOP);
4467   load_unsigned_short(tmp1, Address(post(str1, 2)));
4468   load_unsigned_short(tmp2, Address(post(str2, 2)));
4469   subw(tmp1, tmp1, tmp2);
4470   cbnz(tmp1, DONE);
4471   sub(cnt, cnt, 1);
4472   cbnz(cnt, SHORT_LOOP);
4473 
4474   // Strings are equal.
4475   bind(SAME_CHARS);
4476   mov(result, true);
4477 
4478   // That's it
4479   bind(DONE);
4480 
4481   BLOCK_COMMENT("} string_equals");
4482 }
4483 
4484 // Compare char[] arrays aligned to 4 bytes
4485 void MacroAssembler::char_arrays_equals(Register ary1, Register ary2,
4486                                         Register result, Register tmp1)
4487 {
4488   Register cnt1 = rscratch1;
4489   Register cnt2 = rscratch2;
4490   Register tmp2 = rscratch2;
4491 
4492   Label SAME, DIFFER, NEXT, TAIL03, TAIL01;
4493 
4494   int length_offset  = arrayOopDesc::length_offset_in_bytes();
4495   int base_offset    = arrayOopDesc::base_offset_in_bytes(T_CHAR);
4496 
4497   BLOCK_COMMENT("char_arrays_equals  {");
4498 
4499     // different until proven equal
4500     mov(result, false);
4501 
4502     // same array?
4503     cmp(ary1, ary2);
4504     br(Assembler::EQ, SAME);
4505 
4506     // ne if either null
4507     cbz(ary1, DIFFER);
4508     cbz(ary2, DIFFER);
4509 
4510     // lengths ne?
4511     ldrw(cnt1, Address(ary1, length_offset));
4512     ldrw(cnt2, Address(ary2, length_offset));
4513     cmp(cnt1, cnt2);
4514     br(Assembler::NE, DIFFER);
4515 
4516     lea(ary1, Address(ary1, base_offset));
4517     lea(ary2, Address(ary2, base_offset));
4518 
4519     subs(cnt1, cnt1, 4);
4520     br(LT, TAIL03);
4521 
4522   BIND(NEXT);
4523     ldr(tmp1, Address(post(ary1, 8)));
4524     ldr(tmp2, Address(post(ary2, 8)));
4525     subs(cnt1, cnt1, 4);
4526     eor(tmp1, tmp1, tmp2);
4527     cbnz(tmp1, DIFFER);
4528     br(GE, NEXT);
4529 
4530   BIND(TAIL03);  // 0-3 chars left, cnt1 = #chars left - 4
4531     tst(cnt1, 0b10);
4532     br(EQ, TAIL01);
4533     ldrw(tmp1, Address(post(ary1, 4)));
4534     ldrw(tmp2, Address(post(ary2, 4)));
4535     cmp(tmp1, tmp2);
4536     br(NE, DIFFER);
4537   BIND(TAIL01);  // 0-1 chars left
4538     tst(cnt1, 0b01);
4539     br(EQ, SAME);
4540     ldrh(tmp1, ary1);
4541     ldrh(tmp2, ary2);
4542     cmp(tmp1, tmp2);
4543     br(NE, DIFFER);
4544 
4545   BIND(SAME);
4546     mov(result, true);
4547   BIND(DIFFER); // result already set
4548 
4549   BLOCK_COMMENT("} char_arrays_equals");
4550 }
4551 
4552 // encode char[] to byte[] in ISO_8859_1
4553 void MacroAssembler::encode_iso_array(Register src, Register dst,
4554                       Register len, Register result,
4555                       FloatRegister Vtmp1, FloatRegister Vtmp2,
4556                       FloatRegister Vtmp3, FloatRegister Vtmp4)
4557 {
4558     Label DONE, NEXT_32, LOOP_8, NEXT_8, LOOP_1, NEXT_1;
4559     Register tmp1 = rscratch1;
4560 
4561       mov(result, len); // Save initial len
4562 
4563 #ifndef BUILTIN_SIM
4564       subs(len, len, 32);
4565       br(LT, LOOP_8);
4566 
4567 // The following code uses the SIMD 'uqxtn' and 'uqxtn2' instructions
4568 // to convert chars to bytes. These set the 'QC' bit in the FPSR if
4569 // any char could not fit in a byte, so clear the FPSR so we can test it.
4570       clear_fpsr();
4571 
4572     BIND(NEXT_32);
4573       ld1(Vtmp1, Vtmp2, Vtmp3, Vtmp4, T8H, src);
4574       uqxtn(Vtmp1, T8B, Vtmp1, T8H);  // uqxtn  - write bottom half
4575       uqxtn(Vtmp1, T16B, Vtmp2, T8H); // uqxtn2 - write top half
4576       uqxtn(Vtmp2, T8B, Vtmp3, T8H);
4577       uqxtn(Vtmp2, T16B, Vtmp4, T8H); // uqxtn2
4578       get_fpsr(tmp1);
4579       cbnzw(tmp1, LOOP_8);
4580       st1(Vtmp1, Vtmp2, T16B, post(dst, 32));
4581       subs(len, len, 32);
4582       add(src, src, 64);
4583       br(GE, NEXT_32);
4584 
4585     BIND(LOOP_8);
4586       adds(len, len, 32-8);
4587       br(LT, LOOP_1);
4588       clear_fpsr(); // QC may be set from loop above, clear again
4589     BIND(NEXT_8);
4590       ld1(Vtmp1, T8H, src);
4591       uqxtn(Vtmp1, T8B, Vtmp1, T8H);
4592       get_fpsr(tmp1);
4593       cbnzw(tmp1, LOOP_1);
4594       st1(Vtmp1, T8B, post(dst, 8));
4595       subs(len, len, 8);
4596       add(src, src, 16);
4597       br(GE, NEXT_8);
4598 
4599     BIND(LOOP_1);
4600       adds(len, len, 8);
4601       br(LE, DONE);
4602 #else
4603       cbz(len, DONE);
4604 #endif
4605     BIND(NEXT_1);
4606       ldrh(tmp1, Address(post(src, 2)));
4607       tst(tmp1, 0xff00);
4608       br(NE, DONE);
4609       strb(tmp1, Address(post(dst, 1)));
4610       subs(len, len, 1);
4611       br(GT, NEXT_1);
4612 
4613     BIND(DONE);
4614       sub(result, result, len); // Return index where we stopped
4615 }