1 /*
   2  * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2014, 2024, 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 "asm/assembler.hpp"
  27 #include "asm/assembler.inline.hpp"
  28 #include "ci/ciEnv.hpp"
  29 #include "ci/ciInlineKlass.hpp"
  30 #include "code/compiledIC.hpp"
  31 #include "compiler/compileTask.hpp"
  32 #include "compiler/disassembler.hpp"
  33 #include "compiler/oopMap.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/barrierSetAssembler.hpp"
  36 #include "gc/shared/cardTableBarrierSet.hpp"
  37 #include "gc/shared/cardTable.hpp"
  38 #include "gc/shared/collectedHeap.hpp"
  39 #include "gc/shared/tlab_globals.hpp"
  40 #include "interpreter/bytecodeHistogram.hpp"
  41 #include "interpreter/interpreter.hpp"
  42 #include "interpreter/interpreterRuntime.hpp"
  43 #include "jvm.h"
  44 #include "memory/resourceArea.hpp"
  45 #include "memory/universe.hpp"
  46 #include "nativeInst_aarch64.hpp"
  47 #include "oops/accessDecorators.hpp"
  48 #include "oops/compressedKlass.inline.hpp"
  49 #include "oops/compressedOops.inline.hpp"
  50 #include "oops/klass.inline.hpp"
  51 #include "oops/resolvedFieldEntry.hpp"
  52 #include "runtime/arguments.hpp"
  53 #include "runtime/continuation.hpp"
  54 #include "runtime/globals.hpp"
  55 #include "runtime/icache.hpp"
  56 #include "runtime/interfaceSupport.inline.hpp"
  57 #include "runtime/javaThread.hpp"
  58 #include "runtime/jniHandles.inline.hpp"
  59 #include "runtime/sharedRuntime.hpp"
  60 #include "runtime/signature_cc.hpp"
  61 #include "runtime/stubRoutines.hpp"
  62 #include "utilities/globalDefinitions.hpp"
  63 #include "utilities/integerCast.hpp"
  64 #include "utilities/powerOfTwo.hpp"
  65 #include "vmreg_aarch64.inline.hpp"
  66 #ifdef COMPILER1
  67 #include "c1/c1_LIRAssembler.hpp"
  68 #endif
  69 #ifdef COMPILER2
  70 #include "oops/oop.hpp"
  71 #include "opto/compile.hpp"
  72 #include "opto/node.hpp"
  73 #include "opto/output.hpp"
  74 #endif
  75 
  76 #include <sys/types.h>
  77 
  78 #ifdef PRODUCT
  79 #define BLOCK_COMMENT(str) /* nothing */
  80 #else
  81 #define BLOCK_COMMENT(str) block_comment(str)
  82 #endif
  83 #define STOP(str) stop(str);
  84 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  85 
  86 #ifdef ASSERT
  87 extern "C" void disnm(intptr_t p);
  88 #endif
  89 // Target-dependent relocation processing
  90 //
  91 // Instruction sequences whose target may need to be retrieved or
  92 // patched are distinguished by their leading instruction, sorting
  93 // them into three main instruction groups and related subgroups.
  94 //
  95 // 1) Branch, Exception and System (insn count = 1)
  96 //    1a) Unconditional branch (immediate):
  97 //      b/bl imm19
  98 //    1b) Compare & branch (immediate):
  99 //      cbz/cbnz Rt imm19
 100 //    1c) Test & branch (immediate):
 101 //      tbz/tbnz Rt imm14
 102 //    1d) Conditional branch (immediate):
 103 //      b.cond imm19
 104 //
 105 // 2) Loads and Stores (insn count = 1)
 106 //    2a) Load register literal:
 107 //      ldr Rt imm19
 108 //
 109 // 3) Data Processing Immediate (insn count = 2 or 3)
 110 //    3a) PC-rel. addressing
 111 //      adr/adrp Rx imm21; ldr/str Ry Rx  #imm12
 112 //      adr/adrp Rx imm21; add Ry Rx  #imm12
 113 //      adr/adrp Rx imm21; movk Rx #imm16<<32; ldr/str Ry, [Rx, #offset_in_page]
 114 //      adr/adrp Rx imm21
 115 //      adr/adrp Rx imm21; movk Rx #imm16<<32
 116 //      adr/adrp Rx imm21; movk Rx #imm16<<32; add Ry, Rx, #offset_in_page
 117 //      The latter form can only happen when the target is an
 118 //      ExternalAddress, and (by definition) ExternalAddresses don't
 119 //      move. Because of that property, there is never any need to
 120 //      patch the last of the three instructions. However,
 121 //      MacroAssembler::target_addr_for_insn takes all three
 122 //      instructions into account and returns the correct address.
 123 //    3b) Move wide (immediate)
 124 //      movz Rx #imm16; movk Rx #imm16 << 16; movk Rx #imm16 << 32;
 125 //
 126 // A switch on a subset of the instruction's bits provides an
 127 // efficient dispatch to these subcases.
 128 //
 129 // insn[28:26] -> main group ('x' == don't care)
 130 //   00x -> UNALLOCATED
 131 //   100 -> Data Processing Immediate
 132 //   101 -> Branch, Exception and System
 133 //   x1x -> Loads and Stores
 134 //
 135 // insn[30:25] -> subgroup ('_' == group, 'x' == don't care).
 136 // n.b. in some cases extra bits need to be checked to verify the
 137 // instruction is as expected
 138 //
 139 // 1) ... xx101x Branch, Exception and System
 140 //   1a)  00___x Unconditional branch (immediate)
 141 //   1b)  01___0 Compare & branch (immediate)
 142 //   1c)  01___1 Test & branch (immediate)
 143 //   1d)  10___0 Conditional branch (immediate)
 144 //        other  Should not happen
 145 //
 146 // 2) ... xxx1x0 Loads and Stores
 147 //   2a)  xx1__00 Load/Store register (insn[28] == 1 && insn[24] == 0)
 148 //   2aa) x01__00 Load register literal (i.e. requires insn[29] == 0)
 149 //                strictly should be 64 bit non-FP/SIMD i.e.
 150 //       0101_000 (i.e. requires insn[31:24] == 01011000)
 151 //
 152 // 3) ... xx100x Data Processing Immediate
 153 //   3a)  xx___00 PC-rel. addressing (n.b. requires insn[24] == 0)
 154 //   3b)  xx___101 Move wide (immediate) (n.b. requires insn[24:23] == 01)
 155 //                 strictly should be 64 bit movz #imm16<<0
 156 //       110___10100 (i.e. requires insn[31:21] == 11010010100)
 157 //
 158 
 159 static uint32_t insn_at(address insn_addr, int n) {
 160   return ((uint32_t*)insn_addr)[n];
 161 }
 162 
 163 template<typename T>
 164 class RelocActions : public AllStatic {
 165 
 166 public:
 167 
 168   static int ALWAYSINLINE run(address insn_addr, address &target) {
 169     int instructions = 1;
 170     uint32_t insn = insn_at(insn_addr, 0);
 171 
 172     uint32_t dispatch = Instruction_aarch64::extract(insn, 30, 25);
 173     switch(dispatch) {
 174       case 0b001010:
 175       case 0b001011: {
 176         instructions = T::unconditionalBranch(insn_addr, target);
 177         break;
 178       }
 179       case 0b101010:   // Conditional branch (immediate)
 180       case 0b011010: { // Compare & branch (immediate)
 181         instructions = T::conditionalBranch(insn_addr, target);
 182         break;
 183       }
 184       case 0b011011: {
 185         instructions = T::testAndBranch(insn_addr, target);
 186         break;
 187       }
 188       case 0b001100:
 189       case 0b001110:
 190       case 0b011100:
 191       case 0b011110:
 192       case 0b101100:
 193       case 0b101110:
 194       case 0b111100:
 195       case 0b111110: {
 196         // load/store
 197         if ((Instruction_aarch64::extract(insn, 29, 24) & 0b111011) == 0b011000) {
 198           // Load register (literal)
 199           instructions = T::loadStore(insn_addr, target);
 200           break;
 201         } else {
 202           // nothing to do
 203           assert(target == nullptr, "did not expect to relocate target for polling page load");
 204         }
 205         break;
 206       }
 207       case 0b001000:
 208       case 0b011000:
 209       case 0b101000:
 210       case 0b111000: {
 211         // adr/adrp
 212         assert(Instruction_aarch64::extract(insn, 28, 24) == 0b10000, "must be");
 213         int shift = Instruction_aarch64::extract(insn, 31, 31);
 214         if (shift) {
 215           uint32_t insn2 = insn_at(insn_addr, 1);
 216           if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
 217               Instruction_aarch64::extract(insn, 4, 0) ==
 218               Instruction_aarch64::extract(insn2, 9, 5)) {
 219             instructions = T::adrp(insn_addr, target, T::adrpMem);
 220           } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
 221                      Instruction_aarch64::extract(insn, 4, 0) ==
 222                      Instruction_aarch64::extract(insn2, 4, 0)) {
 223             instructions = T::adrp(insn_addr, target, T::adrpAdd);
 224           } else if (Instruction_aarch64::extract(insn2, 31, 21) == 0b11110010110 &&
 225                      Instruction_aarch64::extract(insn, 4, 0) ==
 226                      Instruction_aarch64::extract(insn2, 4, 0)) {
 227             instructions = T::adrp(insn_addr, target, T::adrpMovk);
 228           } else {
 229             ShouldNotReachHere();
 230           }
 231         } else {
 232           instructions = T::adr(insn_addr, target);
 233         }
 234         break;
 235       }
 236       case 0b001001:
 237       case 0b011001:
 238       case 0b101001:
 239       case 0b111001: {
 240         instructions = T::immediate(insn_addr, target);
 241         break;
 242       }
 243       default: {
 244         ShouldNotReachHere();
 245       }
 246     }
 247 
 248     T::verify(insn_addr, target);
 249     return instructions * NativeInstruction::instruction_size;
 250   }
 251 };
 252 
 253 class Patcher : public AllStatic {
 254 public:
 255   static int unconditionalBranch(address insn_addr, address &target) {
 256     intptr_t offset = (target - insn_addr) >> 2;
 257     Instruction_aarch64::spatch(insn_addr, 25, 0, offset);
 258     return 1;
 259   }
 260   static int conditionalBranch(address insn_addr, address &target) {
 261     intptr_t offset = (target - insn_addr) >> 2;
 262     Instruction_aarch64::spatch(insn_addr, 23, 5, offset);
 263     return 1;
 264   }
 265   static int testAndBranch(address insn_addr, address &target) {
 266     intptr_t offset = (target - insn_addr) >> 2;
 267     Instruction_aarch64::spatch(insn_addr, 18, 5, offset);
 268     return 1;
 269   }
 270   static int loadStore(address insn_addr, address &target) {
 271     intptr_t offset = (target - insn_addr) >> 2;
 272     Instruction_aarch64::spatch(insn_addr, 23, 5, offset);
 273     return 1;
 274   }
 275   static int adr(address insn_addr, address &target) {
 276 #ifdef ASSERT
 277     assert(Instruction_aarch64::extract(insn_at(insn_addr, 0), 28, 24) == 0b10000, "must be");
 278 #endif
 279     // PC-rel. addressing
 280     ptrdiff_t offset = target - insn_addr;
 281     int offset_lo = offset & 3;
 282     offset >>= 2;
 283     Instruction_aarch64::spatch(insn_addr, 23, 5, offset);
 284     Instruction_aarch64::patch(insn_addr, 30, 29, offset_lo);
 285     return 1;
 286   }
 287   template<typename U>
 288   static int adrp(address insn_addr, address &target, U inner) {
 289     int instructions = 1;
 290 #ifdef ASSERT
 291     assert(Instruction_aarch64::extract(insn_at(insn_addr, 0), 28, 24) == 0b10000, "must be");
 292 #endif
 293     ptrdiff_t offset = target - insn_addr;
 294     instructions = 2;
 295     precond(inner != nullptr);
 296     // Give the inner reloc a chance to modify the target.
 297     address adjusted_target = target;
 298     instructions = inner(insn_addr, adjusted_target);
 299     uintptr_t pc_page = (uintptr_t)insn_addr >> 12;
 300     uintptr_t adr_page = (uintptr_t)adjusted_target >> 12;
 301     offset = adr_page - pc_page;
 302     int offset_lo = offset & 3;
 303     offset >>= 2;
 304     Instruction_aarch64::spatch(insn_addr, 23, 5, offset);
 305     Instruction_aarch64::patch(insn_addr, 30, 29, offset_lo);
 306     return instructions;
 307   }
 308   static int adrpMem(address insn_addr, address &target) {
 309     uintptr_t dest = (uintptr_t)target;
 310     int offset_lo = dest & 0xfff;
 311     uint32_t insn2 = insn_at(insn_addr, 1);
 312     uint32_t size = Instruction_aarch64::extract(insn2, 31, 30);
 313     Instruction_aarch64::patch(insn_addr + sizeof (uint32_t), 21, 10, offset_lo >> size);
 314     guarantee(((dest >> size) << size) == dest, "misaligned target");
 315     return 2;
 316   }
 317   static int adrpAdd(address insn_addr, address &target) {
 318     uintptr_t dest = (uintptr_t)target;
 319     int offset_lo = dest & 0xfff;
 320     Instruction_aarch64::patch(insn_addr + sizeof (uint32_t), 21, 10, offset_lo);
 321     return 2;
 322   }
 323   static int adrpMovk(address insn_addr, address &target) {
 324     uintptr_t dest = uintptr_t(target);
 325     Instruction_aarch64::patch(insn_addr + sizeof (uint32_t), 20, 5, (uintptr_t)target >> 32);
 326     dest = (dest & 0xffffffffULL) | (uintptr_t(insn_addr) & 0xffff00000000ULL);
 327     target = address(dest);
 328     return 2;
 329   }
 330   static int immediate(address insn_addr, address &target) {
 331     assert(Instruction_aarch64::extract(insn_at(insn_addr, 0), 31, 21) == 0b11010010100, "must be");
 332     uint64_t dest = (uint64_t)target;
 333     // Move wide constant
 334     assert(nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 335     assert(nativeInstruction_at(insn_addr+8)->is_movk(), "wrong insns in patch");
 336     Instruction_aarch64::patch(insn_addr, 20, 5, dest & 0xffff);
 337     Instruction_aarch64::patch(insn_addr+4, 20, 5, (dest >>= 16) & 0xffff);
 338     Instruction_aarch64::patch(insn_addr+8, 20, 5, (dest >>= 16) & 0xffff);
 339     return 3;
 340   }
 341   static void verify(address insn_addr, address &target) {
 342 #ifdef ASSERT
 343     address address_is = MacroAssembler::target_addr_for_insn(insn_addr);
 344     if (!(address_is == target)) {
 345       tty->print_cr("%p at %p should be %p", address_is, insn_addr, target);
 346       disnm((intptr_t)insn_addr);
 347       assert(address_is == target, "should be");
 348     }
 349 #endif
 350   }
 351 };
 352 
 353 // If insn1 and insn2 use the same register to form an address, either
 354 // by an offsetted LDR or a simple ADD, return the offset. If the
 355 // second instruction is an LDR, the offset may be scaled.
 356 static bool offset_for(uint32_t insn1, uint32_t insn2, ptrdiff_t &byte_offset) {
 357   if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
 358       Instruction_aarch64::extract(insn1, 4, 0) ==
 359       Instruction_aarch64::extract(insn2, 9, 5)) {
 360     // Load/store register (unsigned immediate)
 361     byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 362     uint32_t size = Instruction_aarch64::extract(insn2, 31, 30);
 363     byte_offset <<= size;
 364     return true;
 365   } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
 366              Instruction_aarch64::extract(insn1, 4, 0) ==
 367              Instruction_aarch64::extract(insn2, 4, 0)) {
 368     // add (immediate)
 369     byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 370     return true;
 371   }
 372   return false;
 373 }
 374 
 375 class AArch64Decoder : public AllStatic {
 376 public:
 377 
 378   static int loadStore(address insn_addr, address &target) {
 379     intptr_t offset = Instruction_aarch64::sextract(insn_at(insn_addr, 0), 23, 5);
 380     target = insn_addr + (offset << 2);
 381     return 1;
 382   }
 383   static int unconditionalBranch(address insn_addr, address &target) {
 384     intptr_t offset = Instruction_aarch64::sextract(insn_at(insn_addr, 0), 25, 0);
 385     target = insn_addr + (offset << 2);
 386     return 1;
 387   }
 388   static int conditionalBranch(address insn_addr, address &target) {
 389     intptr_t offset = Instruction_aarch64::sextract(insn_at(insn_addr, 0), 23, 5);
 390     target = address(((uint64_t)insn_addr + (offset << 2)));
 391     return 1;
 392   }
 393   static int testAndBranch(address insn_addr, address &target) {
 394     intptr_t offset = Instruction_aarch64::sextract(insn_at(insn_addr, 0), 18, 5);
 395     target = address(((uint64_t)insn_addr + (offset << 2)));
 396     return 1;
 397   }
 398   static int adr(address insn_addr, address &target) {
 399     // PC-rel. addressing
 400     uint32_t insn = insn_at(insn_addr, 0);
 401     intptr_t offset = Instruction_aarch64::extract(insn, 30, 29);
 402     offset |= Instruction_aarch64::sextract(insn, 23, 5) << 2;
 403     target = address((uint64_t)insn_addr + offset);
 404     return 1;
 405   }
 406   template<typename U>
 407   static int adrp(address insn_addr, address &target, U inner) {
 408     uint32_t insn = insn_at(insn_addr, 0);
 409     assert(Instruction_aarch64::extract(insn, 28, 24) == 0b10000, "must be");
 410     intptr_t offset = Instruction_aarch64::extract(insn, 30, 29);
 411     offset |= Instruction_aarch64::sextract(insn, 23, 5) << 2;
 412     int shift = 12;
 413     offset <<= shift;
 414     uint64_t target_page = ((uint64_t)insn_addr) + offset;
 415     target_page &= ((uint64_t)-1) << shift;
 416     target = address(target_page);
 417     precond(inner != nullptr);
 418     inner(insn_addr, target);
 419     return 2;
 420   }
 421   static int adrpMem(address insn_addr, address &target) {
 422     uint32_t insn2 = insn_at(insn_addr, 1);
 423     // Load/store register (unsigned immediate)
 424     ptrdiff_t byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 425     uint32_t size = Instruction_aarch64::extract(insn2, 31, 30);
 426     byte_offset <<= size;
 427     target += byte_offset;
 428     return 2;
 429   }
 430   static int adrpAdd(address insn_addr, address &target) {
 431     uint32_t insn2 = insn_at(insn_addr, 1);
 432     // add (immediate)
 433     ptrdiff_t byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 434     target += byte_offset;
 435     return 2;
 436   }
 437   static int adrpMovk(address insn_addr, address &target) {
 438     uint32_t insn2 = insn_at(insn_addr, 1);
 439     uint64_t dest = uint64_t(target);
 440     dest = (dest & 0xffff0000ffffffff) |
 441       ((uint64_t)Instruction_aarch64::extract(insn2, 20, 5) << 32);
 442     target = address(dest);
 443 
 444     // We know the destination 4k page. Maybe we have a third
 445     // instruction.
 446     uint32_t insn = insn_at(insn_addr, 0);
 447     uint32_t insn3 = insn_at(insn_addr, 2);
 448     ptrdiff_t byte_offset;
 449     if (offset_for(insn, insn3, byte_offset)) {
 450       target += byte_offset;
 451       return 3;
 452     } else {
 453       return 2;
 454     }
 455   }
 456   static int immediate(address insn_addr, address &target) {
 457     uint32_t *insns = (uint32_t *)insn_addr;
 458     assert(Instruction_aarch64::extract(insns[0], 31, 21) == 0b11010010100, "must be");
 459     // Move wide constant: movz, movk, movk.  See movptr().
 460     assert(nativeInstruction_at(insns+1)->is_movk(), "wrong insns in patch");
 461     assert(nativeInstruction_at(insns+2)->is_movk(), "wrong insns in patch");
 462     target = address(uint64_t(Instruction_aarch64::extract(insns[0], 20, 5))
 463                   + (uint64_t(Instruction_aarch64::extract(insns[1], 20, 5)) << 16)
 464                   + (uint64_t(Instruction_aarch64::extract(insns[2], 20, 5)) << 32));
 465     assert(nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 466     assert(nativeInstruction_at(insn_addr+8)->is_movk(), "wrong insns in patch");
 467     return 3;
 468   }
 469   static void verify(address insn_addr, address &target) {
 470   }
 471 };
 472 
 473 address MacroAssembler::target_addr_for_insn(address insn_addr) {
 474   address target;
 475   RelocActions<AArch64Decoder>::run(insn_addr, target);
 476   return target;
 477 }
 478 
 479 // Patch any kind of instruction; there may be several instructions.
 480 // Return the total length (in bytes) of the instructions.
 481 int MacroAssembler::pd_patch_instruction_size(address insn_addr, address target) {
 482   MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
 483   return RelocActions<Patcher>::run(insn_addr, target);
 484 }
 485 
 486 int MacroAssembler::patch_oop(address insn_addr, address o) {
 487   int instructions;
 488   unsigned insn = *(unsigned*)insn_addr;
 489   assert(nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 490 
 491   MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
 492 
 493   // OOPs are either narrow (32 bits) or wide (48 bits).  We encode
 494   // narrow OOPs by setting the upper 16 bits in the first
 495   // instruction.
 496   if (Instruction_aarch64::extract(insn, 31, 21) == 0b11010010101) {
 497     // Move narrow OOP
 498     uint32_t n = CompressedOops::narrow_oop_value(cast_to_oop(o));
 499     Instruction_aarch64::patch(insn_addr, 20, 5, n >> 16);
 500     Instruction_aarch64::patch(insn_addr+4, 20, 5, n & 0xffff);
 501     instructions = 2;
 502   } else {
 503     // Move wide OOP
 504     assert(nativeInstruction_at(insn_addr+8)->is_movk(), "wrong insns in patch");
 505     uintptr_t dest = (uintptr_t)o;
 506     Instruction_aarch64::patch(insn_addr, 20, 5, dest & 0xffff);
 507     Instruction_aarch64::patch(insn_addr+4, 20, 5, (dest >>= 16) & 0xffff);
 508     Instruction_aarch64::patch(insn_addr+8, 20, 5, (dest >>= 16) & 0xffff);
 509     instructions = 3;
 510   }
 511   return instructions * NativeInstruction::instruction_size;
 512 }
 513 
 514 void MacroAssembler::safepoint_poll(Label& slow_path, bool at_return, bool in_nmethod, Register tmp) {
 515   ldr(tmp, Address(rthread, JavaThread::polling_word_offset()));
 516   if (at_return) {
 517     // Note that when in_nmethod is set, the stack pointer is incremented before the poll. Therefore,
 518     // we may safely use the sp instead to perform the stack watermark check.
 519     cmp(in_nmethod ? sp : rfp, tmp);
 520     br(Assembler::HI, slow_path);
 521   } else {
 522     tbnz(tmp, log2i_exact(SafepointMechanism::poll_bit()), slow_path);
 523   }
 524 }
 525 
 526 void MacroAssembler::rt_call(address dest, Register tmp) {
 527   CodeBlob *cb = CodeCache::find_blob(dest);
 528   if (cb) {
 529     far_call(RuntimeAddress(dest));
 530   } else {
 531     lea(tmp, RuntimeAddress(dest));
 532     blr(tmp);
 533   }
 534 }
 535 
 536 void MacroAssembler::push_cont_fastpath(Register java_thread) {
 537   if (!Continuations::enabled()) return;
 538   Label done;
 539   ldr(rscratch1, Address(java_thread, JavaThread::cont_fastpath_offset()));
 540   cmp(sp, rscratch1);
 541   br(Assembler::LS, done);
 542   mov(rscratch1, sp); // we can't use sp as the source in str
 543   str(rscratch1, Address(java_thread, JavaThread::cont_fastpath_offset()));
 544   bind(done);
 545 }
 546 
 547 void MacroAssembler::pop_cont_fastpath(Register java_thread) {
 548   if (!Continuations::enabled()) return;
 549   Label done;
 550   ldr(rscratch1, Address(java_thread, JavaThread::cont_fastpath_offset()));
 551   cmp(sp, rscratch1);
 552   br(Assembler::LO, done);
 553   str(zr, Address(java_thread, JavaThread::cont_fastpath_offset()));
 554   bind(done);
 555 }
 556 
 557 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 558   // we must set sp to zero to clear frame
 559   str(zr, Address(rthread, JavaThread::last_Java_sp_offset()));
 560 
 561   // must clear fp, so that compiled frames are not confused; it is
 562   // possible that we need it only for debugging
 563   if (clear_fp) {
 564     str(zr, Address(rthread, JavaThread::last_Java_fp_offset()));
 565   }
 566 
 567   // Always clear the pc because it could have been set by make_walkable()
 568   str(zr, Address(rthread, JavaThread::last_Java_pc_offset()));
 569 }
 570 
 571 // Calls to C land
 572 //
 573 // When entering C land, the rfp, & resp of the last Java frame have to be recorded
 574 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
 575 // has to be reset to 0. This is required to allow proper stack traversal.
 576 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 577                                          Register last_java_fp,
 578                                          Register last_java_pc,
 579                                          Register scratch) {
 580 
 581   if (last_java_pc->is_valid()) {
 582       str(last_java_pc, Address(rthread,
 583                                 JavaThread::frame_anchor_offset()
 584                                 + JavaFrameAnchor::last_Java_pc_offset()));
 585     }
 586 
 587   // determine last_java_sp register
 588   if (last_java_sp == sp) {
 589     mov(scratch, sp);
 590     last_java_sp = scratch;
 591   } else if (!last_java_sp->is_valid()) {
 592     last_java_sp = esp;
 593   }
 594 
 595   // last_java_fp is optional
 596   if (last_java_fp->is_valid()) {
 597     str(last_java_fp, Address(rthread, JavaThread::last_Java_fp_offset()));
 598   }
 599 
 600   // We must set sp last.
 601   str(last_java_sp, Address(rthread, JavaThread::last_Java_sp_offset()));
 602 }
 603 
 604 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 605                                          Register last_java_fp,
 606                                          address  last_java_pc,
 607                                          Register scratch) {
 608   assert(last_java_pc != nullptr, "must provide a valid PC");
 609 
 610   adr(scratch, last_java_pc);
 611   str(scratch, Address(rthread,
 612                        JavaThread::frame_anchor_offset()
 613                        + JavaFrameAnchor::last_Java_pc_offset()));
 614 
 615   set_last_Java_frame(last_java_sp, last_java_fp, noreg, scratch);
 616 }
 617 
 618 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 619                                          Register last_java_fp,
 620                                          Label &L,
 621                                          Register scratch) {
 622   if (L.is_bound()) {
 623     set_last_Java_frame(last_java_sp, last_java_fp, target(L), scratch);
 624   } else {
 625     InstructionMark im(this);
 626     L.add_patch_at(code(), locator());
 627     set_last_Java_frame(last_java_sp, last_java_fp, pc() /* Patched later */, scratch);
 628   }
 629 }
 630 
 631 static inline bool target_needs_far_branch(address addr) {
 632   if (AOTCodeCache::is_on_for_dump()) {
 633     return true;
 634   }
 635   // codecache size <= 128M
 636   if (!MacroAssembler::far_branches()) {
 637     return false;
 638   }
 639   // codecache size > 240M
 640   if (MacroAssembler::codestub_branch_needs_far_jump()) {
 641     return true;
 642   }
 643   // codecache size: 128M..240M
 644   return !CodeCache::is_non_nmethod(addr);
 645 }
 646 
 647 void MacroAssembler::far_call(Address entry, Register tmp) {
 648   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
 649   assert(CodeCache::find_blob(entry.target()) != nullptr,
 650          "destination of far call not found in code cache");
 651   assert(entry.rspec().type() == relocInfo::external_word_type
 652          || entry.rspec().type() == relocInfo::runtime_call_type
 653          || entry.rspec().type() == relocInfo::none, "wrong entry relocInfo type");
 654   if (target_needs_far_branch(entry.target())) {
 655     uint64_t offset;
 656     // We can use ADRP here because we know that the total size of
 657     // the code cache cannot exceed 2Gb (ADRP limit is 4GB).
 658     adrp(tmp, entry, offset);
 659     add(tmp, tmp, offset);
 660     blr(tmp);
 661   } else {
 662     bl(entry);
 663   }
 664 }
 665 
 666 int MacroAssembler::far_jump(Address entry, Register tmp) {
 667   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
 668   assert(CodeCache::find_blob(entry.target()) != nullptr,
 669          "destination of far call not found in code cache");
 670   assert(entry.rspec().type() == relocInfo::external_word_type
 671          || entry.rspec().type() == relocInfo::runtime_call_type
 672          || entry.rspec().type() == relocInfo::none, "wrong entry relocInfo type");
 673   address start = pc();
 674   if (target_needs_far_branch(entry.target())) {
 675     uint64_t offset;
 676     // We can use ADRP here because we know that the total size of
 677     // the code cache cannot exceed 2Gb (ADRP limit is 4GB).
 678     adrp(tmp, entry, offset);
 679     add(tmp, tmp, offset);
 680     br(tmp);
 681   } else {
 682     b(entry);
 683   }
 684   return pc() - start;
 685 }
 686 
 687 void MacroAssembler::reserved_stack_check() {
 688     // testing if reserved zone needs to be enabled
 689     Label no_reserved_zone_enabling;
 690 
 691     ldr(rscratch1, Address(rthread, JavaThread::reserved_stack_activation_offset()));
 692     cmp(sp, rscratch1);
 693     br(Assembler::LO, no_reserved_zone_enabling);
 694 
 695     enter();   // LR and FP are live.
 696     lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone)));
 697     mov(c_rarg0, rthread);
 698     blr(rscratch1);
 699     leave();
 700 
 701     // We have already removed our own frame.
 702     // throw_delayed_StackOverflowError will think that it's been
 703     // called by our caller.
 704     lea(rscratch1, RuntimeAddress(SharedRuntime::throw_delayed_StackOverflowError_entry()));
 705     br(rscratch1);
 706     should_not_reach_here();
 707 
 708     bind(no_reserved_zone_enabling);
 709 }
 710 
 711 static void pass_arg0(MacroAssembler* masm, Register arg) {
 712   if (c_rarg0 != arg ) {
 713     masm->mov(c_rarg0, arg);
 714   }
 715 }
 716 
 717 static void pass_arg1(MacroAssembler* masm, Register arg) {
 718   if (c_rarg1 != arg ) {
 719     masm->mov(c_rarg1, arg);
 720   }
 721 }
 722 
 723 static void pass_arg2(MacroAssembler* masm, Register arg) {
 724   if (c_rarg2 != arg ) {
 725     masm->mov(c_rarg2, arg);
 726   }
 727 }
 728 
 729 static void pass_arg3(MacroAssembler* masm, Register arg) {
 730   if (c_rarg3 != arg ) {
 731     masm->mov(c_rarg3, arg);
 732   }
 733 }
 734 
 735 void MacroAssembler::call_VM_base(Register oop_result,
 736                                   Register java_thread,
 737                                   Register last_java_sp,
 738                                   Label*   return_pc,
 739                                   address  entry_point,
 740                                   int      number_of_arguments,
 741                                   bool     check_exceptions) {
 742    // determine java_thread register
 743   if (!java_thread->is_valid()) {
 744     java_thread = rthread;
 745   }
 746 
 747   // determine last_java_sp register
 748   if (!last_java_sp->is_valid()) {
 749     last_java_sp = esp;
 750   }
 751 
 752   // debugging support
 753   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
 754   assert(java_thread == rthread, "unexpected register");
 755 #ifdef ASSERT
 756   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
 757   // if (!TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");
 758 #endif // ASSERT
 759 
 760   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
 761   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
 762 
 763   // push java thread (becomes first argument of C function)
 764 
 765   mov(c_rarg0, java_thread);
 766 
 767   // set last Java frame before call
 768   assert(last_java_sp != rfp, "can't use rfp");
 769 
 770   Label l;
 771   set_last_Java_frame(last_java_sp, rfp, return_pc != nullptr ? *return_pc : l, rscratch1);
 772 
 773   // do the call, remove parameters
 774   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments, &l);
 775 
 776   // lr could be poisoned with PAC signature during throw_pending_exception
 777   // if it was tail-call optimized by compiler, since lr is not callee-saved
 778   // reload it with proper value
 779   adr(lr, l);
 780 
 781   // reset last Java frame
 782   // Only interpreter should have to clear fp
 783   reset_last_Java_frame(true);
 784 
 785    // C++ interp handles this in the interpreter
 786   check_and_handle_popframe(java_thread);
 787   check_and_handle_earlyret(java_thread);
 788 
 789   if (check_exceptions) {
 790     // check for pending exceptions (java_thread is set upon return)
 791     ldr(rscratch1, Address(java_thread, in_bytes(Thread::pending_exception_offset())));
 792     Label ok;
 793     cbz(rscratch1, ok);
 794     lea(rscratch1, RuntimeAddress(StubRoutines::forward_exception_entry()));
 795     br(rscratch1);
 796     bind(ok);
 797   }
 798 
 799   // get oop result if there is one and reset the value in the thread
 800   if (oop_result->is_valid()) {
 801     get_vm_result_oop(oop_result, java_thread);
 802   }
 803 }
 804 
 805 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
 806   call_VM_base(oop_result, noreg, noreg, nullptr, entry_point, number_of_arguments, check_exceptions);
 807 }
 808 
 809 // Check the entry target is always reachable from any branch.
 810 static bool is_always_within_branch_range(Address entry) {
 811   if (AOTCodeCache::is_on_for_dump()) {
 812     return false;
 813   }
 814   const address target = entry.target();
 815 
 816   if (!CodeCache::contains(target)) {
 817     // We always use trampolines for callees outside CodeCache.
 818     assert(entry.rspec().type() == relocInfo::runtime_call_type, "non-runtime call of an external target");
 819     return false;
 820   }
 821 
 822   if (!MacroAssembler::far_branches()) {
 823     return true;
 824   }
 825 
 826   if (entry.rspec().type() == relocInfo::runtime_call_type) {
 827     // Runtime calls are calls of a non-compiled method (stubs, adapters).
 828     // Non-compiled methods stay forever in CodeCache.
 829     // We check whether the longest possible branch is within the branch range.
 830     assert(CodeCache::find_blob(target) != nullptr &&
 831           !CodeCache::find_blob(target)->is_nmethod(),
 832           "runtime call of compiled method");
 833     const address right_longest_branch_start = CodeCache::high_bound() - NativeInstruction::instruction_size;
 834     const address left_longest_branch_start = CodeCache::low_bound();
 835     const bool is_reachable = Assembler::reachable_from_branch_at(left_longest_branch_start, target) &&
 836                               Assembler::reachable_from_branch_at(right_longest_branch_start, target);
 837     return is_reachable;
 838   }
 839 
 840   return false;
 841 }
 842 
 843 // Maybe emit a call via a trampoline. If the code cache is small
 844 // trampolines won't be emitted.
 845 address MacroAssembler::trampoline_call(Address entry) {
 846   assert(entry.rspec().type() == relocInfo::runtime_call_type
 847          || entry.rspec().type() == relocInfo::opt_virtual_call_type
 848          || entry.rspec().type() == relocInfo::static_call_type
 849          || entry.rspec().type() == relocInfo::virtual_call_type, "wrong reloc type");
 850 
 851   address target = entry.target();
 852 
 853   if (!is_always_within_branch_range(entry)) {
 854     if (!in_scratch_emit_size()) {
 855       // We don't want to emit a trampoline if C2 is generating dummy
 856       // code during its branch shortening phase.
 857       if (entry.rspec().type() == relocInfo::runtime_call_type) {
 858         assert(CodeBuffer::supports_shared_stubs(), "must support shared stubs");
 859         code()->share_trampoline_for(entry.target(), offset());
 860       } else {
 861         address stub = emit_trampoline_stub(offset(), target);
 862         if (stub == nullptr) {
 863           postcond(pc() == badAddress);
 864           return nullptr; // CodeCache is full
 865         }
 866       }
 867     }
 868     target = pc();
 869   }
 870 
 871   address call_pc = pc();
 872   relocate(entry.rspec());
 873   bl(target);
 874 
 875   postcond(pc() != badAddress);
 876   return call_pc;
 877 }
 878 
 879 // Emit a trampoline stub for a call to a target which is too far away.
 880 //
 881 // code sequences:
 882 //
 883 // call-site:
 884 //   branch-and-link to <destination> or <trampoline stub>
 885 //
 886 // Related trampoline stub for this call site in the stub section:
 887 //   load the call target from the constant pool
 888 //   branch (LR still points to the call site above)
 889 
 890 address MacroAssembler::emit_trampoline_stub(int insts_call_instruction_offset,
 891                                              address dest) {
 892   // Max stub size: alignment nop, TrampolineStub.
 893   address stub = start_a_stub(max_trampoline_stub_size());
 894   if (stub == nullptr) {
 895     return nullptr;  // CodeBuffer::expand failed
 896   }
 897 
 898   // Create a trampoline stub relocation which relates this trampoline stub
 899   // with the call instruction at insts_call_instruction_offset in the
 900   // instructions code-section.
 901   align(wordSize);
 902   relocate(trampoline_stub_Relocation::spec(code()->insts()->start()
 903                                             + insts_call_instruction_offset));
 904   const int stub_start_offset = offset();
 905 
 906   // Now, create the trampoline stub's code:
 907   // - load the call
 908   // - call
 909   Label target;
 910   ldr(rscratch1, target);
 911   br(rscratch1);
 912   bind(target);
 913   assert(offset() - stub_start_offset == NativeCallTrampolineStub::data_offset,
 914          "should be");
 915   emit_int64((int64_t)dest);
 916 
 917   const address stub_start_addr = addr_at(stub_start_offset);
 918 
 919   assert(is_NativeCallTrampolineStub_at(stub_start_addr), "doesn't look like a trampoline");
 920 
 921   end_a_stub();
 922   return stub_start_addr;
 923 }
 924 
 925 int MacroAssembler::max_trampoline_stub_size() {
 926   // Max stub size: alignment nop, TrampolineStub.
 927   return NativeInstruction::instruction_size + NativeCallTrampolineStub::instruction_size;
 928 }
 929 
 930 void MacroAssembler::emit_static_call_stub() {
 931   // CompiledDirectCall::set_to_interpreted knows the
 932   // exact layout of this stub.
 933 
 934   isb();
 935   mov_metadata(rmethod, nullptr);
 936 
 937   // Jump to the entry point of the c2i stub.
 938   if (codestub_branch_needs_far_jump()) {
 939     movptr(rscratch1, 0);
 940     br(rscratch1);
 941   } else {
 942     b(pc());
 943   }
 944 }
 945 
 946 int MacroAssembler::static_call_stub_size() {
 947   // During AOT production run AOT and JIT compiled code
 948   // are used at the same time. We need this size
 949   // to be the same for both types of code.
 950   if (!codestub_branch_needs_far_jump() && !AOTCodeCache::is_on_for_use()) {
 951     // isb; movk; movz; movz; b
 952     return 5 * NativeInstruction::instruction_size;
 953   }
 954   // isb; movk; movz; movz; movk; movz; movz; br
 955   return 8 * NativeInstruction::instruction_size;
 956 }
 957 
 958 void MacroAssembler::c2bool(Register x) {
 959   // implements x == 0 ? 0 : 1
 960   // note: must only look at least-significant byte of x
 961   //       since C-style booleans are stored in one byte
 962   //       only! (was bug)
 963   tst(x, 0xff);
 964   cset(x, Assembler::NE);
 965 }
 966 
 967 address MacroAssembler::ic_call(address entry, jint method_index) {
 968   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
 969   movptr(rscratch2, (intptr_t)Universe::non_oop_word());
 970   return trampoline_call(Address(entry, rh));
 971 }
 972 
 973 int MacroAssembler::ic_check_size() {
 974   int extra_instructions = UseCompactObjectHeaders ? 1 : 0;
 975   if (target_needs_far_branch(CAST_FROM_FN_PTR(address, SharedRuntime::get_ic_miss_stub()))) {
 976     return NativeInstruction::instruction_size * (7 + extra_instructions);
 977   } else {
 978     return NativeInstruction::instruction_size * (5 + extra_instructions);
 979   }
 980 }
 981 
 982 int MacroAssembler::ic_check(int end_alignment) {
 983   Register receiver = j_rarg0;
 984   Register data = rscratch2;
 985   Register tmp1 = rscratch1;
 986   Register tmp2 = r10;
 987 
 988   // The UEP of a code blob ensures that the VEP is padded. However, the padding of the UEP is placed
 989   // before the inline cache check, so we don't have to execute any nop instructions when dispatching
 990   // through the UEP, yet we can ensure that the VEP is aligned appropriately. That's why we align
 991   // before the inline cache check here, and not after
 992   align(end_alignment, offset() + ic_check_size());
 993 
 994   int uep_offset = offset();
 995 
 996   if (UseCompactObjectHeaders) {
 997     load_narrow_klass_compact(tmp1, receiver);
 998     ldrw(tmp2, Address(data, CompiledICData::speculated_klass_offset()));
 999     cmpw(tmp1, tmp2);
1000   } else {
1001     ldrw(tmp1, Address(receiver, oopDesc::klass_offset_in_bytes()));
1002     ldrw(tmp2, Address(data, CompiledICData::speculated_klass_offset()));
1003     cmpw(tmp1, tmp2);
1004   }
1005 
1006   Label dont;
1007   br(Assembler::EQ, dont);
1008   far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
1009   bind(dont);
1010   assert((offset() % end_alignment) == 0, "Misaligned verified entry point");
1011 
1012   return uep_offset;
1013 }
1014 
1015 // Implementation of call_VM versions
1016 
1017 void MacroAssembler::call_VM(Register oop_result,
1018                              address entry_point,
1019                              bool check_exceptions) {
1020   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
1021 }
1022 
1023 void MacroAssembler::call_VM(Register oop_result,
1024                              address entry_point,
1025                              Register arg_1,
1026                              bool check_exceptions) {
1027   pass_arg1(this, arg_1);
1028   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
1029 }
1030 
1031 void MacroAssembler::call_VM(Register oop_result,
1032                              address entry_point,
1033                              Register arg_1,
1034                              Register arg_2,
1035                              bool check_exceptions) {
1036   assert_different_registers(arg_1, c_rarg2);
1037   pass_arg2(this, arg_2);
1038   pass_arg1(this, arg_1);
1039   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
1040 }
1041 
1042 void MacroAssembler::call_VM(Register oop_result,
1043                              address entry_point,
1044                              Register arg_1,
1045                              Register arg_2,
1046                              Register arg_3,
1047                              bool check_exceptions) {
1048   assert_different_registers(arg_1, c_rarg2, c_rarg3);
1049   assert_different_registers(arg_2, c_rarg3);
1050   pass_arg3(this, arg_3);
1051 
1052   pass_arg2(this, arg_2);
1053 
1054   pass_arg1(this, arg_1);
1055   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
1056 }
1057 
1058 void MacroAssembler::call_VM(Register oop_result,
1059                              Register last_java_sp,
1060                              address entry_point,
1061                              int number_of_arguments,
1062                              bool check_exceptions) {
1063   call_VM_base(oop_result, rthread, last_java_sp, nullptr, entry_point, number_of_arguments, check_exceptions);
1064 }
1065 
1066 void MacroAssembler::call_VM(Register oop_result,
1067                              Register last_java_sp,
1068                              address entry_point,
1069                              Register arg_1,
1070                              bool check_exceptions) {
1071   pass_arg1(this, arg_1);
1072   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
1073 }
1074 
1075 void MacroAssembler::call_VM(Register oop_result,
1076                              Register last_java_sp,
1077                              address entry_point,
1078                              Register arg_1,
1079                              Register arg_2,
1080                              bool check_exceptions) {
1081 
1082   assert_different_registers(arg_1, c_rarg2);
1083   pass_arg2(this, arg_2);
1084   pass_arg1(this, arg_1);
1085   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
1086 }
1087 
1088 void MacroAssembler::call_VM(Register oop_result,
1089                              Register last_java_sp,
1090                              address entry_point,
1091                              Register arg_1,
1092                              Register arg_2,
1093                              Register arg_3,
1094                              bool check_exceptions) {
1095   assert_different_registers(arg_1, c_rarg2, c_rarg3);
1096   assert_different_registers(arg_2, c_rarg3);
1097   pass_arg3(this, arg_3);
1098   pass_arg2(this, arg_2);
1099   pass_arg1(this, arg_1);
1100   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
1101 }
1102 
1103 
1104 void MacroAssembler::get_vm_result_oop(Register oop_result, Register java_thread) {
1105   ldr(oop_result, Address(java_thread, JavaThread::vm_result_oop_offset()));
1106   str(zr, Address(java_thread, JavaThread::vm_result_oop_offset()));
1107   verify_oop_msg(oop_result, "broken oop in call_VM_base");
1108 }
1109 
1110 void MacroAssembler::get_vm_result_metadata(Register metadata_result, Register java_thread) {
1111   ldr(metadata_result, Address(java_thread, JavaThread::vm_result_metadata_offset()));
1112   str(zr, Address(java_thread, JavaThread::vm_result_metadata_offset()));
1113 }
1114 
1115 void MacroAssembler::align(int modulus) {
1116   align(modulus, offset());
1117 }
1118 
1119 // Ensure that the code at target bytes offset from the current offset() is aligned
1120 // according to modulus.
1121 void MacroAssembler::align(int modulus, int target) {
1122   int delta = target - offset();
1123   while ((offset() + delta) % modulus != 0) nop();
1124 }
1125 
1126 void MacroAssembler::post_call_nop() {
1127   if (!Continuations::enabled()) {
1128     return;
1129   }
1130   InstructionMark im(this);
1131   relocate(post_call_nop_Relocation::spec());
1132   InlineSkippedInstructionsCounter skipCounter(this);
1133   nop();
1134   movk(zr, 0);
1135   movk(zr, 0);
1136 }
1137 
1138 // these are no-ops overridden by InterpreterMacroAssembler
1139 
1140 void MacroAssembler::check_and_handle_earlyret(Register java_thread) { }
1141 
1142 void MacroAssembler::check_and_handle_popframe(Register java_thread) { }
1143 
1144 // Look up the method for a megamorphic invokeinterface call.
1145 // The target method is determined by <intf_klass, itable_index>.
1146 // The receiver klass is in recv_klass.
1147 // On success, the result will be in method_result, and execution falls through.
1148 // On failure, execution transfers to the given label.
1149 void MacroAssembler::lookup_interface_method(Register recv_klass,
1150                                              Register intf_klass,
1151                                              RegisterOrConstant itable_index,
1152                                              Register method_result,
1153                                              Register scan_temp,
1154                                              Label& L_no_such_interface,
1155                          bool return_method) {
1156   assert_different_registers(recv_klass, intf_klass, scan_temp);
1157   assert_different_registers(method_result, intf_klass, scan_temp);
1158   assert(recv_klass != method_result || !return_method,
1159      "recv_klass can be destroyed when method isn't needed");
1160   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
1161          "caller must use same register for non-constant itable index as for method");
1162 
1163   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
1164   int vtable_base = in_bytes(Klass::vtable_start_offset());
1165   int itentry_off = in_bytes(itableMethodEntry::method_offset());
1166   int scan_step   = itableOffsetEntry::size() * wordSize;
1167   int vte_size    = vtableEntry::size_in_bytes();
1168   assert(vte_size == wordSize, "else adjust times_vte_scale");
1169 
1170   ldrw(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
1171 
1172   // Could store the aligned, prescaled offset in the klass.
1173   // lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
1174   lea(scan_temp, Address(recv_klass, scan_temp, Address::lsl(3)));
1175   add(scan_temp, scan_temp, vtable_base);
1176 
1177   if (return_method) {
1178     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
1179     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
1180     // lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
1181     lea(recv_klass, Address(recv_klass, itable_index, Address::lsl(3)));
1182     if (itentry_off)
1183       add(recv_klass, recv_klass, itentry_off);
1184   }
1185 
1186   // for (scan = klass->itable(); scan->interface() != nullptr; scan += scan_step) {
1187   //   if (scan->interface() == intf) {
1188   //     result = (klass + scan->offset() + itable_index);
1189   //   }
1190   // }
1191   Label search, found_method;
1192 
1193   ldr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset()));
1194   cmp(intf_klass, method_result);
1195   br(Assembler::EQ, found_method);
1196   bind(search);
1197   // Check that the previous entry is non-null.  A null entry means that
1198   // the receiver class doesn't implement the interface, and wasn't the
1199   // same as when the caller was compiled.
1200   cbz(method_result, L_no_such_interface);
1201   if (itableOffsetEntry::interface_offset() != 0) {
1202     add(scan_temp, scan_temp, scan_step);
1203     ldr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset()));
1204   } else {
1205     ldr(method_result, Address(pre(scan_temp, scan_step)));
1206   }
1207   cmp(intf_klass, method_result);
1208   br(Assembler::NE, search);
1209 
1210   bind(found_method);
1211 
1212   // Got a hit.
1213   if (return_method) {
1214     ldrw(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset()));
1215     ldr(method_result, Address(recv_klass, scan_temp, Address::uxtw(0)));
1216   }
1217 }
1218 
1219 // Look up the method for a megamorphic invokeinterface call in a single pass over itable:
1220 // - check recv_klass (actual object class) is a subtype of resolved_klass from CompiledICData
1221 // - find a holder_klass (class that implements the method) vtable offset and get the method from vtable by index
1222 // The target method is determined by <holder_klass, itable_index>.
1223 // The receiver klass is in recv_klass.
1224 // On success, the result will be in method_result, and execution falls through.
1225 // On failure, execution transfers to the given label.
1226 void MacroAssembler::lookup_interface_method_stub(Register recv_klass,
1227                                                   Register holder_klass,
1228                                                   Register resolved_klass,
1229                                                   Register method_result,
1230                                                   Register temp_itbl_klass,
1231                                                   Register scan_temp,
1232                                                   int itable_index,
1233                                                   Label& L_no_such_interface) {
1234   // 'method_result' is only used as output register at the very end of this method.
1235   // Until then we can reuse it as 'holder_offset'.
1236   Register holder_offset = method_result;
1237   assert_different_registers(resolved_klass, recv_klass, holder_klass, temp_itbl_klass, scan_temp, holder_offset);
1238 
1239   int vtable_start_offset = in_bytes(Klass::vtable_start_offset());
1240   int itable_offset_entry_size = itableOffsetEntry::size() * wordSize;
1241   int ioffset = in_bytes(itableOffsetEntry::interface_offset());
1242   int ooffset = in_bytes(itableOffsetEntry::offset_offset());
1243 
1244   Label L_loop_search_resolved_entry, L_resolved_found, L_holder_found;
1245 
1246   ldrw(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
1247   add(recv_klass, recv_klass, vtable_start_offset + ioffset);
1248   // itableOffsetEntry[] itable = recv_klass + Klass::vtable_start_offset() + sizeof(vtableEntry) * recv_klass->_vtable_len;
1249   // temp_itbl_klass = itable[0]._interface;
1250   int vtblEntrySize = vtableEntry::size_in_bytes();
1251   assert(vtblEntrySize == wordSize, "ldr lsl shift amount must be 3");
1252   ldr(temp_itbl_klass, Address(recv_klass, scan_temp, Address::lsl(exact_log2(vtblEntrySize))));
1253   mov(holder_offset, zr);
1254   // scan_temp = &(itable[0]._interface)
1255   lea(scan_temp, Address(recv_klass, scan_temp, Address::lsl(exact_log2(vtblEntrySize))));
1256 
1257   // Initial checks:
1258   //   - if (holder_klass != resolved_klass), go to "scan for resolved"
1259   //   - if (itable[0] == holder_klass), shortcut to "holder found"
1260   //   - if (itable[0] == 0), no such interface
1261   cmp(resolved_klass, holder_klass);
1262   br(Assembler::NE, L_loop_search_resolved_entry);
1263   cmp(holder_klass, temp_itbl_klass);
1264   br(Assembler::EQ, L_holder_found);
1265   cbz(temp_itbl_klass, L_no_such_interface);
1266 
1267   // Loop: Look for holder_klass record in itable
1268   //   do {
1269   //     temp_itbl_klass = *(scan_temp += itable_offset_entry_size);
1270   //     if (temp_itbl_klass == holder_klass) {
1271   //       goto L_holder_found; // Found!
1272   //     }
1273   //   } while (temp_itbl_klass != 0);
1274   //   goto L_no_such_interface // Not found.
1275   Label L_search_holder;
1276   bind(L_search_holder);
1277     ldr(temp_itbl_klass, Address(pre(scan_temp, itable_offset_entry_size)));
1278     cmp(holder_klass, temp_itbl_klass);
1279     br(Assembler::EQ, L_holder_found);
1280     cbnz(temp_itbl_klass, L_search_holder);
1281 
1282   b(L_no_such_interface);
1283 
1284   // Loop: Look for resolved_class record in itable
1285   //   while (true) {
1286   //     temp_itbl_klass = *(scan_temp += itable_offset_entry_size);
1287   //     if (temp_itbl_klass == 0) {
1288   //       goto L_no_such_interface;
1289   //     }
1290   //     if (temp_itbl_klass == resolved_klass) {
1291   //        goto L_resolved_found;  // Found!
1292   //     }
1293   //     if (temp_itbl_klass == holder_klass) {
1294   //        holder_offset = scan_temp;
1295   //     }
1296   //   }
1297   //
1298   Label L_loop_search_resolved;
1299   bind(L_loop_search_resolved);
1300     ldr(temp_itbl_klass, Address(pre(scan_temp, itable_offset_entry_size)));
1301   bind(L_loop_search_resolved_entry);
1302     cbz(temp_itbl_klass, L_no_such_interface);
1303     cmp(resolved_klass, temp_itbl_klass);
1304     br(Assembler::EQ, L_resolved_found);
1305     cmp(holder_klass, temp_itbl_klass);
1306     br(Assembler::NE, L_loop_search_resolved);
1307     mov(holder_offset, scan_temp);
1308     b(L_loop_search_resolved);
1309 
1310   // See if we already have a holder klass. If not, go and scan for it.
1311   bind(L_resolved_found);
1312   cbz(holder_offset, L_search_holder);
1313   mov(scan_temp, holder_offset);
1314 
1315   // Finally, scan_temp contains holder_klass vtable offset
1316   bind(L_holder_found);
1317   ldrw(method_result, Address(scan_temp, ooffset - ioffset));
1318   add(recv_klass, recv_klass, itable_index * wordSize + in_bytes(itableMethodEntry::method_offset())
1319     - vtable_start_offset - ioffset); // substract offsets to restore the original value of recv_klass
1320   ldr(method_result, Address(recv_klass, method_result, Address::uxtw(0)));
1321 }
1322 
1323 // virtual method calling
1324 void MacroAssembler::lookup_virtual_method(Register recv_klass,
1325                                            RegisterOrConstant vtable_index,
1326                                            Register method_result) {
1327   assert(vtableEntry::size() * wordSize == 8,
1328          "adjust the scaling in the code below");
1329   int64_t vtable_offset_in_bytes = in_bytes(Klass::vtable_start_offset() + vtableEntry::method_offset());
1330 
1331   if (vtable_index.is_register()) {
1332     lea(method_result, Address(recv_klass,
1333                                vtable_index.as_register(),
1334                                Address::lsl(LogBytesPerWord)));
1335     ldr(method_result, Address(method_result, vtable_offset_in_bytes));
1336   } else {
1337     vtable_offset_in_bytes += vtable_index.as_constant() * wordSize;
1338     ldr(method_result,
1339         form_address(rscratch1, recv_klass, vtable_offset_in_bytes, 0));
1340   }
1341 }
1342 
1343 void MacroAssembler::check_klass_subtype(Register sub_klass,
1344                            Register super_klass,
1345                            Register temp_reg,
1346                            Label& L_success) {
1347   Label L_failure;
1348   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, nullptr);
1349   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, nullptr);
1350   bind(L_failure);
1351 }
1352 
1353 
1354 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
1355                                                    Register super_klass,
1356                                                    Register temp_reg,
1357                                                    Label* L_success,
1358                                                    Label* L_failure,
1359                                                    Label* L_slow_path,
1360                                                    Register super_check_offset) {
1361   assert_different_registers(sub_klass, super_klass, temp_reg, super_check_offset);
1362   bool must_load_sco = ! super_check_offset->is_valid();
1363   if (must_load_sco) {
1364     assert(temp_reg != noreg, "supply either a temp or a register offset");
1365   }
1366 
1367   Label L_fallthrough;
1368   int label_nulls = 0;
1369   if (L_success == nullptr)   { L_success   = &L_fallthrough; label_nulls++; }
1370   if (L_failure == nullptr)   { L_failure   = &L_fallthrough; label_nulls++; }
1371   if (L_slow_path == nullptr) { L_slow_path = &L_fallthrough; label_nulls++; }
1372   assert(label_nulls <= 1, "at most one null in the batch");
1373 
1374   int sco_offset = in_bytes(Klass::super_check_offset_offset());
1375   Address super_check_offset_addr(super_klass, sco_offset);
1376 
1377   // Hacked jmp, which may only be used just before L_fallthrough.
1378 #define final_jmp(label)                                                \
1379   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
1380   else                            b(label)                /*omit semi*/
1381 
1382   // If the pointers are equal, we are done (e.g., String[] elements).
1383   // This self-check enables sharing of secondary supertype arrays among
1384   // non-primary types such as array-of-interface.  Otherwise, each such
1385   // type would need its own customized SSA.
1386   // We move this check to the front of the fast path because many
1387   // type checks are in fact trivially successful in this manner,
1388   // so we get a nicely predicted branch right at the start of the check.
1389   cmp(sub_klass, super_klass);
1390   br(Assembler::EQ, *L_success);
1391 
1392   // Check the supertype display:
1393   if (must_load_sco) {
1394     ldrw(temp_reg, super_check_offset_addr);
1395     super_check_offset = temp_reg;
1396   }
1397 
1398   Address super_check_addr(sub_klass, super_check_offset);
1399   ldr(rscratch1, super_check_addr);
1400   cmp(super_klass, rscratch1); // load displayed supertype
1401   br(Assembler::EQ, *L_success);
1402 
1403   // This check has worked decisively for primary supers.
1404   // Secondary supers are sought in the super_cache ('super_cache_addr').
1405   // (Secondary supers are interfaces and very deeply nested subtypes.)
1406   // This works in the same check above because of a tricky aliasing
1407   // between the super_cache and the primary super display elements.
1408   // (The 'super_check_addr' can address either, as the case requires.)
1409   // Note that the cache is updated below if it does not help us find
1410   // what we need immediately.
1411   // So if it was a primary super, we can just fail immediately.
1412   // Otherwise, it's the slow path for us (no success at this point).
1413 
1414   sub(rscratch1, super_check_offset, in_bytes(Klass::secondary_super_cache_offset()));
1415   if (L_failure == &L_fallthrough) {
1416     cbz(rscratch1, *L_slow_path);
1417   } else {
1418     cbnz(rscratch1, *L_failure);
1419     final_jmp(*L_slow_path);
1420   }
1421 
1422   bind(L_fallthrough);
1423 
1424 #undef final_jmp
1425 }
1426 
1427 // These two are taken from x86, but they look generally useful
1428 
1429 // scans count pointer sized words at [addr] for occurrence of value,
1430 // generic
1431 void MacroAssembler::repne_scan(Register addr, Register value, Register count,
1432                                 Register scratch) {
1433   Label Lloop, Lexit;
1434   cbz(count, Lexit);
1435   bind(Lloop);
1436   ldr(scratch, post(addr, wordSize));
1437   cmp(value, scratch);
1438   br(EQ, Lexit);
1439   sub(count, count, 1);
1440   cbnz(count, Lloop);
1441   bind(Lexit);
1442 }
1443 
1444 // scans count 4 byte words at [addr] for occurrence of value,
1445 // generic
1446 void MacroAssembler::repne_scanw(Register addr, Register value, Register count,
1447                                 Register scratch) {
1448   Label Lloop, Lexit;
1449   cbz(count, Lexit);
1450   bind(Lloop);
1451   ldrw(scratch, post(addr, wordSize));
1452   cmpw(value, scratch);
1453   br(EQ, Lexit);
1454   sub(count, count, 1);
1455   cbnz(count, Lloop);
1456   bind(Lexit);
1457 }
1458 
1459 void MacroAssembler::check_klass_subtype_slow_path_linear(Register sub_klass,
1460                                                           Register super_klass,
1461                                                           Register temp_reg,
1462                                                           Register temp2_reg,
1463                                                           Label* L_success,
1464                                                           Label* L_failure,
1465                                                           bool set_cond_codes) {
1466   // NB! Callers may assume that, when temp2_reg is a valid register,
1467   // this code sets it to a nonzero value.
1468 
1469   assert_different_registers(sub_klass, super_klass, temp_reg);
1470   if (temp2_reg != noreg)
1471     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg, rscratch1);
1472 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
1473 
1474   Label L_fallthrough;
1475   int label_nulls = 0;
1476   if (L_success == nullptr)   { L_success   = &L_fallthrough; label_nulls++; }
1477   if (L_failure == nullptr)   { L_failure   = &L_fallthrough; label_nulls++; }
1478   assert(label_nulls <= 1, "at most one null in the batch");
1479 
1480   // a couple of useful fields in sub_klass:
1481   int ss_offset = in_bytes(Klass::secondary_supers_offset());
1482   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1483   Address secondary_supers_addr(sub_klass, ss_offset);
1484   Address super_cache_addr(     sub_klass, sc_offset);
1485 
1486   BLOCK_COMMENT("check_klass_subtype_slow_path");
1487 
1488   // Do a linear scan of the secondary super-klass chain.
1489   // This code is rarely used, so simplicity is a virtue here.
1490   // The repne_scan instruction uses fixed registers, which we must spill.
1491   // Don't worry too much about pre-existing connections with the input regs.
1492 
1493   assert(sub_klass != r0, "killed reg"); // killed by mov(r0, super)
1494   assert(sub_klass != r2, "killed reg"); // killed by lea(r2, &pst_counter)
1495 
1496   RegSet pushed_registers;
1497   if (!IS_A_TEMP(r2))    pushed_registers += r2;
1498   if (!IS_A_TEMP(r5))    pushed_registers += r5;
1499 
1500   if (super_klass != r0) {
1501     if (!IS_A_TEMP(r0))   pushed_registers += r0;
1502   }
1503 
1504   push(pushed_registers, sp);
1505 
1506   // Get super_klass value into r0 (even if it was in r5 or r2).
1507   if (super_klass != r0) {
1508     mov(r0, super_klass);
1509   }
1510 
1511 #ifndef PRODUCT
1512   incrementw(ExternalAddress((address)&SharedRuntime::_partial_subtype_ctr));
1513 #endif //PRODUCT
1514 
1515   // We will consult the secondary-super array.
1516   ldr(r5, secondary_supers_addr);
1517   // Load the array length.
1518   ldrw(r2, Address(r5, Array<Klass*>::length_offset_in_bytes()));
1519   // Skip to start of data.
1520   add(r5, r5, Array<Klass*>::base_offset_in_bytes());
1521 
1522   cmp(sp, zr); // Clear Z flag; SP is never zero
1523   // Scan R2 words at [R5] for an occurrence of R0.
1524   // Set NZ/Z based on last compare.
1525   repne_scan(r5, r0, r2, rscratch1);
1526 
1527   // Unspill the temp. registers:
1528   pop(pushed_registers, sp);
1529 
1530   br(Assembler::NE, *L_failure);
1531 
1532   // Success.  Cache the super we found and proceed in triumph.
1533 
1534   if (UseSecondarySupersCache) {
1535     str(super_klass, super_cache_addr);
1536   }
1537 
1538   if (L_success != &L_fallthrough) {
1539     b(*L_success);
1540   }
1541 
1542 #undef IS_A_TEMP
1543 
1544   bind(L_fallthrough);
1545 }
1546 
1547 // If Register r is invalid, remove a new register from
1548 // available_regs, and add new register to regs_to_push.
1549 Register MacroAssembler::allocate_if_noreg(Register r,
1550                                   RegSetIterator<Register> &available_regs,
1551                                   RegSet &regs_to_push) {
1552   if (!r->is_valid()) {
1553     r = *available_regs++;
1554     regs_to_push += r;
1555   }
1556   return r;
1557 }
1558 
1559 // check_klass_subtype_slow_path_table() looks for super_klass in the
1560 // hash table belonging to super_klass, branching to L_success or
1561 // L_failure as appropriate. This is essentially a shim which
1562 // allocates registers as necessary then calls
1563 // lookup_secondary_supers_table() to do the work. Any of the temp
1564 // regs may be noreg, in which case this logic will chooses some
1565 // registers push and pop them from the stack.
1566 void MacroAssembler::check_klass_subtype_slow_path_table(Register sub_klass,
1567                                                          Register super_klass,
1568                                                          Register temp_reg,
1569                                                          Register temp2_reg,
1570                                                          Register temp3_reg,
1571                                                          Register result_reg,
1572                                                          FloatRegister vtemp,
1573                                                          Label* L_success,
1574                                                          Label* L_failure,
1575                                                          bool set_cond_codes) {
1576   RegSet temps = RegSet::of(temp_reg, temp2_reg, temp3_reg);
1577 
1578   assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg, rscratch1);
1579 
1580   Label L_fallthrough;
1581   int label_nulls = 0;
1582   if (L_success == nullptr)   { L_success   = &L_fallthrough; label_nulls++; }
1583   if (L_failure == nullptr)   { L_failure   = &L_fallthrough; label_nulls++; }
1584   assert(label_nulls <= 1, "at most one null in the batch");
1585 
1586   BLOCK_COMMENT("check_klass_subtype_slow_path");
1587 
1588   RegSetIterator<Register> available_regs
1589     = (RegSet::range(r0, r15) - temps - sub_klass - super_klass).begin();
1590 
1591   RegSet pushed_regs;
1592 
1593   temp_reg = allocate_if_noreg(temp_reg, available_regs, pushed_regs);
1594   temp2_reg = allocate_if_noreg(temp2_reg, available_regs, pushed_regs);
1595   temp3_reg = allocate_if_noreg(temp3_reg, available_regs, pushed_regs);
1596   result_reg = allocate_if_noreg(result_reg, available_regs, pushed_regs);
1597 
1598   push(pushed_regs, sp);
1599 
1600   lookup_secondary_supers_table_var(sub_klass,
1601                                     super_klass,
1602                                     temp_reg, temp2_reg, temp3_reg, vtemp, result_reg,
1603                                     nullptr);
1604   cmp(result_reg, zr);
1605 
1606   // Unspill the temp. registers:
1607   pop(pushed_regs, sp);
1608 
1609   // NB! Callers may assume that, when set_cond_codes is true, this
1610   // code sets temp2_reg to a nonzero value.
1611   if (set_cond_codes) {
1612     mov(temp2_reg, 1);
1613   }
1614 
1615   br(Assembler::NE, *L_failure);
1616 
1617   if (L_success != &L_fallthrough) {
1618     b(*L_success);
1619   }
1620 
1621   bind(L_fallthrough);
1622 }
1623 
1624 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
1625                                                    Register super_klass,
1626                                                    Register temp_reg,
1627                                                    Register temp2_reg,
1628                                                    Label* L_success,
1629                                                    Label* L_failure,
1630                                                    bool set_cond_codes) {
1631   if (UseSecondarySupersTable) {
1632     check_klass_subtype_slow_path_table
1633       (sub_klass, super_klass, temp_reg, temp2_reg, /*temp3*/noreg, /*result*/noreg,
1634        /*vtemp*/fnoreg,
1635        L_success, L_failure, set_cond_codes);
1636   } else {
1637     check_klass_subtype_slow_path_linear
1638       (sub_klass, super_klass, temp_reg, temp2_reg, L_success, L_failure, set_cond_codes);
1639   }
1640 }
1641 
1642 
1643 // Ensure that the inline code and the stub are using the same registers.
1644 #define LOOKUP_SECONDARY_SUPERS_TABLE_REGISTERS                    \
1645 do {                                                               \
1646   assert(r_super_klass  == r0                                   && \
1647          r_array_base   == r1                                   && \
1648          r_array_length == r2                                   && \
1649          (r_array_index == r3        || r_array_index == noreg) && \
1650          (r_sub_klass   == r4        || r_sub_klass   == noreg) && \
1651          (r_bitmap      == rscratch2 || r_bitmap      == noreg) && \
1652          (result        == r5        || result        == noreg), "registers must match aarch64.ad"); \
1653 } while(0)
1654 
1655 bool MacroAssembler::lookup_secondary_supers_table_const(Register r_sub_klass,
1656                                                          Register r_super_klass,
1657                                                          Register temp1,
1658                                                          Register temp2,
1659                                                          Register temp3,
1660                                                          FloatRegister vtemp,
1661                                                          Register result,
1662                                                          u1 super_klass_slot,
1663                                                          bool stub_is_near) {
1664   assert_different_registers(r_sub_klass, temp1, temp2, temp3, result, rscratch1, rscratch2);
1665 
1666   Label L_fallthrough;
1667 
1668   BLOCK_COMMENT("lookup_secondary_supers_table {");
1669 
1670   const Register
1671     r_array_base   = temp1, // r1
1672     r_array_length = temp2, // r2
1673     r_array_index  = temp3, // r3
1674     r_bitmap       = rscratch2;
1675 
1676   LOOKUP_SECONDARY_SUPERS_TABLE_REGISTERS;
1677 
1678   u1 bit = super_klass_slot;
1679 
1680   // Make sure that result is nonzero if the TBZ below misses.
1681   mov(result, 1);
1682 
1683   // We're going to need the bitmap in a vector reg and in a core reg,
1684   // so load both now.
1685   ldr(r_bitmap, Address(r_sub_klass, Klass::secondary_supers_bitmap_offset()));
1686   if (bit != 0) {
1687     ldrd(vtemp, Address(r_sub_klass, Klass::secondary_supers_bitmap_offset()));
1688   }
1689   // First check the bitmap to see if super_klass might be present. If
1690   // the bit is zero, we are certain that super_klass is not one of
1691   // the secondary supers.
1692   tbz(r_bitmap, bit, L_fallthrough);
1693 
1694   // Get the first array index that can contain super_klass into r_array_index.
1695   if (bit != 0) {
1696     shld(vtemp, vtemp, Klass::SECONDARY_SUPERS_TABLE_MASK - bit);
1697     cnt(vtemp, T8B, vtemp);
1698     addv(vtemp, T8B, vtemp);
1699     fmovd(r_array_index, vtemp);
1700   } else {
1701     mov(r_array_index, (u1)1);
1702   }
1703   // NB! r_array_index is off by 1. It is compensated by keeping r_array_base off by 1 word.
1704 
1705   // We will consult the secondary-super array.
1706   ldr(r_array_base, Address(r_sub_klass, in_bytes(Klass::secondary_supers_offset())));
1707 
1708   // The value i in r_array_index is >= 1, so even though r_array_base
1709   // points to the length, we don't need to adjust it to point to the
1710   // data.
1711   assert(Array<Klass*>::base_offset_in_bytes() == wordSize, "Adjust this code");
1712   assert(Array<Klass*>::length_offset_in_bytes() == 0, "Adjust this code");
1713 
1714   ldr(result, Address(r_array_base, r_array_index, Address::lsl(LogBytesPerWord)));
1715   eor(result, result, r_super_klass);
1716   cbz(result, L_fallthrough); // Found a match
1717 
1718   // Is there another entry to check? Consult the bitmap.
1719   tbz(r_bitmap, (bit + 1) & Klass::SECONDARY_SUPERS_TABLE_MASK, L_fallthrough);
1720 
1721   // Linear probe.
1722   if (bit != 0) {
1723     ror(r_bitmap, r_bitmap, bit);
1724   }
1725 
1726   // The slot we just inspected is at secondary_supers[r_array_index - 1].
1727   // The next slot to be inspected, by the stub we're about to call,
1728   // is secondary_supers[r_array_index]. Bits 0 and 1 in the bitmap
1729   // have been checked.
1730   Address stub = RuntimeAddress(StubRoutines::lookup_secondary_supers_table_slow_path_stub());
1731   if (stub_is_near) {
1732     bl(stub);
1733   } else {
1734     address call = trampoline_call(stub);
1735     if (call == nullptr) {
1736       return false; // trampoline allocation failed
1737     }
1738   }
1739 
1740   BLOCK_COMMENT("} lookup_secondary_supers_table");
1741 
1742   bind(L_fallthrough);
1743 
1744   if (VerifySecondarySupers) {
1745     verify_secondary_supers_table(r_sub_klass, r_super_klass, // r4, r0
1746                                   temp1, temp2, result);      // r1, r2, r5
1747   }
1748   return true;
1749 }
1750 
1751 // At runtime, return 0 in result if r_super_klass is a superclass of
1752 // r_sub_klass, otherwise return nonzero. Use this version of
1753 // lookup_secondary_supers_table() if you don't know ahead of time
1754 // which superclass will be searched for. Used by interpreter and
1755 // runtime stubs. It is larger and has somewhat greater latency than
1756 // the version above, which takes a constant super_klass_slot.
1757 void MacroAssembler::lookup_secondary_supers_table_var(Register r_sub_klass,
1758                                                        Register r_super_klass,
1759                                                        Register temp1,
1760                                                        Register temp2,
1761                                                        Register temp3,
1762                                                        FloatRegister vtemp,
1763                                                        Register result,
1764                                                        Label *L_success) {
1765   assert_different_registers(r_sub_klass, temp1, temp2, temp3, result, rscratch1, rscratch2);
1766 
1767   Label L_fallthrough;
1768 
1769   BLOCK_COMMENT("lookup_secondary_supers_table {");
1770 
1771   const Register
1772     r_array_index = temp3,
1773     slot          = rscratch1,
1774     r_bitmap      = rscratch2;
1775 
1776   ldrb(slot, Address(r_super_klass, Klass::hash_slot_offset()));
1777 
1778   // Make sure that result is nonzero if the test below misses.
1779   mov(result, 1);
1780 
1781   ldr(r_bitmap, Address(r_sub_klass, Klass::secondary_supers_bitmap_offset()));
1782 
1783   // First check the bitmap to see if super_klass might be present. If
1784   // the bit is zero, we are certain that super_klass is not one of
1785   // the secondary supers.
1786 
1787   // This next instruction is equivalent to:
1788   // mov(tmp_reg, (u1)(Klass::SECONDARY_SUPERS_TABLE_SIZE - 1));
1789   // sub(temp2, tmp_reg, slot);
1790   eor(temp2, slot, (u1)(Klass::SECONDARY_SUPERS_TABLE_SIZE - 1));
1791   lslv(temp2, r_bitmap, temp2);
1792   tbz(temp2, Klass::SECONDARY_SUPERS_TABLE_SIZE - 1, L_fallthrough);
1793 
1794   bool must_save_v0 = (vtemp == fnoreg);
1795   if (must_save_v0) {
1796     // temp1 and result are free, so use them to preserve vtemp
1797     vtemp = v0;
1798     mov(temp1,  vtemp, D, 0);
1799     mov(result, vtemp, D, 1);
1800   }
1801 
1802   // Get the first array index that can contain super_klass into r_array_index.
1803   mov(vtemp, D, 0, temp2);
1804   cnt(vtemp, T8B, vtemp);
1805   addv(vtemp, T8B, vtemp);
1806   mov(r_array_index, vtemp, D, 0);
1807 
1808   if (must_save_v0) {
1809     mov(vtemp, D, 0, temp1 );
1810     mov(vtemp, D, 1, result);
1811   }
1812 
1813   // NB! r_array_index is off by 1. It is compensated by keeping r_array_base off by 1 word.
1814 
1815   const Register
1816     r_array_base   = temp1,
1817     r_array_length = temp2;
1818 
1819   // The value i in r_array_index is >= 1, so even though r_array_base
1820   // points to the length, we don't need to adjust it to point to the
1821   // data.
1822   assert(Array<Klass*>::base_offset_in_bytes() == wordSize, "Adjust this code");
1823   assert(Array<Klass*>::length_offset_in_bytes() == 0, "Adjust this code");
1824 
1825   // We will consult the secondary-super array.
1826   ldr(r_array_base, Address(r_sub_klass, in_bytes(Klass::secondary_supers_offset())));
1827 
1828   ldr(result, Address(r_array_base, r_array_index, Address::lsl(LogBytesPerWord)));
1829   eor(result, result, r_super_klass);
1830   cbz(result, L_success ? *L_success : L_fallthrough); // Found a match
1831 
1832   // Is there another entry to check? Consult the bitmap.
1833   rorv(r_bitmap, r_bitmap, slot);
1834   // rol(r_bitmap, r_bitmap, 1);
1835   tbz(r_bitmap, 1, L_fallthrough);
1836 
1837   // The slot we just inspected is at secondary_supers[r_array_index - 1].
1838   // The next slot to be inspected, by the logic we're about to call,
1839   // is secondary_supers[r_array_index]. Bits 0 and 1 in the bitmap
1840   // have been checked.
1841   lookup_secondary_supers_table_slow_path(r_super_klass, r_array_base, r_array_index,
1842                                           r_bitmap, r_array_length, result, /*is_stub*/false);
1843 
1844   BLOCK_COMMENT("} lookup_secondary_supers_table");
1845 
1846   bind(L_fallthrough);
1847 
1848   if (VerifySecondarySupers) {
1849     verify_secondary_supers_table(r_sub_klass, r_super_klass, // r4, r0
1850                                   temp1, temp2, result);      // r1, r2, r5
1851   }
1852 
1853   if (L_success) {
1854     cbz(result, *L_success);
1855   }
1856 }
1857 
1858 // Called by code generated by check_klass_subtype_slow_path
1859 // above. This is called when there is a collision in the hashed
1860 // lookup in the secondary supers array.
1861 void MacroAssembler::lookup_secondary_supers_table_slow_path(Register r_super_klass,
1862                                                              Register r_array_base,
1863                                                              Register r_array_index,
1864                                                              Register r_bitmap,
1865                                                              Register temp1,
1866                                                              Register result,
1867                                                              bool is_stub) {
1868   assert_different_registers(r_super_klass, r_array_base, r_array_index, r_bitmap, temp1, result, rscratch1);
1869 
1870   const Register
1871     r_array_length = temp1,
1872     r_sub_klass    = noreg; // unused
1873 
1874   if (is_stub) {
1875     LOOKUP_SECONDARY_SUPERS_TABLE_REGISTERS;
1876   }
1877 
1878   Label L_fallthrough, L_huge;
1879 
1880   // Load the array length.
1881   ldrw(r_array_length, Address(r_array_base, Array<Klass*>::length_offset_in_bytes()));
1882   // And adjust the array base to point to the data.
1883   // NB! Effectively increments current slot index by 1.
1884   assert(Array<Klass*>::base_offset_in_bytes() == wordSize, "");
1885   add(r_array_base, r_array_base, Array<Klass*>::base_offset_in_bytes());
1886 
1887   // The bitmap is full to bursting.
1888   // Implicit invariant: BITMAP_FULL implies (length > 0)
1889   assert(Klass::SECONDARY_SUPERS_BITMAP_FULL == ~uintx(0), "");
1890   cmpw(r_array_length, (u1)(Klass::SECONDARY_SUPERS_TABLE_SIZE - 2));
1891   br(GT, L_huge);
1892 
1893   // NB! Our caller has checked bits 0 and 1 in the bitmap. The
1894   // current slot (at secondary_supers[r_array_index]) has not yet
1895   // been inspected, and r_array_index may be out of bounds if we
1896   // wrapped around the end of the array.
1897 
1898   { // This is conventional linear probing, but instead of terminating
1899     // when a null entry is found in the table, we maintain a bitmap
1900     // in which a 0 indicates missing entries.
1901     // As long as the bitmap is not completely full,
1902     // array_length == popcount(bitmap). The array_length check above
1903     // guarantees there are 0s in the bitmap, so the loop eventually
1904     // terminates.
1905     Label L_loop;
1906     bind(L_loop);
1907 
1908     // Check for wraparound.
1909     cmp(r_array_index, r_array_length);
1910     csel(r_array_index, zr, r_array_index, GE);
1911 
1912     ldr(rscratch1, Address(r_array_base, r_array_index, Address::lsl(LogBytesPerWord)));
1913     eor(result, rscratch1, r_super_klass);
1914     cbz(result, L_fallthrough);
1915 
1916     tbz(r_bitmap, 2, L_fallthrough); // look-ahead check (Bit 2); result is non-zero
1917 
1918     ror(r_bitmap, r_bitmap, 1);
1919     add(r_array_index, r_array_index, 1);
1920     b(L_loop);
1921   }
1922 
1923   { // Degenerate case: more than 64 secondary supers.
1924     // FIXME: We could do something smarter here, maybe a vectorized
1925     // comparison or a binary search, but is that worth any added
1926     // complexity?
1927     bind(L_huge);
1928     cmp(sp, zr); // Clear Z flag; SP is never zero
1929     repne_scan(r_array_base, r_super_klass, r_array_length, rscratch1);
1930     cset(result, NE); // result == 0 iff we got a match.
1931   }
1932 
1933   bind(L_fallthrough);
1934 }
1935 
1936 // Make sure that the hashed lookup and a linear scan agree.
1937 void MacroAssembler::verify_secondary_supers_table(Register r_sub_klass,
1938                                                    Register r_super_klass,
1939                                                    Register temp1,
1940                                                    Register temp2,
1941                                                    Register result) {
1942   assert_different_registers(r_sub_klass, r_super_klass, temp1, temp2, result, rscratch1);
1943 
1944   const Register
1945     r_array_base   = temp1,
1946     r_array_length = temp2;
1947 
1948   BLOCK_COMMENT("verify_secondary_supers_table {");
1949 
1950   // We will consult the secondary-super array.
1951   ldr(r_array_base, Address(r_sub_klass, in_bytes(Klass::secondary_supers_offset())));
1952 
1953   // Load the array length.
1954   ldrw(r_array_length, Address(r_array_base, Array<Klass*>::length_offset_in_bytes()));
1955   // And adjust the array base to point to the data.
1956   add(r_array_base, r_array_base, Array<Klass*>::base_offset_in_bytes());
1957 
1958   cmp(sp, zr); // Clear Z flag; SP is never zero
1959   // Scan R2 words at [R5] for an occurrence of R0.
1960   // Set NZ/Z based on last compare.
1961   repne_scan(/*addr*/r_array_base, /*value*/r_super_klass, /*count*/r_array_length, rscratch2);
1962   // rscratch1 == 0 iff we got a match.
1963   cset(rscratch1, NE);
1964 
1965   Label passed;
1966   cmp(result, zr);
1967   cset(result, NE); // normalize result to 0/1 for comparison
1968 
1969   cmp(rscratch1, result);
1970   br(EQ, passed);
1971   {
1972     mov(r0, r_super_klass);         // r0 <- r0
1973     mov(r1, r_sub_klass);           // r1 <- r4
1974     mov(r2, /*expected*/rscratch1); // r2 <- r8
1975     mov(r3, result);                // r3 <- r5
1976     mov(r4, (address)("mismatch")); // r4 <- const
1977     rt_call(CAST_FROM_FN_PTR(address, Klass::on_secondary_supers_verification_failure), rscratch2);
1978     should_not_reach_here();
1979   }
1980   bind(passed);
1981 
1982   BLOCK_COMMENT("} verify_secondary_supers_table");
1983 }
1984 
1985 void MacroAssembler::clinit_barrier(Register klass, Register scratch, Label* L_fast_path, Label* L_slow_path) {
1986   assert(L_fast_path != nullptr || L_slow_path != nullptr, "at least one is required");
1987   assert_different_registers(klass, rthread, scratch);
1988 
1989   Label L_fallthrough, L_tmp;
1990   if (L_fast_path == nullptr) {
1991     L_fast_path = &L_fallthrough;
1992   } else if (L_slow_path == nullptr) {
1993     L_slow_path = &L_fallthrough;
1994   }
1995   // Fast path check: class is fully initialized
1996   lea(scratch, Address(klass, InstanceKlass::init_state_offset()));
1997   ldarb(scratch, scratch);
1998   cmp(scratch, InstanceKlass::fully_initialized);
1999   br(Assembler::EQ, *L_fast_path);
2000 
2001   // Fast path check: current thread is initializer thread
2002   ldr(scratch, Address(klass, InstanceKlass::init_thread_offset()));
2003   cmp(rthread, scratch);
2004 
2005   if (L_slow_path == &L_fallthrough) {
2006     br(Assembler::EQ, *L_fast_path);
2007     bind(*L_slow_path);
2008   } else if (L_fast_path == &L_fallthrough) {
2009     br(Assembler::NE, *L_slow_path);
2010     bind(*L_fast_path);
2011   } else {
2012     Unimplemented();
2013   }
2014 }
2015 
2016 void MacroAssembler::_verify_oop(Register reg, const char* s, const char* file, int line) {
2017   if (!VerifyOops || VerifyAdapterSharing) {
2018     // Below address of the code string confuses VerifyAdapterSharing
2019     // because it may differ between otherwise equivalent adapters.
2020     return;
2021   }
2022 
2023   // Pass register number to verify_oop_subroutine
2024   const char* b = nullptr;
2025   {
2026     ResourceMark rm;
2027     stringStream ss;
2028     ss.print("verify_oop: %s: %s (%s:%d)", reg->name(), s, file, line);
2029     b = code_string(ss.as_string());
2030   }
2031   BLOCK_COMMENT("verify_oop {");
2032 
2033   strip_return_address(); // This might happen within a stack frame.
2034   protect_return_address();
2035   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
2036   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
2037 
2038   mov(r0, reg);
2039   movptr(rscratch1, (uintptr_t)(address)b);
2040 
2041   // call indirectly to solve generation ordering problem
2042   lea(rscratch2, RuntimeAddress(StubRoutines::verify_oop_subroutine_entry_address()));
2043   ldr(rscratch2, Address(rscratch2));
2044   blr(rscratch2);
2045 
2046   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
2047   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
2048   authenticate_return_address();
2049 
2050   BLOCK_COMMENT("} verify_oop");
2051 }
2052 
2053 void MacroAssembler::_verify_oop_addr(Address addr, const char* s, const char* file, int line) {
2054   if (!VerifyOops || VerifyAdapterSharing) {
2055     // Below address of the code string confuses VerifyAdapterSharing
2056     // because it may differ between otherwise equivalent adapters.
2057     return;
2058   }
2059 
2060   const char* b = nullptr;
2061   {
2062     ResourceMark rm;
2063     stringStream ss;
2064     ss.print("verify_oop_addr: %s (%s:%d)", s, file, line);
2065     b = code_string(ss.as_string());
2066   }
2067   BLOCK_COMMENT("verify_oop_addr {");
2068 
2069   strip_return_address(); // This might happen within a stack frame.
2070   protect_return_address();
2071   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
2072   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
2073 
2074   // addr may contain sp so we will have to adjust it based on the
2075   // pushes that we just did.
2076   if (addr.uses(sp)) {
2077     lea(r0, addr);
2078     ldr(r0, Address(r0, 4 * wordSize));
2079   } else {
2080     ldr(r0, addr);
2081   }
2082   movptr(rscratch1, (uintptr_t)(address)b);
2083 
2084   // call indirectly to solve generation ordering problem
2085   lea(rscratch2, RuntimeAddress(StubRoutines::verify_oop_subroutine_entry_address()));
2086   ldr(rscratch2, Address(rscratch2));
2087   blr(rscratch2);
2088 
2089   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
2090   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
2091   authenticate_return_address();
2092 
2093   BLOCK_COMMENT("} verify_oop_addr");
2094 }
2095 
2096 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
2097                                          int extra_slot_offset) {
2098   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
2099   int stackElementSize = Interpreter::stackElementSize;
2100   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
2101 #ifdef ASSERT
2102   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
2103   assert(offset1 - offset == stackElementSize, "correct arithmetic");
2104 #endif
2105   if (arg_slot.is_constant()) {
2106     return Address(esp, arg_slot.as_constant() * stackElementSize
2107                    + offset);
2108   } else {
2109     add(rscratch1, esp, arg_slot.as_register(),
2110         ext::uxtx, exact_log2(stackElementSize));
2111     return Address(rscratch1, offset);
2112   }
2113 }
2114 
2115 // Handle the receiver type profile update given the "recv" klass.
2116 //
2117 // Normally updates the ReceiverData (RD) that starts at "mdp" + "mdp_offset".
2118 // If there are no matching or claimable receiver entries in RD, updates
2119 // the polymorphic counter.
2120 //
2121 // This code expected to run by either the interpreter or JIT-ed code, without
2122 // extra synchronization. For safety, receiver cells are claimed atomically, which
2123 // avoids grossly misrepresenting the profiles under concurrent updates. For speed,
2124 // counter updates are not atomic.
2125 //
2126 void MacroAssembler::profile_receiver_type(Register recv, Register mdp, int mdp_offset) {
2127   assert_different_registers(recv, mdp, rscratch1, rscratch2);
2128 
2129   int base_receiver_offset   = in_bytes(ReceiverTypeData::receiver_offset(0));
2130   int end_receiver_offset    = in_bytes(ReceiverTypeData::receiver_offset(ReceiverTypeData::row_limit()));
2131   int poly_count_offset      = in_bytes(CounterData::count_offset());
2132   int receiver_step          = in_bytes(ReceiverTypeData::receiver_offset(1)) - base_receiver_offset;
2133   int receiver_to_count_step = in_bytes(ReceiverTypeData::receiver_count_offset(0)) - base_receiver_offset;
2134 
2135   // Adjust for MDP offsets.
2136   base_receiver_offset += mdp_offset;
2137   end_receiver_offset  += mdp_offset;
2138   poly_count_offset    += mdp_offset;
2139 
2140 #ifdef ASSERT
2141   // We are about to walk the MDO slots without asking for offsets.
2142   // Check that our math hits all the right spots.
2143   for (uint c = 0; c < ReceiverTypeData::row_limit(); c++) {
2144     int real_recv_offset  = mdp_offset + in_bytes(ReceiverTypeData::receiver_offset(c));
2145     int real_count_offset = mdp_offset + in_bytes(ReceiverTypeData::receiver_count_offset(c));
2146     int offset = base_receiver_offset + receiver_step*c;
2147     int count_offset = offset + receiver_to_count_step;
2148     assert(offset == real_recv_offset, "receiver slot math");
2149     assert(count_offset == real_count_offset, "receiver count math");
2150   }
2151   int real_poly_count_offset = mdp_offset + in_bytes(CounterData::count_offset());
2152   assert(poly_count_offset == real_poly_count_offset, "poly counter math");
2153 #endif
2154 
2155   // Corner case: no profile table. Increment poly counter and exit.
2156   if (ReceiverTypeData::row_limit() == 0) {
2157     increment(Address(mdp, poly_count_offset), DataLayout::counter_increment);
2158     return;
2159   }
2160 
2161   Register offset = rscratch2;
2162 
2163   Label L_loop_search_receiver, L_loop_search_empty;
2164   Label L_restart, L_found_recv, L_found_empty, L_count_update;
2165 
2166   // The code here recognizes three major cases:
2167   //   A. Fastest: receiver found in the table
2168   //   B. Fast: no receiver in the table, and the table is full
2169   //   C. Slow: no receiver in the table, free slots in the table
2170   //
2171   // The case A performance is most important, as perfectly-behaved code would end up
2172   // there, especially with larger TypeProfileWidth. The case B performance is
2173   // important as well, this is where bulk of code would land for normally megamorphic
2174   // cases. The case C performance is not essential, its job is to deal with installation
2175   // races, we optimize for code density instead. Case C needs to make sure that receiver
2176   // rows are only claimed once. This makes sure we never overwrite a row for another
2177   // receiver and never duplicate the receivers in the list, making profile type-accurate.
2178   //
2179   // It is very tempting to handle these cases in a single loop, and claim the first slot
2180   // without checking the rest of the table. But, profiling code should tolerate free slots
2181   // in the table, as class unloading can clear them. After such cleanup, the receiver
2182   // we need might be _after_ the free slot. Therefore, we need to let at least full scan
2183   // to complete, before trying to install new slots. Splitting the code in several tight
2184   // loops also helpfully optimizes for cases A and B.
2185   //
2186   // This code is effectively:
2187   //
2188   // restart:
2189   //   // Fastest: receiver is already installed
2190   //   for (i = 0; i < receiver_count(); i++) {
2191   //     if (receiver(i) == recv) goto found_recv(i);
2192   //   }
2193   //
2194   //   // Fast: no receiver, but profile is not full
2195   //   for (i = 0; i < receiver_count(); i++) {
2196   //     if (receiver(i) == null) goto found_null(i);
2197   //   }
2198   //
2199   //   // Slow: profile is full, polymorphic case
2200   //   count++;
2201   //   return
2202   //
2203   //   // Slow: try to install receiver
2204   // found_null(i):
2205   //   CAS(&receiver(i), null, recv);
2206   //   goto restart
2207   //
2208   // found_recv(i):
2209   //   *receiver_count(i)++
2210   //
2211 
2212   bind(L_restart);
2213 
2214   // Fastest: receiver is already installed
2215   mov(offset, base_receiver_offset);
2216   bind(L_loop_search_receiver);
2217     ldr(rscratch1, Address(mdp, offset));
2218     cmp(rscratch1, recv);
2219     br(Assembler::EQ, L_found_recv);
2220   add(offset, offset, receiver_step);
2221   sub(rscratch1, offset, end_receiver_offset);
2222   cbnz(rscratch1, L_loop_search_receiver);
2223 
2224   // Fast: no receiver, but profile is not full
2225   mov(offset, base_receiver_offset);
2226   bind(L_loop_search_empty);
2227     ldr(rscratch1, Address(mdp, offset));
2228     cbz(rscratch1, L_found_empty);
2229   add(offset, offset, receiver_step);
2230   sub(rscratch1, offset, end_receiver_offset);
2231   cbnz(rscratch1, L_loop_search_empty);
2232 
2233   // Slow: Receiver is not found and table is full.
2234   // Increment polymorphic counter instead of receiver slot.
2235   mov(offset, poly_count_offset);
2236   b(L_count_update);
2237 
2238   // Slowest: try to install receiver
2239   bind(L_found_empty);
2240 
2241   // Atomically swing receiver slot: null -> recv.
2242   //
2243   // The update uses CAS, which clobbers rscratch1. Therefore, rscratch2
2244   // is used to hold the destination address. This is safe because the
2245   // offset is no longer needed after the address is computed.
2246 
2247   lea(rscratch2, Address(mdp, offset));
2248   cmpxchg(/*addr*/ rscratch2, /*expected*/ zr, /*new*/ recv, Assembler::xword,
2249           /*acquire*/ false, /*release*/ false, /*weak*/ true, noreg);
2250 
2251   // CAS success means the slot now has the receiver we want. CAS failure means
2252   // something had claimed the slot concurrently: it can be the same receiver we want,
2253   // or something else. Since this is a slow path, we can optimize for code density,
2254   // and just restart the search from the beginning.
2255   b(L_restart);
2256 
2257   // Found a receiver, convert its slot offset to corresponding count offset.
2258   bind(L_found_recv);
2259   add(offset, offset, receiver_to_count_step);
2260 
2261   // Finally, update the counter
2262   bind(L_count_update);
2263   increment(Address(mdp, offset), DataLayout::counter_increment);
2264 }
2265 
2266 
2267 void MacroAssembler::call_VM_leaf_base(address entry_point,
2268                                        int number_of_arguments,
2269                                        Label *retaddr) {
2270   Label E, L;
2271 
2272   stp(rscratch1, rmethod, Address(pre(sp, -2 * wordSize)));
2273 
2274   mov(rscratch1, RuntimeAddress(entry_point));
2275   blr(rscratch1);
2276   if (retaddr)
2277     bind(*retaddr);
2278 
2279   ldp(rscratch1, rmethod, Address(post(sp, 2 * wordSize)));
2280 }
2281 
2282 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2283   call_VM_leaf_base(entry_point, number_of_arguments);
2284 }
2285 
2286 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2287   pass_arg0(this, arg_0);
2288   call_VM_leaf_base(entry_point, 1);
2289 }
2290 
2291 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2292   assert_different_registers(arg_1, c_rarg0);
2293   pass_arg0(this, arg_0);
2294   pass_arg1(this, arg_1);
2295   call_VM_leaf_base(entry_point, 2);
2296 }
2297 
2298 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0,
2299                                   Register arg_1, Register arg_2) {
2300   assert_different_registers(arg_1, c_rarg0);
2301   assert_different_registers(arg_2, c_rarg0, c_rarg1);
2302   pass_arg0(this, arg_0);
2303   pass_arg1(this, arg_1);
2304   pass_arg2(this, arg_2);
2305   call_VM_leaf_base(entry_point, 3);
2306 }
2307 
2308 void MacroAssembler::super_call_VM_leaf(address entry_point) {
2309   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2310 }
2311 
2312 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2313   pass_arg0(this, arg_0);
2314   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2315 }
2316 
2317 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2318 
2319   assert_different_registers(arg_0, c_rarg1);
2320   pass_arg1(this, arg_1);
2321   pass_arg0(this, arg_0);
2322   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2323 }
2324 
2325 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2326   assert_different_registers(arg_0, c_rarg1, c_rarg2);
2327   assert_different_registers(arg_1, c_rarg2);
2328   pass_arg2(this, arg_2);
2329   pass_arg1(this, arg_1);
2330   pass_arg0(this, arg_0);
2331   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2332 }
2333 
2334 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2335   assert_different_registers(arg_0, c_rarg1, c_rarg2, c_rarg3);
2336   assert_different_registers(arg_1, c_rarg2, c_rarg3);
2337   assert_different_registers(arg_2, c_rarg3);
2338   pass_arg3(this, arg_3);
2339   pass_arg2(this, arg_2);
2340   pass_arg1(this, arg_1);
2341   pass_arg0(this, arg_0);
2342   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2343 }
2344 
2345 void MacroAssembler::null_check(Register reg, int offset) {
2346   if (needs_explicit_null_check(offset)) {
2347     // provoke OS null exception if reg is null by
2348     // accessing M[reg] w/o changing any registers
2349     // NOTE: this is plenty to provoke a segv
2350     ldr(zr, Address(reg));
2351   } else {
2352     // nothing to do, (later) access of M[reg + offset]
2353     // will provoke OS null exception if reg is null
2354   }
2355 }
2356 
2357 void MacroAssembler::test_markword_is_inline_type(Register markword, Label& is_inline_type) {
2358   assert_different_registers(markword, rscratch2);
2359   mov(rscratch2, markWord::inline_type_pattern_mask);
2360   andr(markword, markword, rscratch2);
2361   mov(rscratch2, markWord::inline_type_pattern);
2362   cmp(markword, rscratch2);
2363   br(Assembler::EQ, is_inline_type);
2364 }
2365 
2366 void MacroAssembler::test_oop_is_not_inline_type(Register object, Register tmp, Label& not_inline_type, bool can_be_null) {
2367   assert_different_registers(tmp, rscratch1);
2368   if (can_be_null) {
2369     cbz(object, not_inline_type);
2370   }
2371   const int is_inline_type_mask = markWord::inline_type_pattern;
2372   ldr(tmp, Address(object, oopDesc::mark_offset_in_bytes()));
2373   mov(rscratch1, is_inline_type_mask);
2374   andr(tmp, tmp, rscratch1);
2375   cmp(tmp, rscratch1);
2376   br(Assembler::NE, not_inline_type);
2377 }
2378 
2379 void MacroAssembler::test_field_is_null_free_inline_type(Register flags, Register temp_reg, Label& is_null_free_inline_type) {
2380   assert(temp_reg == noreg, "not needed"); // keep signature uniform with x86
2381   tbnz(flags, ResolvedFieldEntry::is_null_free_inline_type_shift, is_null_free_inline_type);
2382 }
2383 
2384 void MacroAssembler::test_field_is_not_null_free_inline_type(Register flags, Register temp_reg, Label& not_null_free_inline_type) {
2385   assert(temp_reg == noreg, "not needed"); // keep signature uniform with x86
2386   tbz(flags, ResolvedFieldEntry::is_null_free_inline_type_shift, not_null_free_inline_type);
2387 }
2388 
2389 void MacroAssembler::test_field_is_flat(Register flags, Register temp_reg, Label& is_flat) {
2390   assert(temp_reg == noreg, "not needed"); // keep signature uniform with x86
2391   tbnz(flags, ResolvedFieldEntry::is_flat_shift, is_flat);
2392 }
2393 
2394 void MacroAssembler::test_oop_prototype_bit(Register oop, Register temp_reg, int32_t test_bit, bool jmp_set, Label& jmp_label) {
2395   Label test_mark_word;
2396   // load mark word
2397   ldr(temp_reg, Address(oop, oopDesc::mark_offset_in_bytes()));
2398   // check displaced
2399   tst(temp_reg, markWord::unlocked_value);
2400   br(Assembler::NE, test_mark_word);
2401   // slow path use klass prototype
2402   load_prototype_header(temp_reg, oop);
2403 
2404   bind(test_mark_word);
2405   andr(temp_reg, temp_reg, test_bit);
2406   if (jmp_set) {
2407     cbnz(temp_reg, jmp_label);
2408   } else {
2409     cbz(temp_reg, jmp_label);
2410   }
2411 }
2412 
2413 void MacroAssembler::test_flat_array_oop(Register oop, Register temp_reg, Label& is_flat_array) {
2414   test_oop_prototype_bit(oop, temp_reg, markWord::flat_array_bit_in_place, true, is_flat_array);
2415 }
2416 
2417 void MacroAssembler::test_non_flat_array_oop(Register oop, Register temp_reg,
2418                                                   Label&is_non_flat_array) {
2419   test_oop_prototype_bit(oop, temp_reg, markWord::flat_array_bit_in_place, false, is_non_flat_array);
2420 }
2421 
2422 void MacroAssembler::test_null_free_array_oop(Register oop, Register temp_reg, Label& is_null_free_array) {
2423   test_oop_prototype_bit(oop, temp_reg, markWord::null_free_array_bit_in_place, true, is_null_free_array);
2424 }
2425 
2426 void MacroAssembler::test_non_null_free_array_oop(Register oop, Register temp_reg, Label&is_non_null_free_array) {
2427   test_oop_prototype_bit(oop, temp_reg, markWord::null_free_array_bit_in_place, false, is_non_null_free_array);
2428 }
2429 
2430 void MacroAssembler::test_flat_array_layout(Register lh, Label& is_flat_array) {
2431   tst(lh, Klass::_lh_array_tag_flat_value_bit_inplace);
2432   br(Assembler::NE, is_flat_array);
2433 }
2434 
2435 // MacroAssembler protected routines needed to implement
2436 // public methods
2437 
2438 void MacroAssembler::mov(Register r, Address dest) {
2439   code_section()->relocate(pc(), dest.rspec());
2440   uint64_t imm64 = (uint64_t)dest.target();
2441   movptr(r, imm64);
2442 }
2443 
2444 // Move a constant pointer into r.  In AArch64 mode the virtual
2445 // address space is 48 bits in size, so we only need three
2446 // instructions to create a patchable instruction sequence that can
2447 // reach anywhere.
2448 void MacroAssembler::movptr(Register r, uintptr_t imm64) {
2449 #ifndef PRODUCT
2450   {
2451     char buffer[64];
2452     os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX64, (uint64_t)imm64);
2453     block_comment(buffer);
2454   }
2455 #endif
2456   assert(imm64 < (1ull << 48), "48-bit overflow in address constant");
2457   movz(r, imm64 & 0xffff);
2458   imm64 >>= 16;
2459   movk(r, imm64 & 0xffff, 16);
2460   imm64 >>= 16;
2461   movk(r, imm64 & 0xffff, 32);
2462 }
2463 
2464 // Macro to mov replicated immediate to vector register.
2465 // imm64: only the lower 8/16/32 bits are considered for B/H/S type. That is,
2466 //        the upper 56/48/32 bits must be zeros for B/H/S type.
2467 // Vd will get the following values for different arrangements in T
2468 //   imm64 == hex 000000gh  T8B:  Vd = ghghghghghghghgh
2469 //   imm64 == hex 000000gh  T16B: Vd = ghghghghghghghghghghghghghghghgh
2470 //   imm64 == hex 0000efgh  T4H:  Vd = efghefghefghefgh
2471 //   imm64 == hex 0000efgh  T8H:  Vd = efghefghefghefghefghefghefghefgh
2472 //   imm64 == hex abcdefgh  T2S:  Vd = abcdefghabcdefgh
2473 //   imm64 == hex abcdefgh  T4S:  Vd = abcdefghabcdefghabcdefghabcdefgh
2474 //   imm64 == hex abcdefgh  T1D:  Vd = 00000000abcdefgh
2475 //   imm64 == hex abcdefgh  T2D:  Vd = 00000000abcdefgh00000000abcdefgh
2476 // Clobbers rscratch1
2477 void MacroAssembler::mov(FloatRegister Vd, SIMD_Arrangement T, uint64_t imm64) {
2478   assert(T != T1Q, "unsupported");
2479   if (T == T1D || T == T2D) {
2480     int imm = operand_valid_for_movi_immediate(imm64, T);
2481     if (-1 != imm) {
2482       movi(Vd, T, imm);
2483     } else {
2484       mov(rscratch1, imm64);
2485       dup(Vd, T, rscratch1);
2486     }
2487     return;
2488   }
2489 
2490 #ifdef ASSERT
2491   if (T == T8B || T == T16B) assert((imm64 & ~0xff) == 0, "extraneous bits (T8B/T16B)");
2492   if (T == T4H || T == T8H) assert((imm64  & ~0xffff) == 0, "extraneous bits (T4H/T8H)");
2493   if (T == T2S || T == T4S) assert((imm64  & ~0xffffffff) == 0, "extraneous bits (T2S/T4S)");
2494 #endif
2495   int shift = operand_valid_for_movi_immediate(imm64, T);
2496   uint32_t imm32 = imm64 & 0xffffffffULL;
2497   if (shift >= 0) {
2498     movi(Vd, T, (imm32 >> shift) & 0xff, shift);
2499   } else {
2500     movw(rscratch1, imm32);
2501     dup(Vd, T, rscratch1);
2502   }
2503 }
2504 
2505 void MacroAssembler::mov_immediate64(Register dst, uint64_t imm64)
2506 {
2507 #ifndef PRODUCT
2508   {
2509     char buffer[64];
2510     os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX64, imm64);
2511     block_comment(buffer);
2512   }
2513 #endif
2514   if (operand_valid_for_logical_immediate(false, imm64)) {
2515     orr(dst, zr, imm64);
2516   } else {
2517     // we can use a combination of MOVZ or MOVN with
2518     // MOVK to build up the constant
2519     uint64_t imm_h[4];
2520     int zero_count = 0;
2521     int neg_count = 0;
2522     int i;
2523     for (i = 0; i < 4; i++) {
2524       imm_h[i] = ((imm64 >> (i * 16)) & 0xffffL);
2525       if (imm_h[i] == 0) {
2526         zero_count++;
2527       } else if (imm_h[i] == 0xffffL) {
2528         neg_count++;
2529       }
2530     }
2531     if (zero_count == 4) {
2532       // one MOVZ will do
2533       movz(dst, 0);
2534     } else if (neg_count == 4) {
2535       // one MOVN will do
2536       movn(dst, 0);
2537     } else if (zero_count == 3) {
2538       for (i = 0; i < 4; i++) {
2539         if (imm_h[i] != 0L) {
2540           movz(dst, (uint32_t)imm_h[i], (i << 4));
2541           break;
2542         }
2543       }
2544     } else if (neg_count == 3) {
2545       // one MOVN will do
2546       for (int i = 0; i < 4; i++) {
2547         if (imm_h[i] != 0xffffL) {
2548           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2549           break;
2550         }
2551       }
2552     } else if (zero_count == 2) {
2553       // one MOVZ and one MOVK will do
2554       for (i = 0; i < 3; i++) {
2555         if (imm_h[i] != 0L) {
2556           movz(dst, (uint32_t)imm_h[i], (i << 4));
2557           i++;
2558           break;
2559         }
2560       }
2561       for (;i < 4; i++) {
2562         if (imm_h[i] != 0L) {
2563           movk(dst, (uint32_t)imm_h[i], (i << 4));
2564         }
2565       }
2566     } else if (neg_count == 2) {
2567       // one MOVN and one MOVK will do
2568       for (i = 0; i < 4; i++) {
2569         if (imm_h[i] != 0xffffL) {
2570           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2571           i++;
2572           break;
2573         }
2574       }
2575       for (;i < 4; i++) {
2576         if (imm_h[i] != 0xffffL) {
2577           movk(dst, (uint32_t)imm_h[i], (i << 4));
2578         }
2579       }
2580     } else if (zero_count == 1) {
2581       // one MOVZ and two MOVKs will do
2582       for (i = 0; i < 4; i++) {
2583         if (imm_h[i] != 0L) {
2584           movz(dst, (uint32_t)imm_h[i], (i << 4));
2585           i++;
2586           break;
2587         }
2588       }
2589       for (;i < 4; i++) {
2590         if (imm_h[i] != 0x0L) {
2591           movk(dst, (uint32_t)imm_h[i], (i << 4));
2592         }
2593       }
2594     } else if (neg_count == 1) {
2595       // one MOVN and two MOVKs will do
2596       for (i = 0; i < 4; i++) {
2597         if (imm_h[i] != 0xffffL) {
2598           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2599           i++;
2600           break;
2601         }
2602       }
2603       for (;i < 4; i++) {
2604         if (imm_h[i] != 0xffffL) {
2605           movk(dst, (uint32_t)imm_h[i], (i << 4));
2606         }
2607       }
2608     } else {
2609       // use a MOVZ and 3 MOVKs (makes it easier to debug)
2610       movz(dst, (uint32_t)imm_h[0], 0);
2611       for (i = 1; i < 4; i++) {
2612         movk(dst, (uint32_t)imm_h[i], (i << 4));
2613       }
2614     }
2615   }
2616 }
2617 
2618 void MacroAssembler::mov_immediate32(Register dst, uint32_t imm32)
2619 {
2620 #ifndef PRODUCT
2621     {
2622       char buffer[64];
2623       os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX32, imm32);
2624       block_comment(buffer);
2625     }
2626 #endif
2627   if (operand_valid_for_logical_immediate(true, imm32)) {
2628     orrw(dst, zr, imm32);
2629   } else {
2630     // we can use MOVZ, MOVN or two calls to MOVK to build up the
2631     // constant
2632     uint32_t imm_h[2];
2633     imm_h[0] = imm32 & 0xffff;
2634     imm_h[1] = ((imm32 >> 16) & 0xffff);
2635     if (imm_h[0] == 0) {
2636       movzw(dst, imm_h[1], 16);
2637     } else if (imm_h[0] == 0xffff) {
2638       movnw(dst, imm_h[1] ^ 0xffff, 16);
2639     } else if (imm_h[1] == 0) {
2640       movzw(dst, imm_h[0], 0);
2641     } else if (imm_h[1] == 0xffff) {
2642       movnw(dst, imm_h[0] ^ 0xffff, 0);
2643     } else {
2644       // use a MOVZ and MOVK (makes it easier to debug)
2645       movzw(dst, imm_h[0], 0);
2646       movkw(dst, imm_h[1], 16);
2647     }
2648   }
2649 }
2650 
2651 // Form an address from base + offset in Rd.  Rd may or may
2652 // not actually be used: you must use the Address that is returned.
2653 // It is up to you to ensure that the shift provided matches the size
2654 // of your data.
2655 Address MacroAssembler::form_address(Register Rd, Register base, int64_t byte_offset, int shift) {
2656   if (Address::offset_ok_for_immed(byte_offset, shift))
2657     // It fits; no need for any heroics
2658     return Address(base, byte_offset);
2659 
2660   // Don't do anything clever with negative or misaligned offsets
2661   unsigned mask = (1 << shift) - 1;
2662   if (byte_offset < 0 || byte_offset & mask) {
2663     mov(Rd, byte_offset);
2664     add(Rd, base, Rd);
2665     return Address(Rd);
2666   }
2667 
2668   // See if we can do this with two 12-bit offsets
2669   {
2670     uint64_t word_offset = byte_offset >> shift;
2671     uint64_t masked_offset = word_offset & 0xfff000;
2672     if (Address::offset_ok_for_immed(word_offset - masked_offset, 0)
2673         && Assembler::operand_valid_for_add_sub_immediate(masked_offset << shift)) {
2674       add(Rd, base, masked_offset << shift);
2675       word_offset -= masked_offset;
2676       return Address(Rd, word_offset << shift);
2677     }
2678   }
2679 
2680   // Do it the hard way
2681   mov(Rd, byte_offset);
2682   add(Rd, base, Rd);
2683   return Address(Rd);
2684 }
2685 
2686 int MacroAssembler::corrected_idivl(Register result, Register ra, Register rb,
2687                                     bool want_remainder, Register scratch)
2688 {
2689   // Full implementation of Java idiv and irem.  The function
2690   // returns the (pc) offset of the div instruction - may be needed
2691   // for implicit exceptions.
2692   //
2693   // constraint : ra/rb =/= scratch
2694   //         normal case
2695   //
2696   // input : ra: dividend
2697   //         rb: divisor
2698   //
2699   // result: either
2700   //         quotient  (= ra idiv rb)
2701   //         remainder (= ra irem rb)
2702 
2703   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
2704 
2705   int idivl_offset = offset();
2706   if (! want_remainder) {
2707     sdivw(result, ra, rb);
2708   } else {
2709     sdivw(scratch, ra, rb);
2710     Assembler::msubw(result, scratch, rb, ra);
2711   }
2712 
2713   return idivl_offset;
2714 }
2715 
2716 int MacroAssembler::corrected_idivq(Register result, Register ra, Register rb,
2717                                     bool want_remainder, Register scratch)
2718 {
2719   // Full implementation of Java ldiv and lrem.  The function
2720   // returns the (pc) offset of the div instruction - may be needed
2721   // for implicit exceptions.
2722   //
2723   // constraint : ra/rb =/= scratch
2724   //         normal case
2725   //
2726   // input : ra: dividend
2727   //         rb: divisor
2728   //
2729   // result: either
2730   //         quotient  (= ra idiv rb)
2731   //         remainder (= ra irem rb)
2732 
2733   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
2734 
2735   int idivq_offset = offset();
2736   if (! want_remainder) {
2737     sdiv(result, ra, rb);
2738   } else {
2739     sdiv(scratch, ra, rb);
2740     Assembler::msub(result, scratch, rb, ra);
2741   }
2742 
2743   return idivq_offset;
2744 }
2745 
2746 void MacroAssembler::membar(Membar_mask_bits order_constraint) {
2747   address prev = pc() - NativeMembar::instruction_size;
2748   address last = code()->last_merge_candidate();
2749   if (last != nullptr && nativeInstruction_at(last)->is_Membar() && prev == last) {
2750     NativeMembar *bar = NativeMembar_at(prev);
2751     if (AlwaysMergeDMB) {
2752       bar->set_kind(bar->get_kind() | order_constraint);
2753       BLOCK_COMMENT("merged membar(always)");
2754       return;
2755     }
2756     // Don't promote DMB ST|DMB LD to DMB (a full barrier) because
2757     // doing so would introduce a StoreLoad which the caller did not
2758     // intend
2759     if (bar->get_kind() == order_constraint
2760         || bar->get_kind() == AnyAny
2761         || order_constraint == AnyAny) {
2762       // We are merging two memory barrier instructions.  On AArch64 we
2763       // can do this simply by ORing them together.
2764       bar->set_kind(bar->get_kind() | order_constraint);
2765       BLOCK_COMMENT("merged membar");
2766       return;
2767     } else {
2768       // A special case like "DMB ST;DMB LD;DMB ST", the last DMB can be skipped.
2769       // We need to check the second-to-last instruction, only if it is inside
2770       // the current code section.
2771       address prev2 = prev - NativeMembar::instruction_size;
2772       if (prev2 >= begin() && last != code()->last_label() && nativeInstruction_at(prev2)->is_Membar()) {
2773         NativeMembar *bar2 = NativeMembar_at(prev2);
2774         assert(bar2->get_kind() == order_constraint, "it should be merged before");
2775         BLOCK_COMMENT("merged membar(elided)");
2776         return;
2777       }
2778     }
2779   }
2780   code()->set_last_merge_candidate(pc());
2781   dmb(Assembler::barrier(order_constraint));
2782 }
2783 
2784 bool MacroAssembler::try_merge_ldst(Register rt, const Address &adr, size_t size_in_bytes, bool is_store) {
2785   if (ldst_can_merge(rt, adr, size_in_bytes, is_store)) {
2786     merge_ldst(rt, adr, size_in_bytes, is_store);
2787     code()->clear_last_merge_candidate();
2788     return true;
2789   } else {
2790     assert(size_in_bytes == 8 || size_in_bytes == 4, "only 8 bytes or 4 bytes load/store is supported.");
2791     const uint64_t mask = size_in_bytes - 1;
2792     if (adr.getMode() == Address::base_plus_offset &&
2793         (adr.offset() & mask) == 0) { // only supports base_plus_offset.
2794       code()->set_last_merge_candidate(pc());
2795     }
2796     return false;
2797   }
2798 }
2799 
2800 void MacroAssembler::ldr(Register Rx, const Address &adr) {
2801   // We always try to merge two adjacent loads into one ldp.
2802   if (!try_merge_ldst(Rx, adr, 8, false)) {
2803     Assembler::ldr(Rx, adr);
2804   }
2805 }
2806 
2807 void MacroAssembler::ldrw(Register Rw, const Address &adr) {
2808   // We always try to merge two adjacent loads into one ldp.
2809   if (!try_merge_ldst(Rw, adr, 4, false)) {
2810     Assembler::ldrw(Rw, adr);
2811   }
2812 }
2813 
2814 void MacroAssembler::str(Register Rx, const Address &adr) {
2815   // We always try to merge two adjacent stores into one stp.
2816   if (!try_merge_ldst(Rx, adr, 8, true)) {
2817     Assembler::str(Rx, adr);
2818   }
2819 }
2820 
2821 void MacroAssembler::strw(Register Rw, const Address &adr) {
2822   // We always try to merge two adjacent stores into one stp.
2823   if (!try_merge_ldst(Rw, adr, 4, true)) {
2824     Assembler::strw(Rw, adr);
2825   }
2826 }
2827 
2828 // MacroAssembler routines found actually to be needed
2829 
2830 void MacroAssembler::push(Register src)
2831 {
2832   str(src, Address(pre(esp, -1 * wordSize)));
2833 }
2834 
2835 void MacroAssembler::pop(Register dst)
2836 {
2837   ldr(dst, Address(post(esp, 1 * wordSize)));
2838 }
2839 
2840 // Note: load_unsigned_short used to be called load_unsigned_word.
2841 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
2842   int off = offset();
2843   ldrh(dst, src);
2844   return off;
2845 }
2846 
2847 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
2848   int off = offset();
2849   ldrb(dst, src);
2850   return off;
2851 }
2852 
2853 int MacroAssembler::load_signed_short(Register dst, Address src) {
2854   int off = offset();
2855   ldrsh(dst, src);
2856   return off;
2857 }
2858 
2859 int MacroAssembler::load_signed_byte(Register dst, Address src) {
2860   int off = offset();
2861   ldrsb(dst, src);
2862   return off;
2863 }
2864 
2865 int MacroAssembler::load_signed_short32(Register dst, Address src) {
2866   int off = offset();
2867   ldrshw(dst, src);
2868   return off;
2869 }
2870 
2871 int MacroAssembler::load_signed_byte32(Register dst, Address src) {
2872   int off = offset();
2873   ldrsbw(dst, src);
2874   return off;
2875 }
2876 
2877 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed) {
2878   switch (size_in_bytes) {
2879   case  8:  ldr(dst, src); break;
2880   case  4:  ldrw(dst, src); break;
2881   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
2882   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
2883   default:  ShouldNotReachHere();
2884   }
2885 }
2886 
2887 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes) {
2888   switch (size_in_bytes) {
2889   case  8:  str(src, dst); break;
2890   case  4:  strw(src, dst); break;
2891   case  2:  strh(src, dst); break;
2892   case  1:  strb(src, dst); break;
2893   default:  ShouldNotReachHere();
2894   }
2895 }
2896 
2897 void MacroAssembler::narrow_subword_type(Register reg, BasicType bt) {
2898   assert(is_subword_type(bt), "required");
2899   switch (bt) {
2900   case T_BOOLEAN: andw(reg, reg, 1); break;
2901   case T_BYTE:    sxtbw(reg, reg); break;
2902   case T_CHAR:    uxthw(reg, reg); break;
2903   case T_SHORT:   sxthw(reg, reg); break;
2904   default:        ShouldNotReachHere();
2905   }
2906 }
2907 
2908 void MacroAssembler::decrementw(Register reg, int value)
2909 {
2910   if (value < 0)  { incrementw(reg, -value);      return; }
2911   if (value == 0) {                               return; }
2912   if (value < (1 << 12)) { subw(reg, reg, value); return; }
2913   /* else */ {
2914     guarantee(reg != rscratch2, "invalid dst for register decrement");
2915     movw(rscratch2, (unsigned)value);
2916     subw(reg, reg, rscratch2);
2917   }
2918 }
2919 
2920 void MacroAssembler::decrement(Register reg, int value)
2921 {
2922   if (value < 0)  { increment(reg, -value);      return; }
2923   if (value == 0) {                              return; }
2924   if (value < (1 << 12)) { sub(reg, reg, value); return; }
2925   /* else */ {
2926     assert(reg != rscratch2, "invalid dst for register decrement");
2927     mov(rscratch2, (uint64_t)value);
2928     sub(reg, reg, rscratch2);
2929   }
2930 }
2931 
2932 void MacroAssembler::decrementw(Address dst, int value)
2933 {
2934   assert(!dst.uses(rscratch1), "invalid dst for address decrement");
2935   if (dst.getMode() == Address::literal) {
2936     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2937     lea(rscratch2, dst);
2938     dst = Address(rscratch2);
2939   }
2940   ldrw(rscratch1, dst);
2941   decrementw(rscratch1, value);
2942   strw(rscratch1, dst);
2943 }
2944 
2945 void MacroAssembler::decrement(Address dst, int value)
2946 {
2947   assert(!dst.uses(rscratch1), "invalid address for decrement");
2948   if (dst.getMode() == Address::literal) {
2949     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2950     lea(rscratch2, dst);
2951     dst = Address(rscratch2);
2952   }
2953   ldr(rscratch1, dst);
2954   decrement(rscratch1, value);
2955   str(rscratch1, dst);
2956 }
2957 
2958 void MacroAssembler::incrementw(Register reg, int value)
2959 {
2960   if (value < 0)  { decrementw(reg, -value);      return; }
2961   if (value == 0) {                               return; }
2962   if (value < (1 << 12)) { addw(reg, reg, value); return; }
2963   /* else */ {
2964     assert(reg != rscratch2, "invalid dst for register increment");
2965     movw(rscratch2, (unsigned)value);
2966     addw(reg, reg, rscratch2);
2967   }
2968 }
2969 
2970 void MacroAssembler::increment(Register reg, int value)
2971 {
2972   if (value < 0)  { decrement(reg, -value);      return; }
2973   if (value == 0) {                              return; }
2974   if (value < (1 << 12)) { add(reg, reg, value); return; }
2975   /* else */ {
2976     assert(reg != rscratch2, "invalid dst for register increment");
2977     movw(rscratch2, (unsigned)value);
2978     add(reg, reg, rscratch2);
2979   }
2980 }
2981 
2982 void MacroAssembler::incrementw(Address dst, int value)
2983 {
2984   assert(!dst.uses(rscratch1), "invalid dst for address increment");
2985   if (dst.getMode() == Address::literal) {
2986     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2987     lea(rscratch2, dst);
2988     dst = Address(rscratch2);
2989   }
2990   ldrw(rscratch1, dst);
2991   incrementw(rscratch1, value);
2992   strw(rscratch1, dst);
2993 }
2994 
2995 void MacroAssembler::increment(Address dst, int value)
2996 {
2997   assert(!dst.uses(rscratch1), "invalid dst for address increment");
2998   if (dst.getMode() == Address::literal) {
2999     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
3000     lea(rscratch2, dst);
3001     dst = Address(rscratch2);
3002   }
3003   ldr(rscratch1, dst);
3004   increment(rscratch1, value);
3005   str(rscratch1, dst);
3006 }
3007 
3008 // Push lots of registers in the bit set supplied.  Don't push sp.
3009 // Return the number of words pushed
3010 int MacroAssembler::push(RegSet regset, Register stack) {
3011   if (regset.bits() == 0) {
3012     return 0;
3013   }
3014   auto bitset = integer_cast<unsigned int>(regset.bits());
3015   int words_pushed = 0;
3016 
3017   // Scan bitset to accumulate register pairs
3018   unsigned char regs[32];
3019   int count = 0;
3020   for (int reg = 0; reg <= 30; reg++) {
3021     if (1 & bitset)
3022       regs[count++] = reg;
3023     bitset >>= 1;
3024   }
3025   regs[count++] = zr->raw_encoding();
3026   count &= ~1;  // Only push an even number of regs
3027 
3028   if (count) {
3029     stp(as_Register(regs[0]), as_Register(regs[1]),
3030        Address(pre(stack, -count * wordSize)));
3031     words_pushed += 2;
3032   }
3033   for (int i = 2; i < count; i += 2) {
3034     stp(as_Register(regs[i]), as_Register(regs[i+1]),
3035        Address(stack, i * wordSize));
3036     words_pushed += 2;
3037   }
3038 
3039   assert(words_pushed == count, "oops, pushed != count");
3040 
3041   return count;
3042 }
3043 
3044 int MacroAssembler::pop(RegSet regset, Register stack) {
3045   if (regset.bits() == 0) {
3046     return 0;
3047   }
3048   auto bitset = integer_cast<unsigned int>(regset.bits());
3049   int words_pushed = 0;
3050 
3051   // Scan bitset to accumulate register pairs
3052   unsigned char regs[32];
3053   int count = 0;
3054   for (int reg = 0; reg <= 30; reg++) {
3055     if (1 & bitset)
3056       regs[count++] = reg;
3057     bitset >>= 1;
3058   }
3059   regs[count++] = zr->raw_encoding();
3060   count &= ~1;
3061 
3062   for (int i = 2; i < count; i += 2) {
3063     ldp(as_Register(regs[i]), as_Register(regs[i+1]),
3064        Address(stack, i * wordSize));
3065     words_pushed += 2;
3066   }
3067   if (count) {
3068     ldp(as_Register(regs[0]), as_Register(regs[1]),
3069        Address(post(stack, count * wordSize)));
3070     words_pushed += 2;
3071   }
3072 
3073   assert(words_pushed == count, "oops, pushed != count");
3074 
3075   return count;
3076 }
3077 
3078 // Push lots of registers in the bit set supplied.  Don't push sp.
3079 // Return the number of dwords pushed
3080 int MacroAssembler::push_fp(FloatRegSet regset, Register stack, FpPushPopMode mode) {
3081   if (regset.bits() == 0) {
3082     return 0;
3083   }
3084   auto bitset = integer_cast<unsigned int>(regset.bits());
3085   int words_pushed = 0;
3086   bool use_sve = false;
3087   int sve_vector_size_in_bytes = 0;
3088 
3089 #ifdef COMPILER2
3090   use_sve = Matcher::supports_scalable_vector();
3091   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
3092 #endif
3093 
3094   // Scan bitset to accumulate register pairs
3095   unsigned char regs[32];
3096   int count = 0;
3097   for (int reg = 0; reg <= 31; reg++) {
3098     if (1 & bitset)
3099       regs[count++] = reg;
3100     bitset >>= 1;
3101   }
3102 
3103   if (count == 0) {
3104     return 0;
3105   }
3106 
3107   if (mode == PushPopFull) {
3108     if (use_sve && sve_vector_size_in_bytes > 16) {
3109       mode = PushPopSVE;
3110     } else {
3111       mode = PushPopNeon;
3112     }
3113   }
3114 
3115 #ifndef PRODUCT
3116   {
3117     char buffer[48];
3118     if (mode == PushPopSVE) {
3119       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d SVE registers", count);
3120     } else if (mode == PushPopNeon) {
3121       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d Neon registers", count);
3122     } else {
3123       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d fp registers", count);
3124     }
3125     block_comment(buffer);
3126   }
3127 #endif
3128 
3129   if (mode == PushPopSVE) {
3130     sub(stack, stack, sve_vector_size_in_bytes * count);
3131     for (int i = 0; i < count; i++) {
3132       sve_str(as_FloatRegister(regs[i]), Address(stack, i));
3133     }
3134     return count * sve_vector_size_in_bytes / 8;
3135   }
3136 
3137   if (mode == PushPopNeon) {
3138     if (count == 1) {
3139       strq(as_FloatRegister(regs[0]), Address(pre(stack, -wordSize * 2)));
3140       return 2;
3141     }
3142 
3143     bool odd = (count & 1) == 1;
3144     int push_slots = count + (odd ? 1 : 0);
3145 
3146     // Always pushing full 128 bit registers.
3147     stpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize * 2)));
3148     words_pushed += 2;
3149 
3150     for (int i = 2; i + 1 < count; i += 2) {
3151       stpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
3152       words_pushed += 2;
3153     }
3154 
3155     if (odd) {
3156       strq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
3157       words_pushed++;
3158     }
3159 
3160     assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
3161     return count * 2;
3162   }
3163 
3164   if (mode == PushPopFp) {
3165     bool odd = (count & 1) == 1;
3166     int push_slots = count + (odd ? 1 : 0);
3167 
3168     if (count == 1) {
3169       // Stack pointer must be 16 bytes aligned
3170       strd(as_FloatRegister(regs[0]), Address(pre(stack, -push_slots * wordSize)));
3171       return 1;
3172     }
3173 
3174     stpd(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize)));
3175     words_pushed += 2;
3176 
3177     for (int i = 2; i + 1 < count; i += 2) {
3178       stpd(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize));
3179       words_pushed += 2;
3180     }
3181 
3182     if (odd) {
3183       // Stack pointer must be 16 bytes aligned
3184       strd(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize));
3185       words_pushed++;
3186     }
3187 
3188     assert(words_pushed == count, "oops, pushed != count");
3189 
3190     return count;
3191   }
3192 
3193   return 0;
3194 }
3195 
3196 // Return the number of dwords popped
3197 int MacroAssembler::pop_fp(FloatRegSet regset, Register stack, FpPushPopMode mode) {
3198   if (regset.bits() == 0) {
3199     return 0;
3200   }
3201   auto bitset = integer_cast<unsigned int>(regset.bits());
3202   int words_pushed = 0;
3203   bool use_sve = false;
3204   int sve_vector_size_in_bytes = 0;
3205 
3206 #ifdef COMPILER2
3207   use_sve = Matcher::supports_scalable_vector();
3208   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
3209 #endif
3210   // Scan bitset to accumulate register pairs
3211   unsigned char regs[32];
3212   int count = 0;
3213   for (int reg = 0; reg <= 31; reg++) {
3214     if (1 & bitset)
3215       regs[count++] = reg;
3216     bitset >>= 1;
3217   }
3218 
3219   if (count == 0) {
3220     return 0;
3221   }
3222 
3223   if (mode == PushPopFull) {
3224     if (use_sve && sve_vector_size_in_bytes > 16) {
3225       mode = PushPopSVE;
3226     } else {
3227       mode = PushPopNeon;
3228     }
3229   }
3230 
3231 #ifndef PRODUCT
3232   {
3233     char buffer[48];
3234     if (mode == PushPopSVE) {
3235       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d SVE registers", count);
3236     } else if (mode == PushPopNeon) {
3237       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d Neon registers", count);
3238     } else {
3239       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d fp registers", count);
3240     }
3241     block_comment(buffer);
3242   }
3243 #endif
3244 
3245   if (mode == PushPopSVE) {
3246     for (int i = count - 1; i >= 0; i--) {
3247       sve_ldr(as_FloatRegister(regs[i]), Address(stack, i));
3248     }
3249     add(stack, stack, sve_vector_size_in_bytes * count);
3250     return count * sve_vector_size_in_bytes / 8;
3251   }
3252 
3253   if (mode == PushPopNeon) {
3254     if (count == 1) {
3255       ldrq(as_FloatRegister(regs[0]), Address(post(stack, wordSize * 2)));
3256       return 2;
3257     }
3258 
3259     bool odd = (count & 1) == 1;
3260     int push_slots = count + (odd ? 1 : 0);
3261 
3262     if (odd) {
3263       ldrq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
3264       words_pushed++;
3265     }
3266 
3267     for (int i = 2; i + 1 < count; i += 2) {
3268       ldpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
3269       words_pushed += 2;
3270     }
3271 
3272     ldpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize * 2)));
3273     words_pushed += 2;
3274 
3275     assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
3276 
3277     return count * 2;
3278   }
3279 
3280   if (mode == PushPopFp) {
3281     bool odd = (count & 1) == 1;
3282     int push_slots = count + (odd ? 1 : 0);
3283 
3284     if (count == 1) {
3285       ldrd(as_FloatRegister(regs[0]), Address(post(stack, push_slots * wordSize)));
3286       return 1;
3287     }
3288 
3289     if (odd) {
3290       ldrd(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize));
3291       words_pushed++;
3292     }
3293 
3294     for (int i = 2; i + 1 < count; i += 2) {
3295       ldpd(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize));
3296       words_pushed += 2;
3297     }
3298 
3299     ldpd(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize)));
3300     words_pushed += 2;
3301 
3302     assert(words_pushed == count, "oops, pushed != count");
3303 
3304     return count;
3305   }
3306 
3307   return 0;
3308 }
3309 
3310 // Return the number of dwords pushed
3311 int MacroAssembler::push_p(PRegSet regset, Register stack) {
3312   if (regset.bits() == 0) {
3313     return 0;
3314   }
3315   auto bitset = integer_cast<unsigned int>(regset.bits());
3316   bool use_sve = false;
3317   int sve_predicate_size_in_slots = 0;
3318 
3319 #ifdef COMPILER2
3320   use_sve = Matcher::supports_scalable_vector();
3321   if (use_sve) {
3322     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
3323   }
3324 #endif
3325 
3326   if (!use_sve) {
3327     return 0;
3328   }
3329 
3330   unsigned char regs[PRegister::number_of_registers];
3331   int count = 0;
3332   for (int reg = 0; reg < PRegister::number_of_registers; reg++) {
3333     if (1 & bitset)
3334       regs[count++] = reg;
3335     bitset >>= 1;
3336   }
3337 
3338   if (count == 0) {
3339     return 0;
3340   }
3341 
3342   int total_push_bytes = align_up(sve_predicate_size_in_slots *
3343                                   VMRegImpl::stack_slot_size * count, 16);
3344   sub(stack, stack, total_push_bytes);
3345   for (int i = 0; i < count; i++) {
3346     sve_str(as_PRegister(regs[i]), Address(stack, i));
3347   }
3348   return total_push_bytes / 8;
3349 }
3350 
3351 // Return the number of dwords popped
3352 int MacroAssembler::pop_p(PRegSet regset, Register stack) {
3353   if (regset.bits() == 0) {
3354     return 0;
3355   }
3356   auto bitset = integer_cast<unsigned int>(regset.bits());
3357   bool use_sve = false;
3358   int sve_predicate_size_in_slots = 0;
3359 
3360 #ifdef COMPILER2
3361   use_sve = Matcher::supports_scalable_vector();
3362   if (use_sve) {
3363     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
3364   }
3365 #endif
3366 
3367   if (!use_sve) {
3368     return 0;
3369   }
3370 
3371   unsigned char regs[PRegister::number_of_registers];
3372   int count = 0;
3373   for (int reg = 0; reg < PRegister::number_of_registers; reg++) {
3374     if (1 & bitset)
3375       regs[count++] = reg;
3376     bitset >>= 1;
3377   }
3378 
3379   if (count == 0) {
3380     return 0;
3381   }
3382 
3383   int total_pop_bytes = align_up(sve_predicate_size_in_slots *
3384                                  VMRegImpl::stack_slot_size * count, 16);
3385   for (int i = count - 1; i >= 0; i--) {
3386     sve_ldr(as_PRegister(regs[i]), Address(stack, i));
3387   }
3388   add(stack, stack, total_pop_bytes);
3389   return total_pop_bytes / 8;
3390 }
3391 
3392 #ifdef ASSERT
3393 void MacroAssembler::verify_heapbase(const char* msg) {
3394 #if 0
3395   assert (Universe::heap() != nullptr, "java heap should be initialized");
3396   if (!UseCompressedOops || Universe::ptr_base() == nullptr) {
3397     // rheapbase is allocated as general register
3398     return;
3399   }
3400   if (CheckCompressedOops) {
3401     Label ok;
3402     push(1 << rscratch1->encoding(), sp); // cmpptr trashes rscratch1
3403     cmpptr(rheapbase, ExternalAddress(CompressedOops::base_addr()));
3404     br(Assembler::EQ, ok);
3405     stop(msg);
3406     bind(ok);
3407     pop(1 << rscratch1->encoding(), sp);
3408   }
3409 #endif
3410 }
3411 #endif
3412 
3413 void MacroAssembler::resolve_jobject(Register value, Register tmp1, Register tmp2) {
3414   assert_different_registers(value, tmp1, tmp2);
3415   Label done, tagged, weak_tagged;
3416 
3417   cbz(value, done);           // Use null as-is.
3418   tst(value, JNIHandles::tag_mask); // Test for tag.
3419   br(Assembler::NE, tagged);
3420 
3421   // Resolve local handle
3422   access_load_at(T_OBJECT, IN_NATIVE | AS_RAW, value, Address(value, 0), tmp1, tmp2);
3423   verify_oop(value);
3424   b(done);
3425 
3426   bind(tagged);
3427   STATIC_ASSERT(JNIHandles::TypeTag::weak_global == 0b1);
3428   tbnz(value, 0, weak_tagged);    // Test for weak tag.
3429 
3430   // Resolve global handle
3431   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, -JNIHandles::TypeTag::global), tmp1, tmp2);
3432   verify_oop(value);
3433   b(done);
3434 
3435   bind(weak_tagged);
3436   // Resolve jweak.
3437   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
3438                  value, Address(value, -JNIHandles::TypeTag::weak_global), tmp1, tmp2);
3439   verify_oop(value);
3440 
3441   bind(done);
3442 }
3443 
3444 void MacroAssembler::resolve_global_jobject(Register value, Register tmp1, Register tmp2) {
3445   assert_different_registers(value, tmp1, tmp2);
3446   Label done;
3447 
3448   cbz(value, done);           // Use null as-is.
3449 
3450 #ifdef ASSERT
3451   {
3452     STATIC_ASSERT(JNIHandles::TypeTag::global == 0b10);
3453     Label valid_global_tag;
3454     tbnz(value, 1, valid_global_tag); // Test for global tag
3455     stop("non global jobject using resolve_global_jobject");
3456     bind(valid_global_tag);
3457   }
3458 #endif
3459 
3460   // Resolve global handle
3461   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, -JNIHandles::TypeTag::global), tmp1, tmp2);
3462   verify_oop(value);
3463 
3464   bind(done);
3465 }
3466 
3467 void MacroAssembler::stop(const char* msg) {
3468   // Skip AOT caching C strings in scratch buffer.
3469   const char* str = (code_section()->scratch_emit()) ? msg : AOTCodeCache::add_C_string(msg);
3470   BLOCK_COMMENT(str);
3471   // load msg into r0 so we can access it from the signal handler
3472   // ExternalAddress enables saving and restoring via the code cache
3473   lea(c_rarg0, ExternalAddress((address) str));
3474   dcps1(0xdeae);
3475 }
3476 
3477 void MacroAssembler::unimplemented(const char* what) {
3478   const char* buf = nullptr;
3479   {
3480     ResourceMark rm;
3481     stringStream ss;
3482     ss.print("unimplemented: %s", what);
3483     buf = code_string(ss.as_string());
3484   }
3485   stop(buf);
3486 }
3487 
3488 void MacroAssembler::_assert_asm(Assembler::Condition cc, const char* msg) {
3489 #ifdef ASSERT
3490   Label OK;
3491   br(cc, OK);
3492   stop(msg);
3493   bind(OK);
3494 #endif
3495 }
3496 
3497 // If a constant does not fit in an immediate field, generate some
3498 // number of MOV instructions and then perform the operation.
3499 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, uint64_t imm,
3500                                            add_sub_imm_insn insn1,
3501                                            add_sub_reg_insn insn2,
3502                                            bool is32) {
3503   assert(Rd != zr, "Rd = zr and not setting flags?");
3504   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
3505   if (fits) {
3506     (this->*insn1)(Rd, Rn, imm);
3507   } else {
3508     if (g_uabs(imm) < (1 << 24)) {
3509        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
3510        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
3511     } else {
3512        assert_different_registers(Rd, Rn);
3513        mov(Rd, imm);
3514        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
3515     }
3516   }
3517 }
3518 
3519 // Separate vsn which sets the flags. Optimisations are more restricted
3520 // because we must set the flags correctly.
3521 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, uint64_t imm,
3522                                              add_sub_imm_insn insn1,
3523                                              add_sub_reg_insn insn2,
3524                                              bool is32) {
3525   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
3526   if (fits) {
3527     (this->*insn1)(Rd, Rn, imm);
3528   } else {
3529     assert_different_registers(Rd, Rn);
3530     assert(Rd != zr, "overflow in immediate operand");
3531     mov(Rd, imm);
3532     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
3533   }
3534 }
3535 
3536 
3537 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
3538   if (increment.is_register()) {
3539     add(Rd, Rn, increment.as_register());
3540   } else {
3541     add(Rd, Rn, increment.as_constant());
3542   }
3543 }
3544 
3545 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
3546   if (increment.is_register()) {
3547     addw(Rd, Rn, increment.as_register());
3548   } else {
3549     addw(Rd, Rn, increment.as_constant());
3550   }
3551 }
3552 
3553 void MacroAssembler::sub(Register Rd, Register Rn, RegisterOrConstant decrement) {
3554   if (decrement.is_register()) {
3555     sub(Rd, Rn, decrement.as_register());
3556   } else {
3557     sub(Rd, Rn, decrement.as_constant());
3558   }
3559 }
3560 
3561 void MacroAssembler::subw(Register Rd, Register Rn, RegisterOrConstant decrement) {
3562   if (decrement.is_register()) {
3563     subw(Rd, Rn, decrement.as_register());
3564   } else {
3565     subw(Rd, Rn, decrement.as_constant());
3566   }
3567 }
3568 
3569 void MacroAssembler::reinit_heapbase()
3570 {
3571   if (UseCompressedOops) {
3572     if (Universe::is_fully_initialized() && !AOTCodeCache::is_on_for_dump()) {
3573       mov(rheapbase, CompressedOops::base());
3574     } else {
3575       lea(rheapbase, ExternalAddress(CompressedOops::base_addr()));
3576       ldr(rheapbase, Address(rheapbase));
3577     }
3578   }
3579 }
3580 
3581 // A generic CAS; success or failure is in the EQ flag.  A weak CAS
3582 // doesn't retry and may fail spuriously.  If the oldval is wanted,
3583 // Pass a register for the result, otherwise pass noreg.
3584 
3585 // Clobbers rscratch1
3586 void MacroAssembler::cmpxchg(Register addr, Register expected,
3587                              Register new_val,
3588                              enum operand_size size,
3589                              bool acquire, bool release,
3590                              bool weak,
3591                              Register result) {
3592   if (result == noreg)  result = rscratch1;
3593   BLOCK_COMMENT("cmpxchg {");
3594   if (UseLSE) {
3595     mov(result, expected);
3596     lse_cas(result, new_val, addr, size, acquire, release, /*not_pair*/ true);
3597     compare_eq(result, expected, size);
3598 #ifdef ASSERT
3599     // Poison rscratch1 which is written on !UseLSE branch
3600     mov(rscratch1, 0x1f1f1f1f1f1f1f1f);
3601 #endif
3602   } else {
3603     Label retry_load, done;
3604     prfm(Address(addr), PSTL1STRM);
3605     bind(retry_load);
3606     load_exclusive(result, addr, size, acquire);
3607     compare_eq(result, expected, size);
3608     br(Assembler::NE, done);
3609     store_exclusive(rscratch1, new_val, addr, size, release);
3610     if (weak) {
3611       cmpw(rscratch1, 0u);  // If the store fails, return NE to our caller.
3612     } else {
3613       cbnzw(rscratch1, retry_load);
3614     }
3615     bind(done);
3616   }
3617   BLOCK_COMMENT("} cmpxchg");
3618 }
3619 
3620 // A generic comparison. Only compares for equality, clobbers rscratch1.
3621 void MacroAssembler::compare_eq(Register rm, Register rn, enum operand_size size) {
3622   if (size == xword) {
3623     cmp(rm, rn);
3624   } else if (size == word) {
3625     cmpw(rm, rn);
3626   } else if (size == halfword) {
3627     eorw(rscratch1, rm, rn);
3628     ands(zr, rscratch1, 0xffff);
3629   } else if (size == byte) {
3630     eorw(rscratch1, rm, rn);
3631     ands(zr, rscratch1, 0xff);
3632   } else {
3633     ShouldNotReachHere();
3634   }
3635 }
3636 
3637 
3638 static bool different(Register a, RegisterOrConstant b, Register c) {
3639   if (b.is_constant())
3640     return a != c;
3641   else
3642     return a != b.as_register() && a != c && b.as_register() != c;
3643 }
3644 
3645 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
3646 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
3647   if (UseLSE) {                                                         \
3648     prev = prev->is_valid() ? prev : zr;                                \
3649     if (incr.is_register()) {                                           \
3650       AOP(sz, incr.as_register(), prev, addr);                          \
3651     } else {                                                            \
3652       mov(rscratch2, incr.as_constant());                               \
3653       AOP(sz, rscratch2, prev, addr);                                   \
3654     }                                                                   \
3655     return;                                                             \
3656   }                                                                     \
3657   Register result = rscratch2;                                          \
3658   if (prev->is_valid())                                                 \
3659     result = different(prev, incr, addr) ? prev : rscratch2;            \
3660                                                                         \
3661   Label retry_load;                                                     \
3662   prfm(Address(addr), PSTL1STRM);                                       \
3663   bind(retry_load);                                                     \
3664   LDXR(result, addr);                                                   \
3665   OP(rscratch1, result, incr);                                          \
3666   STXR(rscratch2, rscratch1, addr);                                     \
3667   cbnzw(rscratch2, retry_load);                                         \
3668   if (prev->is_valid() && prev != result) {                             \
3669     IOP(prev, rscratch1, incr);                                         \
3670   }                                                                     \
3671 }
3672 
3673 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
3674 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
3675 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
3676 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
3677 
3678 #undef ATOMIC_OP
3679 
3680 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
3681 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
3682   if (UseLSE) {                                                         \
3683     prev = prev->is_valid() ? prev : zr;                                \
3684     AOP(sz, newv, prev, addr);                                          \
3685     return;                                                             \
3686   }                                                                     \
3687   Register result = rscratch2;                                          \
3688   if (prev->is_valid())                                                 \
3689     result = different(prev, newv, addr) ? prev : rscratch2;            \
3690                                                                         \
3691   Label retry_load;                                                     \
3692   prfm(Address(addr), PSTL1STRM);                                       \
3693   bind(retry_load);                                                     \
3694   LDXR(result, addr);                                                   \
3695   STXR(rscratch1, newv, addr);                                          \
3696   cbnzw(rscratch1, retry_load);                                         \
3697   if (prev->is_valid() && prev != result)                               \
3698     mov(prev, result);                                                  \
3699 }
3700 
3701 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
3702 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
3703 ATOMIC_XCHG(xchgl, swpl, ldxr, stlxr, Assembler::xword)
3704 ATOMIC_XCHG(xchglw, swpl, ldxrw, stlxrw, Assembler::word)
3705 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
3706 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
3707 
3708 #undef ATOMIC_XCHG
3709 
3710 #ifndef PRODUCT
3711 extern "C" void findpc(intptr_t x);
3712 #endif
3713 
3714 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
3715 {
3716   // In order to get locks to work, we need to fake a in_VM state
3717   if (ShowMessageBoxOnError) {
3718     JavaThread* thread = JavaThread::current();
3719     thread->set_thread_state(_thread_in_vm);
3720 #ifndef PRODUCT
3721     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
3722       ttyLocker ttyl;
3723       BytecodeCounter::print();
3724     }
3725 #endif
3726     if (os::message_box(msg, "Execution stopped, print registers?")) {
3727       ttyLocker ttyl;
3728       tty->print_cr(" pc = 0x%016" PRIx64, pc);
3729 #ifndef PRODUCT
3730       tty->cr();
3731       findpc(pc);
3732       tty->cr();
3733 #endif
3734       tty->print_cr(" r0 = 0x%016" PRIx64, regs[0]);
3735       tty->print_cr(" r1 = 0x%016" PRIx64, regs[1]);
3736       tty->print_cr(" r2 = 0x%016" PRIx64, regs[2]);
3737       tty->print_cr(" r3 = 0x%016" PRIx64, regs[3]);
3738       tty->print_cr(" r4 = 0x%016" PRIx64, regs[4]);
3739       tty->print_cr(" r5 = 0x%016" PRIx64, regs[5]);
3740       tty->print_cr(" r6 = 0x%016" PRIx64, regs[6]);
3741       tty->print_cr(" r7 = 0x%016" PRIx64, regs[7]);
3742       tty->print_cr(" r8 = 0x%016" PRIx64, regs[8]);
3743       tty->print_cr(" r9 = 0x%016" PRIx64, regs[9]);
3744       tty->print_cr("r10 = 0x%016" PRIx64, regs[10]);
3745       tty->print_cr("r11 = 0x%016" PRIx64, regs[11]);
3746       tty->print_cr("r12 = 0x%016" PRIx64, regs[12]);
3747       tty->print_cr("r13 = 0x%016" PRIx64, regs[13]);
3748       tty->print_cr("r14 = 0x%016" PRIx64, regs[14]);
3749       tty->print_cr("r15 = 0x%016" PRIx64, regs[15]);
3750       tty->print_cr("r16 = 0x%016" PRIx64, regs[16]);
3751       tty->print_cr("r17 = 0x%016" PRIx64, regs[17]);
3752       tty->print_cr("r18 = 0x%016" PRIx64, regs[18]);
3753       tty->print_cr("r19 = 0x%016" PRIx64, regs[19]);
3754       tty->print_cr("r20 = 0x%016" PRIx64, regs[20]);
3755       tty->print_cr("r21 = 0x%016" PRIx64, regs[21]);
3756       tty->print_cr("r22 = 0x%016" PRIx64, regs[22]);
3757       tty->print_cr("r23 = 0x%016" PRIx64, regs[23]);
3758       tty->print_cr("r24 = 0x%016" PRIx64, regs[24]);
3759       tty->print_cr("r25 = 0x%016" PRIx64, regs[25]);
3760       tty->print_cr("r26 = 0x%016" PRIx64, regs[26]);
3761       tty->print_cr("r27 = 0x%016" PRIx64, regs[27]);
3762       tty->print_cr("r28 = 0x%016" PRIx64, regs[28]);
3763       tty->print_cr("r30 = 0x%016" PRIx64, regs[30]);
3764       tty->print_cr("r31 = 0x%016" PRIx64, regs[31]);
3765       BREAKPOINT;
3766     }
3767   }
3768   fatal("DEBUG MESSAGE: %s", msg);
3769 }
3770 
3771 RegSet MacroAssembler::call_clobbered_gp_registers() {
3772   RegSet regs = RegSet::range(r0, r17) - RegSet::of(rscratch1, rscratch2);
3773 #ifndef R18_RESERVED
3774   regs += r18_tls;
3775 #endif
3776   return regs;
3777 }
3778 
3779 void MacroAssembler::push_call_clobbered_registers_except(RegSet exclude) {
3780   int step = 4 * wordSize;
3781   push(call_clobbered_gp_registers() - exclude, sp);
3782   sub(sp, sp, step);
3783   mov(rscratch1, -step);
3784   // Push v0-v7, v16-v31.
3785   for (int i = 31; i>= 4; i -= 4) {
3786     if (i <= v7->encoding() || i >= v16->encoding())
3787       st1(as_FloatRegister(i-3), as_FloatRegister(i-2), as_FloatRegister(i-1),
3788           as_FloatRegister(i), T1D, Address(post(sp, rscratch1)));
3789   }
3790   st1(as_FloatRegister(0), as_FloatRegister(1), as_FloatRegister(2),
3791       as_FloatRegister(3), T1D, Address(sp));
3792 }
3793 
3794 void MacroAssembler::pop_call_clobbered_registers_except(RegSet exclude) {
3795   for (int i = 0; i < 32; i += 4) {
3796     if (i <= v7->encoding() || i >= v16->encoding())
3797       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3798           as_FloatRegister(i+3), T1D, Address(post(sp, 4 * wordSize)));
3799   }
3800 
3801   reinitialize_ptrue();
3802 
3803   pop(call_clobbered_gp_registers() - exclude, sp);
3804 }
3805 
3806 void MacroAssembler::push_CPU_state(bool save_vectors, bool use_sve,
3807                                     int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
3808   push(RegSet::range(r0, r29), sp); // integer registers except lr & sp
3809   if (save_vectors && use_sve && sve_vector_size_in_bytes > 16) {
3810     sub(sp, sp, sve_vector_size_in_bytes * FloatRegister::number_of_registers);
3811     for (int i = 0; i < FloatRegister::number_of_registers; i++) {
3812       sve_str(as_FloatRegister(i), Address(sp, i));
3813     }
3814   } else {
3815     int step = (save_vectors ? 8 : 4) * wordSize;
3816     mov(rscratch1, -step);
3817     sub(sp, sp, step);
3818     for (int i = 28; i >= 4; i -= 4) {
3819       st1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3820           as_FloatRegister(i+3), save_vectors ? T2D : T1D, Address(post(sp, rscratch1)));
3821     }
3822     st1(v0, v1, v2, v3, save_vectors ? T2D : T1D, sp);
3823   }
3824   if (save_vectors && use_sve && total_predicate_in_bytes > 0) {
3825     sub(sp, sp, total_predicate_in_bytes);
3826     for (int i = 0; i < PRegister::number_of_registers; i++) {
3827       sve_str(as_PRegister(i), Address(sp, i));
3828     }
3829   }
3830 }
3831 
3832 void MacroAssembler::pop_CPU_state(bool restore_vectors, bool use_sve,
3833                                    int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
3834   if (restore_vectors && use_sve && total_predicate_in_bytes > 0) {
3835     for (int i = PRegister::number_of_registers - 1; i >= 0; i--) {
3836       sve_ldr(as_PRegister(i), Address(sp, i));
3837     }
3838     add(sp, sp, total_predicate_in_bytes);
3839   }
3840   if (restore_vectors && use_sve && sve_vector_size_in_bytes > 16) {
3841     for (int i = FloatRegister::number_of_registers - 1; i >= 0; i--) {
3842       sve_ldr(as_FloatRegister(i), Address(sp, i));
3843     }
3844     add(sp, sp, sve_vector_size_in_bytes * FloatRegister::number_of_registers);
3845   } else {
3846     int step = (restore_vectors ? 8 : 4) * wordSize;
3847     for (int i = 0; i <= 28; i += 4)
3848       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3849           as_FloatRegister(i+3), restore_vectors ? T2D : T1D, Address(post(sp, step)));
3850   }
3851 
3852   // We may use predicate registers and rely on ptrue with SVE,
3853   // regardless of wide vector (> 8 bytes) used or not.
3854   if (use_sve) {
3855     reinitialize_ptrue();
3856   }
3857 
3858   // integer registers except lr & sp
3859   pop(RegSet::range(r0, r17), sp);
3860 #ifdef R18_RESERVED
3861   ldp(zr, r19, Address(post(sp, 2 * wordSize)));
3862   pop(RegSet::range(r20, r29), sp);
3863 #else
3864   pop(RegSet::range(r18_tls, r29), sp);
3865 #endif
3866 }
3867 
3868 /**
3869  * Helpers for multiply_to_len().
3870  */
3871 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
3872                                      Register src1, Register src2) {
3873   adds(dest_lo, dest_lo, src1);
3874   adc(dest_hi, dest_hi, zr);
3875   adds(dest_lo, dest_lo, src2);
3876   adc(final_dest_hi, dest_hi, zr);
3877 }
3878 
3879 // Generate an address from (r + r1 extend offset).  "size" is the
3880 // size of the operand.  The result may be in rscratch2.
3881 Address MacroAssembler::offsetted_address(Register r, Register r1,
3882                                           Address::extend ext, int offset, int size) {
3883   if (offset || (ext.shift() % size != 0)) {
3884     lea(rscratch2, Address(r, r1, ext));
3885     return Address(rscratch2, offset);
3886   } else {
3887     return Address(r, r1, ext);
3888   }
3889 }
3890 
3891 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
3892 {
3893   assert(offset >= 0, "spill to negative address?");
3894   // Offset reachable ?
3895   //   Not aligned - 9 bits signed offset
3896   //   Aligned - 12 bits unsigned offset shifted
3897   Register base = sp;
3898   if ((offset & (size-1)) && offset >= (1<<8)) {
3899     add(tmp, base, offset & ((1<<12)-1));
3900     base = tmp;
3901     offset &= -1u<<12;
3902   }
3903 
3904   if (offset >= (1<<12) * size) {
3905     add(tmp, base, offset & (((1<<12)-1)<<12));
3906     base = tmp;
3907     offset &= ~(((1<<12)-1)<<12);
3908   }
3909 
3910   return Address(base, offset);
3911 }
3912 
3913 Address MacroAssembler::sve_spill_address(int sve_reg_size_in_bytes, int offset, Register tmp) {
3914   assert(offset >= 0, "spill to negative address?");
3915 
3916   Register base = sp;
3917 
3918   // An immediate offset in the range 0 to 255 which is multiplied
3919   // by the current vector or predicate register size in bytes.
3920   if (offset % sve_reg_size_in_bytes == 0 && offset < ((1<<8)*sve_reg_size_in_bytes)) {
3921     return Address(base, offset / sve_reg_size_in_bytes);
3922   }
3923 
3924   add(tmp, base, offset);
3925   return Address(tmp);
3926 }
3927 
3928 // Checks whether offset is aligned.
3929 // Returns true if it is, else false.
3930 bool MacroAssembler::merge_alignment_check(Register base,
3931                                            size_t size,
3932                                            int64_t cur_offset,
3933                                            int64_t prev_offset) const {
3934   if (AvoidUnalignedAccesses) {
3935     if (base == sp) {
3936       // Checks whether low offset if aligned to pair of registers.
3937       int64_t pair_mask = size * 2 - 1;
3938       int64_t offset = prev_offset > cur_offset ? cur_offset : prev_offset;
3939       return (offset & pair_mask) == 0;
3940     } else { // If base is not sp, we can't guarantee the access is aligned.
3941       return false;
3942     }
3943   } else {
3944     int64_t mask = size - 1;
3945     // Load/store pair instruction only supports element size aligned offset.
3946     return (cur_offset & mask) == 0 && (prev_offset & mask) == 0;
3947   }
3948 }
3949 
3950 // Checks whether current and previous loads/stores can be merged.
3951 // Returns true if it can be merged, else false.
3952 bool MacroAssembler::ldst_can_merge(Register rt,
3953                                     const Address &adr,
3954                                     size_t cur_size_in_bytes,
3955                                     bool is_store) const {
3956   address prev = pc() - NativeInstruction::instruction_size;
3957   address last = code()->last_merge_candidate();
3958 
3959   if (last == nullptr || !nativeInstruction_at(last)->is_Imm_LdSt()) {
3960     return false;
3961   }
3962 
3963   if (adr.getMode() != Address::base_plus_offset || prev != last) {
3964     return false;
3965   }
3966 
3967   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
3968   size_t prev_size_in_bytes = prev_ldst->size_in_bytes();
3969 
3970   assert(prev_size_in_bytes == 4 || prev_size_in_bytes == 8, "only supports 64/32bit merging.");
3971   assert(cur_size_in_bytes == 4 || cur_size_in_bytes == 8, "only supports 64/32bit merging.");
3972 
3973   if (cur_size_in_bytes != prev_size_in_bytes || is_store != prev_ldst->is_store()) {
3974     return false;
3975   }
3976 
3977   int64_t max_offset = 63 * prev_size_in_bytes;
3978   int64_t min_offset = -64 * prev_size_in_bytes;
3979 
3980   assert(prev_ldst->is_not_pre_post_index(), "pre-index or post-index is not supported to be merged.");
3981 
3982   // Only same base can be merged.
3983   if (adr.base() != prev_ldst->base()) {
3984     return false;
3985   }
3986 
3987   int64_t cur_offset = adr.offset();
3988   int64_t prev_offset = prev_ldst->offset();
3989   size_t diff = abs(cur_offset - prev_offset);
3990   if (diff != prev_size_in_bytes) {
3991     return false;
3992   }
3993 
3994   // Following cases can not be merged:
3995   // ldr x2, [x2, #8]
3996   // ldr x3, [x2, #16]
3997   // or:
3998   // ldr x2, [x3, #8]
3999   // ldr x2, [x3, #16]
4000   // If t1 and t2 is the same in "ldp t1, t2, [xn, #imm]", we'll get SIGILL.
4001   if (!is_store && (adr.base() == prev_ldst->target() || rt == prev_ldst->target())) {
4002     return false;
4003   }
4004 
4005   int64_t low_offset = prev_offset > cur_offset ? cur_offset : prev_offset;
4006   // Offset range must be in ldp/stp instruction's range.
4007   if (low_offset > max_offset || low_offset < min_offset) {
4008     return false;
4009   }
4010 
4011   if (merge_alignment_check(adr.base(), prev_size_in_bytes, cur_offset, prev_offset)) {
4012     return true;
4013   }
4014 
4015   return false;
4016 }
4017 
4018 // Merge current load/store with previous load/store into ldp/stp.
4019 void MacroAssembler::merge_ldst(Register rt,
4020                                 const Address &adr,
4021                                 size_t cur_size_in_bytes,
4022                                 bool is_store) {
4023 
4024   assert(ldst_can_merge(rt, adr, cur_size_in_bytes, is_store) == true, "cur and prev must be able to be merged.");
4025 
4026   Register rt_low, rt_high;
4027   address prev = pc() - NativeInstruction::instruction_size;
4028   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
4029 
4030   int64_t offset;
4031 
4032   if (adr.offset() < prev_ldst->offset()) {
4033     offset = adr.offset();
4034     rt_low = rt;
4035     rt_high = prev_ldst->target();
4036   } else {
4037     offset = prev_ldst->offset();
4038     rt_low = prev_ldst->target();
4039     rt_high = rt;
4040   }
4041 
4042   Address adr_p = Address(prev_ldst->base(), offset);
4043   // Overwrite previous generated binary.
4044   code_section()->set_end(prev);
4045 
4046   const size_t sz = prev_ldst->size_in_bytes();
4047   assert(sz == 8 || sz == 4, "only supports 64/32bit merging.");
4048   if (!is_store) {
4049     BLOCK_COMMENT("merged ldr pair");
4050     if (sz == 8) {
4051       ldp(rt_low, rt_high, adr_p);
4052     } else {
4053       ldpw(rt_low, rt_high, adr_p);
4054     }
4055   } else {
4056     BLOCK_COMMENT("merged str pair");
4057     if (sz == 8) {
4058       stp(rt_low, rt_high, adr_p);
4059     } else {
4060       stpw(rt_low, rt_high, adr_p);
4061     }
4062   }
4063 }
4064 
4065 /**
4066  * Multiply 64 bit by 64 bit first loop.
4067  */
4068 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
4069                                            Register y, Register y_idx, Register z,
4070                                            Register carry, Register product,
4071                                            Register idx, Register kdx) {
4072   //
4073   //  jlong carry, x[], y[], z[];
4074   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
4075   //    huge_128 product = y[idx] * x[xstart] + carry;
4076   //    z[kdx] = (jlong)product;
4077   //    carry  = (jlong)(product >>> 64);
4078   //  }
4079   //  z[xstart] = carry;
4080   //
4081 
4082   Label L_first_loop, L_first_loop_exit;
4083   Label L_one_x, L_one_y, L_multiply;
4084 
4085   subsw(xstart, xstart, 1);
4086   br(Assembler::MI, L_one_x);
4087 
4088   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
4089   ldr(x_xstart, Address(rscratch1));
4090   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
4091 
4092   bind(L_first_loop);
4093   subsw(idx, idx, 1);
4094   br(Assembler::MI, L_first_loop_exit);
4095   subsw(idx, idx, 1);
4096   br(Assembler::MI, L_one_y);
4097   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4098   ldr(y_idx, Address(rscratch1));
4099   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
4100   bind(L_multiply);
4101 
4102   // AArch64 has a multiply-accumulate instruction that we can't use
4103   // here because it has no way to process carries, so we have to use
4104   // separate add and adc instructions.  Bah.
4105   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
4106   mul(product, x_xstart, y_idx);
4107   adds(product, product, carry);
4108   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
4109 
4110   subw(kdx, kdx, 2);
4111   ror(product, product, 32); // back to big-endian
4112   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
4113 
4114   b(L_first_loop);
4115 
4116   bind(L_one_y);
4117   ldrw(y_idx, Address(y,  0));
4118   b(L_multiply);
4119 
4120   bind(L_one_x);
4121   ldrw(x_xstart, Address(x,  0));
4122   b(L_first_loop);
4123 
4124   bind(L_first_loop_exit);
4125 }
4126 
4127 /**
4128  * Multiply 128 bit by 128. Unrolled inner loop.
4129  *
4130  */
4131 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
4132                                              Register carry, Register carry2,
4133                                              Register idx, Register jdx,
4134                                              Register yz_idx1, Register yz_idx2,
4135                                              Register tmp, Register tmp3, Register tmp4,
4136                                              Register tmp6, Register product_hi) {
4137 
4138   //   jlong carry, x[], y[], z[];
4139   //   int kdx = ystart+1;
4140   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
4141   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
4142   //     jlong carry2  = (jlong)(tmp3 >>> 64);
4143   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
4144   //     carry  = (jlong)(tmp4 >>> 64);
4145   //     z[kdx+idx+1] = (jlong)tmp3;
4146   //     z[kdx+idx] = (jlong)tmp4;
4147   //   }
4148   //   idx += 2;
4149   //   if (idx > 0) {
4150   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
4151   //     z[kdx+idx] = (jlong)yz_idx1;
4152   //     carry  = (jlong)(yz_idx1 >>> 64);
4153   //   }
4154   //
4155 
4156   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
4157 
4158   lsrw(jdx, idx, 2);
4159 
4160   bind(L_third_loop);
4161 
4162   subsw(jdx, jdx, 1);
4163   br(Assembler::MI, L_third_loop_exit);
4164   subw(idx, idx, 4);
4165 
4166   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4167 
4168   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
4169 
4170   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4171 
4172   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
4173   ror(yz_idx2, yz_idx2, 32);
4174 
4175   ldp(rscratch2, rscratch1, Address(tmp6, 0));
4176 
4177   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
4178   umulh(tmp4, product_hi, yz_idx1);
4179 
4180   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
4181   ror(rscratch2, rscratch2, 32);
4182 
4183   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
4184   umulh(carry2, product_hi, yz_idx2);
4185 
4186   // propagate sum of both multiplications into carry:tmp4:tmp3
4187   adds(tmp3, tmp3, carry);
4188   adc(tmp4, tmp4, zr);
4189   adds(tmp3, tmp3, rscratch1);
4190   adcs(tmp4, tmp4, tmp);
4191   adc(carry, carry2, zr);
4192   adds(tmp4, tmp4, rscratch2);
4193   adc(carry, carry, zr);
4194 
4195   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
4196   ror(tmp4, tmp4, 32);
4197   stp(tmp4, tmp3, Address(tmp6, 0));
4198 
4199   b(L_third_loop);
4200   bind (L_third_loop_exit);
4201 
4202   andw (idx, idx, 0x3);
4203   cbz(idx, L_post_third_loop_done);
4204 
4205   Label L_check_1;
4206   subsw(idx, idx, 2);
4207   br(Assembler::MI, L_check_1);
4208 
4209   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4210   ldr(yz_idx1, Address(rscratch1, 0));
4211   ror(yz_idx1, yz_idx1, 32);
4212   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
4213   umulh(tmp4, product_hi, yz_idx1);
4214   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4215   ldr(yz_idx2, Address(rscratch1, 0));
4216   ror(yz_idx2, yz_idx2, 32);
4217 
4218   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
4219 
4220   ror(tmp3, tmp3, 32);
4221   str(tmp3, Address(rscratch1, 0));
4222 
4223   bind (L_check_1);
4224 
4225   andw (idx, idx, 0x1);
4226   subsw(idx, idx, 1);
4227   br(Assembler::MI, L_post_third_loop_done);
4228   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4229   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
4230   umulh(carry2, tmp4, product_hi);
4231   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4232 
4233   add2_with_carry(carry2, tmp3, tmp4, carry);
4234 
4235   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4236   extr(carry, carry2, tmp3, 32);
4237 
4238   bind(L_post_third_loop_done);
4239 }
4240 
4241 /**
4242  * Code for BigInteger::multiplyToLen() intrinsic.
4243  *
4244  * r0: x
4245  * r1: xlen
4246  * r2: y
4247  * r3: ylen
4248  * r4:  z
4249  * r5: tmp0
4250  * r10: tmp1
4251  * r11: tmp2
4252  * r12: tmp3
4253  * r13: tmp4
4254  * r14: tmp5
4255  * r15: tmp6
4256  * r16: tmp7
4257  *
4258  */
4259 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
4260                                      Register z, Register tmp0,
4261                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
4262                                      Register tmp5, Register tmp6, Register product_hi) {
4263 
4264   assert_different_registers(x, xlen, y, ylen, z, tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, product_hi);
4265 
4266   const Register idx = tmp1;
4267   const Register kdx = tmp2;
4268   const Register xstart = tmp3;
4269 
4270   const Register y_idx = tmp4;
4271   const Register carry = tmp5;
4272   const Register product  = xlen;
4273   const Register x_xstart = tmp0;
4274 
4275   // First Loop.
4276   //
4277   //  final static long LONG_MASK = 0xffffffffL;
4278   //  int xstart = xlen - 1;
4279   //  int ystart = ylen - 1;
4280   //  long carry = 0;
4281   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
4282   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
4283   //    z[kdx] = (int)product;
4284   //    carry = product >>> 32;
4285   //  }
4286   //  z[xstart] = (int)carry;
4287   //
4288 
4289   movw(idx, ylen);       // idx = ylen;
4290   addw(kdx, xlen, ylen); // kdx = xlen+ylen;
4291   mov(carry, zr);        // carry = 0;
4292 
4293   Label L_done;
4294 
4295   movw(xstart, xlen);
4296   subsw(xstart, xstart, 1);
4297   br(Assembler::MI, L_done);
4298 
4299   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
4300 
4301   Label L_second_loop;
4302   cbzw(kdx, L_second_loop);
4303 
4304   Label L_carry;
4305   subw(kdx, kdx, 1);
4306   cbzw(kdx, L_carry);
4307 
4308   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
4309   lsr(carry, carry, 32);
4310   subw(kdx, kdx, 1);
4311 
4312   bind(L_carry);
4313   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
4314 
4315   // Second and third (nested) loops.
4316   //
4317   // for (int i = xstart-1; i >= 0; i--) { // Second loop
4318   //   carry = 0;
4319   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
4320   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
4321   //                    (z[k] & LONG_MASK) + carry;
4322   //     z[k] = (int)product;
4323   //     carry = product >>> 32;
4324   //   }
4325   //   z[i] = (int)carry;
4326   // }
4327   //
4328   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
4329 
4330   const Register jdx = tmp1;
4331 
4332   bind(L_second_loop);
4333   mov(carry, zr);                // carry = 0;
4334   movw(jdx, ylen);               // j = ystart+1
4335 
4336   subsw(xstart, xstart, 1);      // i = xstart-1;
4337   br(Assembler::MI, L_done);
4338 
4339   str(z, Address(pre(sp, -4 * wordSize)));
4340 
4341   Label L_last_x;
4342   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
4343   subsw(xstart, xstart, 1);       // i = xstart-1;
4344   br(Assembler::MI, L_last_x);
4345 
4346   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
4347   ldr(product_hi, Address(rscratch1));
4348   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
4349 
4350   Label L_third_loop_prologue;
4351   bind(L_third_loop_prologue);
4352 
4353   str(ylen, Address(sp, wordSize));
4354   stp(x, xstart, Address(sp, 2 * wordSize));
4355   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
4356                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
4357   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
4358   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
4359 
4360   addw(tmp3, xlen, 1);
4361   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
4362   subsw(tmp3, tmp3, 1);
4363   br(Assembler::MI, L_done);
4364 
4365   lsr(carry, carry, 32);
4366   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
4367   b(L_second_loop);
4368 
4369   // Next infrequent code is moved outside loops.
4370   bind(L_last_x);
4371   ldrw(product_hi, Address(x,  0));
4372   b(L_third_loop_prologue);
4373 
4374   bind(L_done);
4375 }
4376 
4377 // Code for BigInteger::mulAdd intrinsic
4378 // out     = r0
4379 // in      = r1
4380 // offset  = r2  (already out.length-offset)
4381 // len     = r3
4382 // k       = r4
4383 //
4384 // pseudo code from java implementation:
4385 // carry = 0;
4386 // offset = out.length-offset - 1;
4387 // for (int j=len-1; j >= 0; j--) {
4388 //     product = (in[j] & LONG_MASK) * kLong + (out[offset] & LONG_MASK) + carry;
4389 //     out[offset--] = (int)product;
4390 //     carry = product >>> 32;
4391 // }
4392 // return (int)carry;
4393 void MacroAssembler::mul_add(Register out, Register in, Register offset,
4394       Register len, Register k) {
4395     Label LOOP, END;
4396     // pre-loop
4397     cmp(len, zr); // cmp, not cbz/cbnz: to use condition twice => less branches
4398     csel(out, zr, out, Assembler::EQ);
4399     br(Assembler::EQ, END);
4400     add(in, in, len, LSL, 2); // in[j+1] address
4401     add(offset, out, offset, LSL, 2); // out[offset + 1] address
4402     mov(out, zr); // used to keep carry now
4403     BIND(LOOP);
4404     ldrw(rscratch1, Address(pre(in, -4)));
4405     madd(rscratch1, rscratch1, k, out);
4406     ldrw(rscratch2, Address(pre(offset, -4)));
4407     add(rscratch1, rscratch1, rscratch2);
4408     strw(rscratch1, Address(offset));
4409     lsr(out, rscratch1, 32);
4410     subs(len, len, 1);
4411     br(Assembler::NE, LOOP);
4412     BIND(END);
4413 }
4414 
4415 /**
4416  * Emits code to update CRC-32 with a byte value according to constants in table
4417  *
4418  * @param [in,out]crc   Register containing the crc.
4419  * @param [in]val       Register containing the byte to fold into the CRC.
4420  * @param [in]table     Register containing the table of crc constants.
4421  *
4422  * uint32_t crc;
4423  * val = crc_table[(val ^ crc) & 0xFF];
4424  * crc = val ^ (crc >> 8);
4425  *
4426  */
4427 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
4428   eor(val, val, crc);
4429   andr(val, val, 0xff);
4430   ldrw(val, Address(table, val, Address::lsl(2)));
4431   eor(crc, val, crc, Assembler::LSR, 8);
4432 }
4433 
4434 /**
4435  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
4436  *
4437  * @param [in,out]crc   Register containing the crc.
4438  * @param [in]v         Register containing the 32-bit to fold into the CRC.
4439  * @param [in]table0    Register containing table 0 of crc constants.
4440  * @param [in]table1    Register containing table 1 of crc constants.
4441  * @param [in]table2    Register containing table 2 of crc constants.
4442  * @param [in]table3    Register containing table 3 of crc constants.
4443  *
4444  * uint32_t crc;
4445  *   v = crc ^ v
4446  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
4447  *
4448  */
4449 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
4450         Register table0, Register table1, Register table2, Register table3,
4451         bool upper) {
4452   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
4453   uxtb(tmp, v);
4454   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
4455   ubfx(tmp, v, 8, 8);
4456   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
4457   eor(crc, crc, tmp);
4458   ubfx(tmp, v, 16, 8);
4459   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
4460   eor(crc, crc, tmp);
4461   ubfx(tmp, v, 24, 8);
4462   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
4463   eor(crc, crc, tmp);
4464 }
4465 
4466 void MacroAssembler::kernel_crc32_using_crypto_pmull(Register crc, Register buf,
4467         Register len, Register tmp0, Register tmp1, Register tmp2, Register tmp3) {
4468     Label CRC_by4_loop, CRC_by1_loop, CRC_less128, CRC_by128_pre, CRC_by32_loop, CRC_less32, L_exit;
4469     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
4470 
4471     subs(tmp0, len, 384);
4472     mvnw(crc, crc);
4473     br(Assembler::GE, CRC_by128_pre);
4474   BIND(CRC_less128);
4475     subs(len, len, 32);
4476     br(Assembler::GE, CRC_by32_loop);
4477   BIND(CRC_less32);
4478     adds(len, len, 32 - 4);
4479     br(Assembler::GE, CRC_by4_loop);
4480     adds(len, len, 4);
4481     br(Assembler::GT, CRC_by1_loop);
4482     b(L_exit);
4483 
4484   BIND(CRC_by32_loop);
4485     ldp(tmp0, tmp1, Address(buf));
4486     crc32x(crc, crc, tmp0);
4487     ldp(tmp2, tmp3, Address(buf, 16));
4488     crc32x(crc, crc, tmp1);
4489     add(buf, buf, 32);
4490     crc32x(crc, crc, tmp2);
4491     subs(len, len, 32);
4492     crc32x(crc, crc, tmp3);
4493     br(Assembler::GE, CRC_by32_loop);
4494     cmn(len, (u1)32);
4495     br(Assembler::NE, CRC_less32);
4496     b(L_exit);
4497 
4498   BIND(CRC_by4_loop);
4499     ldrw(tmp0, Address(post(buf, 4)));
4500     subs(len, len, 4);
4501     crc32w(crc, crc, tmp0);
4502     br(Assembler::GE, CRC_by4_loop);
4503     adds(len, len, 4);
4504     br(Assembler::LE, L_exit);
4505   BIND(CRC_by1_loop);
4506     ldrb(tmp0, Address(post(buf, 1)));
4507     subs(len, len, 1);
4508     crc32b(crc, crc, tmp0);
4509     br(Assembler::GT, CRC_by1_loop);
4510     b(L_exit);
4511 
4512   BIND(CRC_by128_pre);
4513     kernel_crc32_common_fold_using_crypto_pmull(crc, buf, len, tmp0, tmp1, tmp2,
4514       4*256*sizeof(juint) + 8*sizeof(juint));
4515     mov(crc, 0);
4516     crc32x(crc, crc, tmp0);
4517     crc32x(crc, crc, tmp1);
4518 
4519     cbnz(len, CRC_less128);
4520 
4521   BIND(L_exit);
4522     mvnw(crc, crc);
4523 }
4524 
4525 void MacroAssembler::kernel_crc32_using_crc32(Register crc, Register buf,
4526         Register len, Register tmp0, Register tmp1, Register tmp2,
4527         Register tmp3) {
4528     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
4529     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
4530 
4531     mvnw(crc, crc);
4532 
4533     subs(len, len, 128);
4534     br(Assembler::GE, CRC_by64_pre);
4535   BIND(CRC_less64);
4536     adds(len, len, 128-32);
4537     br(Assembler::GE, CRC_by32_loop);
4538   BIND(CRC_less32);
4539     adds(len, len, 32-4);
4540     br(Assembler::GE, CRC_by4_loop);
4541     adds(len, len, 4);
4542     br(Assembler::GT, CRC_by1_loop);
4543     b(L_exit);
4544 
4545   BIND(CRC_by32_loop);
4546     ldp(tmp0, tmp1, Address(post(buf, 16)));
4547     subs(len, len, 32);
4548     crc32x(crc, crc, tmp0);
4549     ldr(tmp2, Address(post(buf, 8)));
4550     crc32x(crc, crc, tmp1);
4551     ldr(tmp3, Address(post(buf, 8)));
4552     crc32x(crc, crc, tmp2);
4553     crc32x(crc, crc, tmp3);
4554     br(Assembler::GE, CRC_by32_loop);
4555     cmn(len, (u1)32);
4556     br(Assembler::NE, CRC_less32);
4557     b(L_exit);
4558 
4559   BIND(CRC_by4_loop);
4560     ldrw(tmp0, Address(post(buf, 4)));
4561     subs(len, len, 4);
4562     crc32w(crc, crc, tmp0);
4563     br(Assembler::GE, CRC_by4_loop);
4564     adds(len, len, 4);
4565     br(Assembler::LE, L_exit);
4566   BIND(CRC_by1_loop);
4567     ldrb(tmp0, Address(post(buf, 1)));
4568     subs(len, len, 1);
4569     crc32b(crc, crc, tmp0);
4570     br(Assembler::GT, CRC_by1_loop);
4571     b(L_exit);
4572 
4573   BIND(CRC_by64_pre);
4574     sub(buf, buf, 8);
4575     ldp(tmp0, tmp1, Address(buf, 8));
4576     crc32x(crc, crc, tmp0);
4577     ldr(tmp2, Address(buf, 24));
4578     crc32x(crc, crc, tmp1);
4579     ldr(tmp3, Address(buf, 32));
4580     crc32x(crc, crc, tmp2);
4581     ldr(tmp0, Address(buf, 40));
4582     crc32x(crc, crc, tmp3);
4583     ldr(tmp1, Address(buf, 48));
4584     crc32x(crc, crc, tmp0);
4585     ldr(tmp2, Address(buf, 56));
4586     crc32x(crc, crc, tmp1);
4587     ldr(tmp3, Address(pre(buf, 64)));
4588 
4589     b(CRC_by64_loop);
4590 
4591     align(CodeEntryAlignment);
4592   BIND(CRC_by64_loop);
4593     subs(len, len, 64);
4594     crc32x(crc, crc, tmp2);
4595     ldr(tmp0, Address(buf, 8));
4596     crc32x(crc, crc, tmp3);
4597     ldr(tmp1, Address(buf, 16));
4598     crc32x(crc, crc, tmp0);
4599     ldr(tmp2, Address(buf, 24));
4600     crc32x(crc, crc, tmp1);
4601     ldr(tmp3, Address(buf, 32));
4602     crc32x(crc, crc, tmp2);
4603     ldr(tmp0, Address(buf, 40));
4604     crc32x(crc, crc, tmp3);
4605     ldr(tmp1, Address(buf, 48));
4606     crc32x(crc, crc, tmp0);
4607     ldr(tmp2, Address(buf, 56));
4608     crc32x(crc, crc, tmp1);
4609     ldr(tmp3, Address(pre(buf, 64)));
4610     br(Assembler::GE, CRC_by64_loop);
4611 
4612     // post-loop
4613     crc32x(crc, crc, tmp2);
4614     crc32x(crc, crc, tmp3);
4615 
4616     sub(len, len, 64);
4617     add(buf, buf, 8);
4618     cmn(len, (u1)128);
4619     br(Assembler::NE, CRC_less64);
4620   BIND(L_exit);
4621     mvnw(crc, crc);
4622 }
4623 
4624 /**
4625  * @param crc   register containing existing CRC (32-bit)
4626  * @param buf   register pointing to input byte buffer (byte*)
4627  * @param len   register containing number of bytes
4628  * @param table register that will contain address of CRC table
4629  * @param tmp   scratch register
4630  */
4631 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
4632         Register table0, Register table1, Register table2, Register table3,
4633         Register tmp, Register tmp2, Register tmp3) {
4634   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
4635 
4636   if (UseCryptoPmullForCRC32) {
4637       kernel_crc32_using_crypto_pmull(crc, buf, len, table0, table1, table2, table3);
4638       return;
4639   }
4640 
4641   if (UseCRC32) {
4642       kernel_crc32_using_crc32(crc, buf, len, table0, table1, table2, table3);
4643       return;
4644   }
4645 
4646     mvnw(crc, crc);
4647 
4648     {
4649       uint64_t offset;
4650       adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
4651       add(table0, table0, offset);
4652     }
4653     add(table1, table0, 1*256*sizeof(juint));
4654     add(table2, table0, 2*256*sizeof(juint));
4655     add(table3, table0, 3*256*sizeof(juint));
4656 
4657     { // Neon code start
4658       cmp(len, (u1)64);
4659       br(Assembler::LT, L_by16);
4660       eor(v16, T16B, v16, v16);
4661 
4662     Label L_fold;
4663 
4664       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
4665 
4666       ld1(v0, v1, T2D, post(buf, 32));
4667       ld1r(v4, T2D, post(tmp, 8));
4668       ld1r(v5, T2D, post(tmp, 8));
4669       ld1r(v6, T2D, post(tmp, 8));
4670       ld1r(v7, T2D, post(tmp, 8));
4671       mov(v16, S, 0, crc);
4672 
4673       eor(v0, T16B, v0, v16);
4674       sub(len, len, 64);
4675 
4676     BIND(L_fold);
4677       pmull(v22, T8H, v0, v5, T8B);
4678       pmull(v20, T8H, v0, v7, T8B);
4679       pmull(v23, T8H, v0, v4, T8B);
4680       pmull(v21, T8H, v0, v6, T8B);
4681 
4682       pmull2(v18, T8H, v0, v5, T16B);
4683       pmull2(v16, T8H, v0, v7, T16B);
4684       pmull2(v19, T8H, v0, v4, T16B);
4685       pmull2(v17, T8H, v0, v6, T16B);
4686 
4687       uzp1(v24, T8H, v20, v22);
4688       uzp2(v25, T8H, v20, v22);
4689       eor(v20, T16B, v24, v25);
4690 
4691       uzp1(v26, T8H, v16, v18);
4692       uzp2(v27, T8H, v16, v18);
4693       eor(v16, T16B, v26, v27);
4694 
4695       ushll2(v22, T4S, v20, T8H, 8);
4696       ushll(v20, T4S, v20, T4H, 8);
4697 
4698       ushll2(v18, T4S, v16, T8H, 8);
4699       ushll(v16, T4S, v16, T4H, 8);
4700 
4701       eor(v22, T16B, v23, v22);
4702       eor(v18, T16B, v19, v18);
4703       eor(v20, T16B, v21, v20);
4704       eor(v16, T16B, v17, v16);
4705 
4706       uzp1(v17, T2D, v16, v20);
4707       uzp2(v21, T2D, v16, v20);
4708       eor(v17, T16B, v17, v21);
4709 
4710       ushll2(v20, T2D, v17, T4S, 16);
4711       ushll(v16, T2D, v17, T2S, 16);
4712 
4713       eor(v20, T16B, v20, v22);
4714       eor(v16, T16B, v16, v18);
4715 
4716       uzp1(v17, T2D, v20, v16);
4717       uzp2(v21, T2D, v20, v16);
4718       eor(v28, T16B, v17, v21);
4719 
4720       pmull(v22, T8H, v1, v5, T8B);
4721       pmull(v20, T8H, v1, v7, T8B);
4722       pmull(v23, T8H, v1, v4, T8B);
4723       pmull(v21, T8H, v1, v6, T8B);
4724 
4725       pmull2(v18, T8H, v1, v5, T16B);
4726       pmull2(v16, T8H, v1, v7, T16B);
4727       pmull2(v19, T8H, v1, v4, T16B);
4728       pmull2(v17, T8H, v1, v6, T16B);
4729 
4730       ld1(v0, v1, T2D, post(buf, 32));
4731 
4732       uzp1(v24, T8H, v20, v22);
4733       uzp2(v25, T8H, v20, v22);
4734       eor(v20, T16B, v24, v25);
4735 
4736       uzp1(v26, T8H, v16, v18);
4737       uzp2(v27, T8H, v16, v18);
4738       eor(v16, T16B, v26, v27);
4739 
4740       ushll2(v22, T4S, v20, T8H, 8);
4741       ushll(v20, T4S, v20, T4H, 8);
4742 
4743       ushll2(v18, T4S, v16, T8H, 8);
4744       ushll(v16, T4S, v16, T4H, 8);
4745 
4746       eor(v22, T16B, v23, v22);
4747       eor(v18, T16B, v19, v18);
4748       eor(v20, T16B, v21, v20);
4749       eor(v16, T16B, v17, v16);
4750 
4751       uzp1(v17, T2D, v16, v20);
4752       uzp2(v21, T2D, v16, v20);
4753       eor(v16, T16B, v17, v21);
4754 
4755       ushll2(v20, T2D, v16, T4S, 16);
4756       ushll(v16, T2D, v16, T2S, 16);
4757 
4758       eor(v20, T16B, v22, v20);
4759       eor(v16, T16B, v16, v18);
4760 
4761       uzp1(v17, T2D, v20, v16);
4762       uzp2(v21, T2D, v20, v16);
4763       eor(v20, T16B, v17, v21);
4764 
4765       shl(v16, T2D, v28, 1);
4766       shl(v17, T2D, v20, 1);
4767 
4768       eor(v0, T16B, v0, v16);
4769       eor(v1, T16B, v1, v17);
4770 
4771       subs(len, len, 32);
4772       br(Assembler::GE, L_fold);
4773 
4774       mov(crc, 0);
4775       mov(tmp, v0, D, 0);
4776       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4777       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4778       mov(tmp, v0, D, 1);
4779       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4780       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4781       mov(tmp, v1, D, 0);
4782       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4783       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4784       mov(tmp, v1, D, 1);
4785       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4786       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4787 
4788       add(len, len, 32);
4789     } // Neon code end
4790 
4791   BIND(L_by16);
4792     subs(len, len, 16);
4793     br(Assembler::GE, L_by16_loop);
4794     adds(len, len, 16-4);
4795     br(Assembler::GE, L_by4_loop);
4796     adds(len, len, 4);
4797     br(Assembler::GT, L_by1_loop);
4798     b(L_exit);
4799 
4800   BIND(L_by4_loop);
4801     ldrw(tmp, Address(post(buf, 4)));
4802     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
4803     subs(len, len, 4);
4804     br(Assembler::GE, L_by4_loop);
4805     adds(len, len, 4);
4806     br(Assembler::LE, L_exit);
4807   BIND(L_by1_loop);
4808     subs(len, len, 1);
4809     ldrb(tmp, Address(post(buf, 1)));
4810     update_byte_crc32(crc, tmp, table0);
4811     br(Assembler::GT, L_by1_loop);
4812     b(L_exit);
4813 
4814     align(CodeEntryAlignment);
4815   BIND(L_by16_loop);
4816     subs(len, len, 16);
4817     ldp(tmp, tmp3, Address(post(buf, 16)));
4818     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4819     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4820     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
4821     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
4822     br(Assembler::GE, L_by16_loop);
4823     adds(len, len, 16-4);
4824     br(Assembler::GE, L_by4_loop);
4825     adds(len, len, 4);
4826     br(Assembler::GT, L_by1_loop);
4827   BIND(L_exit);
4828     mvnw(crc, crc);
4829 }
4830 
4831 void MacroAssembler::kernel_crc32c_using_crypto_pmull(Register crc, Register buf,
4832         Register len, Register tmp0, Register tmp1, Register tmp2, Register tmp3) {
4833     Label CRC_by4_loop, CRC_by1_loop, CRC_less128, CRC_by128_pre, CRC_by32_loop, CRC_less32, L_exit;
4834     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
4835 
4836     subs(tmp0, len, 384);
4837     br(Assembler::GE, CRC_by128_pre);
4838   BIND(CRC_less128);
4839     subs(len, len, 32);
4840     br(Assembler::GE, CRC_by32_loop);
4841   BIND(CRC_less32);
4842     adds(len, len, 32 - 4);
4843     br(Assembler::GE, CRC_by4_loop);
4844     adds(len, len, 4);
4845     br(Assembler::GT, CRC_by1_loop);
4846     b(L_exit);
4847 
4848   BIND(CRC_by32_loop);
4849     ldp(tmp0, tmp1, Address(buf));
4850     crc32cx(crc, crc, tmp0);
4851     ldr(tmp2, Address(buf, 16));
4852     crc32cx(crc, crc, tmp1);
4853     ldr(tmp3, Address(buf, 24));
4854     crc32cx(crc, crc, tmp2);
4855     add(buf, buf, 32);
4856     subs(len, len, 32);
4857     crc32cx(crc, crc, tmp3);
4858     br(Assembler::GE, CRC_by32_loop);
4859     cmn(len, (u1)32);
4860     br(Assembler::NE, CRC_less32);
4861     b(L_exit);
4862 
4863   BIND(CRC_by4_loop);
4864     ldrw(tmp0, Address(post(buf, 4)));
4865     subs(len, len, 4);
4866     crc32cw(crc, crc, tmp0);
4867     br(Assembler::GE, CRC_by4_loop);
4868     adds(len, len, 4);
4869     br(Assembler::LE, L_exit);
4870   BIND(CRC_by1_loop);
4871     ldrb(tmp0, Address(post(buf, 1)));
4872     subs(len, len, 1);
4873     crc32cb(crc, crc, tmp0);
4874     br(Assembler::GT, CRC_by1_loop);
4875     b(L_exit);
4876 
4877   BIND(CRC_by128_pre);
4878     kernel_crc32_common_fold_using_crypto_pmull(crc, buf, len, tmp0, tmp1, tmp2,
4879       4*256*sizeof(juint) + 8*sizeof(juint) + 0x50);
4880     mov(crc, 0);
4881     crc32cx(crc, crc, tmp0);
4882     crc32cx(crc, crc, tmp1);
4883 
4884     cbnz(len, CRC_less128);
4885 
4886   BIND(L_exit);
4887 }
4888 
4889 void MacroAssembler::kernel_crc32c_using_crc32c(Register crc, Register buf,
4890         Register len, Register tmp0, Register tmp1, Register tmp2,
4891         Register tmp3) {
4892     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
4893     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
4894 
4895     subs(len, len, 128);
4896     br(Assembler::GE, CRC_by64_pre);
4897   BIND(CRC_less64);
4898     adds(len, len, 128-32);
4899     br(Assembler::GE, CRC_by32_loop);
4900   BIND(CRC_less32);
4901     adds(len, len, 32-4);
4902     br(Assembler::GE, CRC_by4_loop);
4903     adds(len, len, 4);
4904     br(Assembler::GT, CRC_by1_loop);
4905     b(L_exit);
4906 
4907   BIND(CRC_by32_loop);
4908     ldp(tmp0, tmp1, Address(post(buf, 16)));
4909     subs(len, len, 32);
4910     crc32cx(crc, crc, tmp0);
4911     ldr(tmp2, Address(post(buf, 8)));
4912     crc32cx(crc, crc, tmp1);
4913     ldr(tmp3, Address(post(buf, 8)));
4914     crc32cx(crc, crc, tmp2);
4915     crc32cx(crc, crc, tmp3);
4916     br(Assembler::GE, CRC_by32_loop);
4917     cmn(len, (u1)32);
4918     br(Assembler::NE, CRC_less32);
4919     b(L_exit);
4920 
4921   BIND(CRC_by4_loop);
4922     ldrw(tmp0, Address(post(buf, 4)));
4923     subs(len, len, 4);
4924     crc32cw(crc, crc, tmp0);
4925     br(Assembler::GE, CRC_by4_loop);
4926     adds(len, len, 4);
4927     br(Assembler::LE, L_exit);
4928   BIND(CRC_by1_loop);
4929     ldrb(tmp0, Address(post(buf, 1)));
4930     subs(len, len, 1);
4931     crc32cb(crc, crc, tmp0);
4932     br(Assembler::GT, CRC_by1_loop);
4933     b(L_exit);
4934 
4935   BIND(CRC_by64_pre);
4936     sub(buf, buf, 8);
4937     ldp(tmp0, tmp1, Address(buf, 8));
4938     crc32cx(crc, crc, tmp0);
4939     ldr(tmp2, Address(buf, 24));
4940     crc32cx(crc, crc, tmp1);
4941     ldr(tmp3, Address(buf, 32));
4942     crc32cx(crc, crc, tmp2);
4943     ldr(tmp0, Address(buf, 40));
4944     crc32cx(crc, crc, tmp3);
4945     ldr(tmp1, Address(buf, 48));
4946     crc32cx(crc, crc, tmp0);
4947     ldr(tmp2, Address(buf, 56));
4948     crc32cx(crc, crc, tmp1);
4949     ldr(tmp3, Address(pre(buf, 64)));
4950 
4951     b(CRC_by64_loop);
4952 
4953     align(CodeEntryAlignment);
4954   BIND(CRC_by64_loop);
4955     subs(len, len, 64);
4956     crc32cx(crc, crc, tmp2);
4957     ldr(tmp0, Address(buf, 8));
4958     crc32cx(crc, crc, tmp3);
4959     ldr(tmp1, Address(buf, 16));
4960     crc32cx(crc, crc, tmp0);
4961     ldr(tmp2, Address(buf, 24));
4962     crc32cx(crc, crc, tmp1);
4963     ldr(tmp3, Address(buf, 32));
4964     crc32cx(crc, crc, tmp2);
4965     ldr(tmp0, Address(buf, 40));
4966     crc32cx(crc, crc, tmp3);
4967     ldr(tmp1, Address(buf, 48));
4968     crc32cx(crc, crc, tmp0);
4969     ldr(tmp2, Address(buf, 56));
4970     crc32cx(crc, crc, tmp1);
4971     ldr(tmp3, Address(pre(buf, 64)));
4972     br(Assembler::GE, CRC_by64_loop);
4973 
4974     // post-loop
4975     crc32cx(crc, crc, tmp2);
4976     crc32cx(crc, crc, tmp3);
4977 
4978     sub(len, len, 64);
4979     add(buf, buf, 8);
4980     cmn(len, (u1)128);
4981     br(Assembler::NE, CRC_less64);
4982   BIND(L_exit);
4983 }
4984 
4985 /**
4986  * @param crc   register containing existing CRC (32-bit)
4987  * @param buf   register pointing to input byte buffer (byte*)
4988  * @param len   register containing number of bytes
4989  * @param table register that will contain address of CRC table
4990  * @param tmp   scratch register
4991  */
4992 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
4993         Register table0, Register table1, Register table2, Register table3,
4994         Register tmp, Register tmp2, Register tmp3) {
4995   if (UseCryptoPmullForCRC32) {
4996     kernel_crc32c_using_crypto_pmull(crc, buf, len, table0, table1, table2, table3);
4997   } else {
4998     kernel_crc32c_using_crc32c(crc, buf, len, table0, table1, table2, table3);
4999   }
5000 }
5001 
5002 void MacroAssembler::kernel_crc32_common_fold_using_crypto_pmull(Register crc, Register buf,
5003         Register len, Register tmp0, Register tmp1, Register tmp2, size_t table_offset) {
5004     Label CRC_by128_loop;
5005     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
5006 
5007     sub(len, len, 256);
5008     Register table = tmp0;
5009     {
5010       uint64_t offset;
5011       adrp(table, ExternalAddress(StubRoutines::crc_table_addr()), offset);
5012       add(table, table, offset);
5013     }
5014     add(table, table, table_offset);
5015 
5016     // Registers v0..v7 are used as data registers.
5017     // Registers v16..v31 are used as tmp registers.
5018     sub(buf, buf, 0x10);
5019     ldrq(v0, Address(buf, 0x10));
5020     ldrq(v1, Address(buf, 0x20));
5021     ldrq(v2, Address(buf, 0x30));
5022     ldrq(v3, Address(buf, 0x40));
5023     ldrq(v4, Address(buf, 0x50));
5024     ldrq(v5, Address(buf, 0x60));
5025     ldrq(v6, Address(buf, 0x70));
5026     ldrq(v7, Address(pre(buf, 0x80)));
5027 
5028     movi(v31, T4S, 0);
5029     mov(v31, S, 0, crc);
5030     eor(v0, T16B, v0, v31);
5031 
5032     // Register v16 contains constants from the crc table.
5033     ldrq(v16, Address(table));
5034     b(CRC_by128_loop);
5035 
5036     align(OptoLoopAlignment);
5037   BIND(CRC_by128_loop);
5038     pmull (v17,  T1Q, v0, v16, T1D);
5039     pmull2(v18, T1Q, v0, v16, T2D);
5040     ldrq(v0, Address(buf, 0x10));
5041     eor3(v0, T16B, v17,  v18, v0);
5042 
5043     pmull (v19, T1Q, v1, v16, T1D);
5044     pmull2(v20, T1Q, v1, v16, T2D);
5045     ldrq(v1, Address(buf, 0x20));
5046     eor3(v1, T16B, v19, v20, v1);
5047 
5048     pmull (v21, T1Q, v2, v16, T1D);
5049     pmull2(v22, T1Q, v2, v16, T2D);
5050     ldrq(v2, Address(buf, 0x30));
5051     eor3(v2, T16B, v21, v22, v2);
5052 
5053     pmull (v23, T1Q, v3, v16, T1D);
5054     pmull2(v24, T1Q, v3, v16, T2D);
5055     ldrq(v3, Address(buf, 0x40));
5056     eor3(v3, T16B, v23, v24, v3);
5057 
5058     pmull (v25, T1Q, v4, v16, T1D);
5059     pmull2(v26, T1Q, v4, v16, T2D);
5060     ldrq(v4, Address(buf, 0x50));
5061     eor3(v4, T16B, v25, v26, v4);
5062 
5063     pmull (v27, T1Q, v5, v16, T1D);
5064     pmull2(v28, T1Q, v5, v16, T2D);
5065     ldrq(v5, Address(buf, 0x60));
5066     eor3(v5, T16B, v27, v28, v5);
5067 
5068     pmull (v29, T1Q, v6, v16, T1D);
5069     pmull2(v30, T1Q, v6, v16, T2D);
5070     ldrq(v6, Address(buf, 0x70));
5071     eor3(v6, T16B, v29, v30, v6);
5072 
5073     // Reuse registers v23, v24.
5074     // Using them won't block the first instruction of the next iteration.
5075     pmull (v23, T1Q, v7, v16, T1D);
5076     pmull2(v24, T1Q, v7, v16, T2D);
5077     ldrq(v7, Address(pre(buf, 0x80)));
5078     eor3(v7, T16B, v23, v24, v7);
5079 
5080     subs(len, len, 0x80);
5081     br(Assembler::GE, CRC_by128_loop);
5082 
5083     // fold into 512 bits
5084     // Use v31 for constants because v16 can be still in use.
5085     ldrq(v31, Address(table, 0x10));
5086 
5087     pmull (v17,  T1Q, v0, v31, T1D);
5088     pmull2(v18, T1Q, v0, v31, T2D);
5089     eor3(v0, T16B, v17, v18, v4);
5090 
5091     pmull (v19, T1Q, v1, v31, T1D);
5092     pmull2(v20, T1Q, v1, v31, T2D);
5093     eor3(v1, T16B, v19, v20, v5);
5094 
5095     pmull (v21, T1Q, v2, v31, T1D);
5096     pmull2(v22, T1Q, v2, v31, T2D);
5097     eor3(v2, T16B, v21, v22, v6);
5098 
5099     pmull (v23, T1Q, v3, v31, T1D);
5100     pmull2(v24, T1Q, v3, v31, T2D);
5101     eor3(v3, T16B, v23, v24, v7);
5102 
5103     // fold into 128 bits
5104     // Use v17 for constants because v31 can be still in use.
5105     ldrq(v17, Address(table, 0x20));
5106     pmull (v25, T1Q, v0, v17, T1D);
5107     pmull2(v26, T1Q, v0, v17, T2D);
5108     eor3(v3, T16B, v3, v25, v26);
5109 
5110     // Use v18 for constants because v17 can be still in use.
5111     ldrq(v18, Address(table, 0x30));
5112     pmull (v27, T1Q, v1, v18, T1D);
5113     pmull2(v28, T1Q, v1, v18, T2D);
5114     eor3(v3, T16B, v3, v27, v28);
5115 
5116     // Use v19 for constants because v18 can be still in use.
5117     ldrq(v19, Address(table, 0x40));
5118     pmull (v29, T1Q, v2, v19, T1D);
5119     pmull2(v30, T1Q, v2, v19, T2D);
5120     eor3(v0, T16B, v3, v29, v30);
5121 
5122     add(len, len, 0x80);
5123     add(buf, buf, 0x10);
5124 
5125     mov(tmp0, v0, D, 0);
5126     mov(tmp1, v0, D, 1);
5127 }
5128 
5129 void MacroAssembler::addptr(const Address &dst, int32_t src) {
5130   Address adr;
5131   switch(dst.getMode()) {
5132   case Address::base_plus_offset:
5133     // This is the expected mode, although we allow all the other
5134     // forms below.
5135     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
5136     break;
5137   default:
5138     lea(rscratch2, dst);
5139     adr = Address(rscratch2);
5140     break;
5141   }
5142   ldr(rscratch1, adr);
5143   add(rscratch1, rscratch1, src);
5144   str(rscratch1, adr);
5145 }
5146 
5147 void MacroAssembler::cmpptr(Register src1, Address src2) {
5148   uint64_t offset;
5149   adrp(rscratch1, src2, offset);
5150   ldr(rscratch1, Address(rscratch1, offset));
5151   cmp(src1, rscratch1);
5152 }
5153 
5154 void MacroAssembler::cmpoop(Register obj1, Register obj2) {
5155   cmp(obj1, obj2);
5156 }
5157 
5158 void MacroAssembler::load_method_holder_cld(Register rresult, Register rmethod) {
5159   load_method_holder(rresult, rmethod);
5160   ldr(rresult, Address(rresult, InstanceKlass::class_loader_data_offset()));
5161 }
5162 
5163 void MacroAssembler::load_method_holder(Register holder, Register method) {
5164   ldr(holder, Address(method, Method::const_offset()));                      // ConstMethod*
5165   ldr(holder, Address(holder, ConstMethod::constants_offset()));             // ConstantPool*
5166   ldr(holder, Address(holder, ConstantPool::pool_holder_offset()));          // InstanceKlass*
5167 }
5168 
5169 void MacroAssembler::load_metadata(Register dst, Register src) {
5170   if (UseCompactObjectHeaders) {
5171     load_narrow_klass_compact(dst, src);
5172   } else {
5173     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5174   }
5175 }
5176 
5177 // Loads the obj's Klass* into dst.
5178 // Preserves all registers (incl src, rscratch1 and rscratch2).
5179 // Input:
5180 // src - the oop we want to load the klass from.
5181 // dst - output narrow klass.
5182 void MacroAssembler::load_narrow_klass_compact(Register dst, Register src) {
5183   assert(UseCompactObjectHeaders, "expects UseCompactObjectHeaders");
5184   ldr(dst, Address(src, oopDesc::mark_offset_in_bytes()));
5185   lsr(dst, dst, markWord::klass_shift);
5186 }
5187 
5188 void MacroAssembler::load_klass(Register dst, Register src) {
5189   if (UseCompactObjectHeaders) {
5190     load_narrow_klass_compact(dst, src);
5191   } else {
5192     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5193   }
5194   decode_klass_not_null(dst);
5195 }
5196 
5197 void MacroAssembler::restore_cpu_control_state_after_jni(Register tmp1, Register tmp2) {
5198   if (RestoreMXCSROnJNICalls) {
5199     Label OK;
5200     get_fpcr(tmp1);
5201     mov(tmp2, tmp1);
5202     // Set FPCR to the state we need. We do want Round to Nearest. We
5203     // don't want non-IEEE rounding modes or floating-point traps.
5204     bfi(tmp1, zr, 22, 4); // Clear DN, FZ, and Rmode
5205     bfi(tmp1, zr, 8, 5);  // Clear exception-control bits (8-12)
5206     bfi(tmp1, zr, 0, 2);  // Clear AH:FIZ
5207     eor(tmp2, tmp1, tmp2);
5208     cbz(tmp2, OK);        // Only reset FPCR if it's wrong
5209     set_fpcr(tmp1);
5210     bind(OK);
5211   }
5212 }
5213 
5214 // ((OopHandle)result).resolve();
5215 void MacroAssembler::resolve_oop_handle(Register result, Register tmp1, Register tmp2) {
5216   // OopHandle::resolve is an indirection.
5217   access_load_at(T_OBJECT, IN_NATIVE, result, Address(result, 0), tmp1, tmp2);
5218 }
5219 
5220 // ((WeakHandle)result).resolve();
5221 void MacroAssembler::resolve_weak_handle(Register result, Register tmp1, Register tmp2) {
5222   assert_different_registers(result, tmp1, tmp2);
5223   Label resolved;
5224 
5225   // A null weak handle resolves to null.
5226   cbz(result, resolved);
5227 
5228   // Only 64 bit platforms support GCs that require a tmp register
5229   // WeakHandle::resolve is an indirection like jweak.
5230   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
5231                  result, Address(result), tmp1, tmp2);
5232   bind(resolved);
5233 }
5234 
5235 void MacroAssembler::load_mirror(Register dst, Register method, Register tmp1, Register tmp2) {
5236   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
5237   ldr(dst, Address(rmethod, Method::const_offset()));
5238   ldr(dst, Address(dst, ConstMethod::constants_offset()));
5239   ldr(dst, Address(dst, ConstantPool::pool_holder_offset()));
5240   ldr(dst, Address(dst, mirror_offset));
5241   resolve_oop_handle(dst, tmp1, tmp2);
5242 }
5243 
5244 void MacroAssembler::cmp_klass(Register obj, Register klass, Register tmp) {
5245   assert_different_registers(obj, klass, tmp);
5246   if (UseCompactObjectHeaders) {
5247     load_narrow_klass_compact(tmp, obj);
5248   } else {
5249     ldrw(tmp, Address(obj, oopDesc::klass_offset_in_bytes()));
5250   }
5251   if (CompressedKlassPointers::base() == nullptr) {
5252     cmp(klass, tmp, LSL, CompressedKlassPointers::shift());
5253     return;
5254   } else if (!AOTCodeCache::is_on_for_dump() &&
5255              ((uint64_t)CompressedKlassPointers::base() & 0xffffffff) == 0
5256              && CompressedKlassPointers::shift() == 0) {
5257     // Only the bottom 32 bits matter
5258     cmpw(klass, tmp);
5259     return;
5260   }
5261   decode_klass_not_null(tmp);
5262   cmp(klass, tmp);
5263 }
5264 
5265 void MacroAssembler::cmp_klasses_from_objects(Register obj1, Register obj2, Register tmp1, Register tmp2) {
5266   if (UseCompactObjectHeaders) {
5267     load_narrow_klass_compact(tmp1, obj1);
5268     load_narrow_klass_compact(tmp2, obj2);
5269   } else {
5270     ldrw(tmp1, Address(obj1, oopDesc::klass_offset_in_bytes()));
5271     ldrw(tmp2, Address(obj2, oopDesc::klass_offset_in_bytes()));
5272   }
5273   cmpw(tmp1, tmp2);
5274 }
5275 
5276 void MacroAssembler::load_prototype_header(Register dst, Register src) {
5277   load_klass(dst, src);
5278   ldr(dst, Address(dst, Klass::prototype_header_offset()));
5279 }
5280 
5281 void MacroAssembler::store_klass(Register dst, Register src) {
5282   // FIXME: Should this be a store release?  concurrent gcs assumes
5283   // klass length is valid if klass field is not null.
5284   assert(!UseCompactObjectHeaders, "not with compact headers");
5285   encode_klass_not_null(src);
5286   strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
5287 }
5288 
5289 void MacroAssembler::store_klass_gap(Register dst, Register src) {
5290   assert(!UseCompactObjectHeaders, "not with compact headers");
5291   // Store to klass gap in destination
5292   strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
5293 }
5294 
5295 // Algorithm must match CompressedOops::encode.
5296 void MacroAssembler::encode_heap_oop(Register d, Register s) {
5297 #ifdef ASSERT
5298   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
5299 #endif
5300   verify_oop_msg(s, "broken oop in encode_heap_oop");
5301   if (CompressedOops::base() == nullptr) {
5302     if (CompressedOops::shift() != 0) {
5303       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5304       lsr(d, s, LogMinObjAlignmentInBytes);
5305     } else {
5306       mov(d, s);
5307     }
5308   } else {
5309     subs(d, s, rheapbase);
5310     csel(d, d, zr, Assembler::HS);
5311     lsr(d, d, LogMinObjAlignmentInBytes);
5312 
5313     /*  Old algorithm: is this any worse?
5314     Label nonnull;
5315     cbnz(r, nonnull);
5316     sub(r, r, rheapbase);
5317     bind(nonnull);
5318     lsr(r, r, LogMinObjAlignmentInBytes);
5319     */
5320   }
5321 }
5322 
5323 void MacroAssembler::encode_heap_oop_not_null(Register r) {
5324 #ifdef ASSERT
5325   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
5326   if (CheckCompressedOops) {
5327     Label ok;
5328     cbnz(r, ok);
5329     stop("null oop passed to encode_heap_oop_not_null");
5330     bind(ok);
5331   }
5332 #endif
5333   verify_oop_msg(r, "broken oop in encode_heap_oop_not_null");
5334   if (CompressedOops::base() != nullptr) {
5335     sub(r, r, rheapbase);
5336   }
5337   if (CompressedOops::shift() != 0) {
5338     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5339     lsr(r, r, LogMinObjAlignmentInBytes);
5340   }
5341 }
5342 
5343 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
5344 #ifdef ASSERT
5345   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
5346   if (CheckCompressedOops) {
5347     Label ok;
5348     cbnz(src, ok);
5349     stop("null oop passed to encode_heap_oop_not_null2");
5350     bind(ok);
5351   }
5352 #endif
5353   verify_oop_msg(src, "broken oop in encode_heap_oop_not_null2");
5354 
5355   Register data = src;
5356   if (CompressedOops::base() != nullptr) {
5357     sub(dst, src, rheapbase);
5358     data = dst;
5359   }
5360   if (CompressedOops::shift() != 0) {
5361     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5362     lsr(dst, data, LogMinObjAlignmentInBytes);
5363     data = dst;
5364   }
5365   if (data == src)
5366     mov(dst, src);
5367 }
5368 
5369 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
5370 #ifdef ASSERT
5371   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
5372 #endif
5373   if (CompressedOops::base() == nullptr) {
5374     if (CompressedOops::shift() != 0) {
5375       lsl(d, s, CompressedOops::shift());
5376     } else if (d != s) {
5377       mov(d, s);
5378     }
5379   } else {
5380     Label done;
5381     if (d != s)
5382       mov(d, s);
5383     cbz(s, done);
5384     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
5385     bind(done);
5386   }
5387   verify_oop_msg(d, "broken oop in decode_heap_oop");
5388 }
5389 
5390 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
5391   assert (UseCompressedOops, "should only be used for compressed headers");
5392   assert (Universe::heap() != nullptr, "java heap should be initialized");
5393   // Cannot assert, unverified entry point counts instructions (see .ad file)
5394   // vtableStubs also counts instructions in pd_code_size_limit.
5395   // Also do not verify_oop as this is called by verify_oop.
5396   if (CompressedOops::shift() != 0) {
5397     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5398     if (CompressedOops::base() != nullptr) {
5399       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
5400     } else {
5401       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
5402     }
5403   } else {
5404     assert (CompressedOops::base() == nullptr, "sanity");
5405   }
5406 }
5407 
5408 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
5409   assert (UseCompressedOops, "should only be used for compressed headers");
5410   assert (Universe::heap() != nullptr, "java heap should be initialized");
5411   // Cannot assert, unverified entry point counts instructions (see .ad file)
5412   // vtableStubs also counts instructions in pd_code_size_limit.
5413   // Also do not verify_oop as this is called by verify_oop.
5414   if (CompressedOops::shift() != 0) {
5415     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5416     if (CompressedOops::base() != nullptr) {
5417       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
5418     } else {
5419       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
5420     }
5421   } else {
5422     assert (CompressedOops::base() == nullptr, "sanity");
5423     if (dst != src) {
5424       mov(dst, src);
5425     }
5426   }
5427 }
5428 
5429 MacroAssembler::KlassDecodeMode MacroAssembler::_klass_decode_mode(KlassDecodeNone);
5430 
5431 MacroAssembler::KlassDecodeMode MacroAssembler::klass_decode_mode() {
5432   assert(Metaspace::initialized(), "metaspace not initialized yet");
5433   assert(_klass_decode_mode != KlassDecodeNone, "should be initialized");
5434   return _klass_decode_mode;
5435 }
5436 
5437 MacroAssembler::KlassDecodeMode  MacroAssembler::klass_decode_mode(address base, int shift, const size_t range) {
5438   // KlassDecodeMode shouldn't be set already.
5439   assert(_klass_decode_mode == KlassDecodeNone, "set once");
5440 
5441   if (base == nullptr) {
5442     return KlassDecodeZero;
5443   }
5444 
5445   if (operand_valid_for_logical_immediate(
5446         /*is32*/false, (uint64_t)base)) {
5447     const uint64_t range_mask = right_n_bits(log2i_ceil(range));
5448     if (((uint64_t)base & range_mask) == 0) {
5449       return KlassDecodeXor;
5450     }
5451   }
5452 
5453   const uint64_t shifted_base =
5454     (uint64_t)base >> shift;
5455   if ((shifted_base & 0xffff0000ffffffff) == 0) {
5456     return KlassDecodeMovk;
5457   }
5458 
5459   // No valid encoding.
5460   return KlassDecodeNone;
5461 }
5462 
5463 // Check if one of the above decoding modes will work for given base, shift and range.
5464 bool MacroAssembler::check_klass_decode_mode(address base, int shift, const size_t range) {
5465   return klass_decode_mode(base, shift, range) != KlassDecodeNone;
5466 }
5467 
5468 bool MacroAssembler::set_klass_decode_mode(address base, int shift, const size_t range) {
5469   _klass_decode_mode = klass_decode_mode(base, shift, range);
5470   return _klass_decode_mode != KlassDecodeNone;
5471 }
5472 
5473 static Register pick_different_tmp(Register dst, Register src) {
5474   auto tmps = RegSet::of(r0, r1, r2) - RegSet::of(src, dst);
5475   return *tmps.begin();
5476 }
5477 
5478 void MacroAssembler::encode_klass_not_null_for_aot(Register dst, Register src) {
5479   // we have to load the klass base from the AOT constants area but
5480   // not the shift because it is not allowed to change
5481   int shift = CompressedKlassPointers::shift();
5482   assert(shift >= 0 && shift <= CompressedKlassPointers::max_shift(), "unexpected compressed klass shift!");
5483   if (dst != src) {
5484     // we can load the base into dst, subtract it formthe src and shift down
5485     lea(dst, ExternalAddress(CompressedKlassPointers::base_addr()));
5486     ldr(dst, dst);
5487     sub(dst, src, dst);
5488     lsr(dst, dst, shift);
5489   } else {
5490     // we need an extra register in order to load the coop base
5491     Register tmp = pick_different_tmp(dst, src);
5492     RegSet regs = RegSet::of(tmp);
5493     push(regs, sp);
5494     lea(tmp, ExternalAddress(CompressedKlassPointers::base_addr()));
5495     ldr(tmp, tmp);
5496     sub(dst, src, tmp);
5497     lsr(dst, dst, shift);
5498     pop(regs, sp);
5499   }
5500 }
5501 
5502 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
5503   if (CompressedKlassPointers::base() != nullptr && AOTCodeCache::is_on_for_dump()) {
5504     encode_klass_not_null_for_aot(dst, src);
5505     return;
5506   }
5507 
5508   switch (klass_decode_mode()) {
5509   case KlassDecodeZero:
5510     if (CompressedKlassPointers::shift() != 0) {
5511       lsr(dst, src, CompressedKlassPointers::shift());
5512     } else {
5513       if (dst != src) mov(dst, src);
5514     }
5515     break;
5516 
5517   case KlassDecodeXor:
5518     if (CompressedKlassPointers::shift() != 0) {
5519       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5520       lsr(dst, dst, CompressedKlassPointers::shift());
5521     } else {
5522       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5523     }
5524     break;
5525 
5526   case KlassDecodeMovk:
5527     if (CompressedKlassPointers::shift() != 0) {
5528       ubfx(dst, src, CompressedKlassPointers::shift(), 32);
5529     } else {
5530       movw(dst, src);
5531     }
5532     break;
5533 
5534   case KlassDecodeNone:
5535     ShouldNotReachHere();
5536     break;
5537   }
5538 }
5539 
5540 void MacroAssembler::encode_klass_not_null(Register r) {
5541   encode_klass_not_null(r, r);
5542 }
5543 
5544 void MacroAssembler::decode_klass_not_null_for_aot(Register dst, Register src) {
5545   // we have to load the klass base from the AOT constants area but
5546   // not the shift because it is not allowed to change
5547   int shift = CompressedKlassPointers::shift();
5548   assert(shift >= 0 && shift <= CompressedKlassPointers::max_shift(), "unexpected compressed klass shift!");
5549   if (dst != src) {
5550     // we can load the base into dst then add the offset with a suitable shift
5551     lea(dst, ExternalAddress(CompressedKlassPointers::base_addr()));
5552     ldr(dst, dst);
5553     add(dst, dst, src, LSL,  shift);
5554   } else {
5555     // we need an extra register in order to load the coop base
5556     Register tmp = pick_different_tmp(dst, src);
5557     RegSet regs = RegSet::of(tmp);
5558     push(regs, sp);
5559     lea(tmp, ExternalAddress(CompressedKlassPointers::base_addr()));
5560     ldr(tmp, tmp);
5561     add(dst, tmp,  src, LSL,  shift);
5562     pop(regs, sp);
5563   }
5564 }
5565 
5566 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
5567   if (AOTCodeCache::is_on_for_dump()) {
5568     decode_klass_not_null_for_aot(dst, src);
5569     return;
5570   }
5571 
5572   switch (klass_decode_mode()) {
5573   case KlassDecodeZero:
5574     if (CompressedKlassPointers::shift() != 0) {
5575       lsl(dst, src, CompressedKlassPointers::shift());
5576     } else {
5577       if (dst != src) mov(dst, src);
5578     }
5579     break;
5580 
5581   case KlassDecodeXor:
5582     if (CompressedKlassPointers::shift() != 0) {
5583       lsl(dst, src, CompressedKlassPointers::shift());
5584       eor(dst, dst, (uint64_t)CompressedKlassPointers::base());
5585     } else {
5586       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5587     }
5588     break;
5589 
5590   case KlassDecodeMovk: {
5591     const uint64_t shifted_base =
5592       (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
5593 
5594     if (dst != src) movw(dst, src);
5595     movk(dst, shifted_base >> 32, 32);
5596 
5597     if (CompressedKlassPointers::shift() != 0) {
5598       lsl(dst, dst, CompressedKlassPointers::shift());
5599     }
5600 
5601     break;
5602   }
5603 
5604   case KlassDecodeNone:
5605     ShouldNotReachHere();
5606     break;
5607   }
5608 }
5609 
5610 void  MacroAssembler::decode_klass_not_null(Register r) {
5611   decode_klass_not_null(r, r);
5612 }
5613 
5614 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
5615 #ifdef ASSERT
5616   {
5617     ThreadInVMfromUnknown tiv;
5618     assert (UseCompressedOops, "should only be used for compressed oops");
5619     assert (Universe::heap() != nullptr, "java heap should be initialized");
5620     assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5621     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
5622   }
5623 #endif
5624   int oop_index = oop_recorder()->find_index(obj);
5625   InstructionMark im(this);
5626   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5627   code_section()->relocate(inst_mark(), rspec);
5628   movz(dst, 0xDEAD, 16);
5629   movk(dst, 0xBEEF);
5630 }
5631 
5632 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
5633   assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5634   int index = oop_recorder()->find_index(k);
5635 
5636   InstructionMark im(this);
5637   RelocationHolder rspec = metadata_Relocation::spec(index);
5638   code_section()->relocate(inst_mark(), rspec);
5639   narrowKlass nk = CompressedKlassPointers::encode(k);
5640   movz(dst, (nk >> 16), 16);
5641   movk(dst, nk & 0xffff);
5642 }
5643 
5644 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators,
5645                                     Register dst, Address src,
5646                                     Register tmp1, Register tmp2) {
5647   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5648   decorators = AccessInternal::decorator_fixup(decorators, type);
5649   bool as_raw = (decorators & AS_RAW) != 0;
5650   if (as_raw) {
5651     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, tmp2);
5652   } else {
5653     bs->load_at(this, decorators, type, dst, src, tmp1, tmp2);
5654   }
5655 }
5656 
5657 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators,
5658                                      Address dst, Register val,
5659                                      Register tmp1, Register tmp2, Register tmp3) {
5660   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5661   decorators = AccessInternal::decorator_fixup(decorators, type);
5662   bool as_raw = (decorators & AS_RAW) != 0;
5663   if (as_raw) {
5664     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
5665   } else {
5666     bs->store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
5667   }
5668 }
5669 
5670 void MacroAssembler::flat_field_copy(DecoratorSet decorators, Register src, Register dst,
5671                                      Register inline_layout_info) {
5672   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5673   bs->flat_field_copy(this, decorators, src, dst, inline_layout_info);
5674 }
5675 
5676 void MacroAssembler::payload_offset(Register inline_klass, Register offset) {
5677   ldr(offset, Address(inline_klass, InlineKlass::adr_members_offset()));
5678   ldrw(offset, Address(offset, InlineKlass::payload_offset_offset()));
5679 }
5680 
5681 void MacroAssembler::payload_address(Register oop, Register data, Register inline_klass) {
5682   // ((address) (void*) o) + vk->payload_offset();
5683   Register offset = (data == oop) ? rscratch1 : data;
5684   payload_offset(inline_klass, offset);
5685   if (data == oop) {
5686     add(data, data, offset);
5687   } else {
5688     lea(data, Address(oop, offset));
5689   }
5690 }
5691 
5692 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
5693                                    Register tmp2, DecoratorSet decorators) {
5694   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
5695 }
5696 
5697 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
5698                                             Register tmp2, DecoratorSet decorators) {
5699   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, tmp2);
5700 }
5701 
5702 void MacroAssembler::store_heap_oop(Address dst, Register val, Register tmp1,
5703                                     Register tmp2, Register tmp3, DecoratorSet decorators) {
5704   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, val, tmp1, tmp2, tmp3);
5705 }
5706 
5707 // Used for storing nulls.
5708 void MacroAssembler::store_heap_oop_null(Address dst) {
5709   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg, noreg);
5710 }
5711 
5712 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
5713   assert(oop_recorder() != nullptr, "this assembler needs a Recorder");
5714   int index = oop_recorder()->allocate_metadata_index(obj);
5715   RelocationHolder rspec = metadata_Relocation::spec(index);
5716   return Address((address)obj, rspec);
5717 }
5718 
5719 // Move an oop into a register.
5720 void MacroAssembler::movoop(Register dst, jobject obj) {
5721   int oop_index;
5722   if (obj == nullptr) {
5723     oop_index = oop_recorder()->allocate_oop_index(obj);
5724   } else {
5725 #ifdef ASSERT
5726     {
5727       ThreadInVMfromUnknown tiv;
5728       assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
5729     }
5730 #endif
5731     oop_index = oop_recorder()->find_index(obj);
5732   }
5733   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5734 
5735   if (BarrierSet::barrier_set()->barrier_set_assembler()->supports_instruction_patching()) {
5736     mov(dst, Address((address)obj, rspec));
5737   } else {
5738     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
5739     ldr(dst, Address(dummy, rspec));
5740   }
5741 }
5742 
5743 // Move a metadata address into a register.
5744 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
5745   int oop_index;
5746   if (obj == nullptr) {
5747     oop_index = oop_recorder()->allocate_metadata_index(obj);
5748   } else {
5749     oop_index = oop_recorder()->find_index(obj);
5750   }
5751   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
5752   mov(dst, Address((address)obj, rspec));
5753 }
5754 
5755 Address MacroAssembler::constant_oop_address(jobject obj) {
5756 #ifdef ASSERT
5757   {
5758     ThreadInVMfromUnknown tiv;
5759     assert(oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5760     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "not an oop");
5761   }
5762 #endif
5763   int oop_index = oop_recorder()->find_index(obj);
5764   return Address((address)obj, oop_Relocation::spec(oop_index));
5765 }
5766 
5767 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5768 void MacroAssembler::tlab_allocate(Register obj,
5769                                    Register var_size_in_bytes,
5770                                    int con_size_in_bytes,
5771                                    Register t1,
5772                                    Register t2,
5773                                    Label& slow_case) {
5774   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5775   bs->tlab_allocate(this, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
5776 }
5777 
5778 void MacroAssembler::verify_tlab() {
5779 #ifdef ASSERT
5780   if (UseTLAB && VerifyOops) {
5781     Label next, ok;
5782 
5783     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
5784 
5785     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
5786     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
5787     cmp(rscratch2, rscratch1);
5788     br(Assembler::HS, next);
5789     STOP("assert(top >= start)");
5790     should_not_reach_here();
5791 
5792     bind(next);
5793     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
5794     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
5795     cmp(rscratch2, rscratch1);
5796     br(Assembler::HS, ok);
5797     STOP("assert(top <= end)");
5798     should_not_reach_here();
5799 
5800     bind(ok);
5801     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
5802   }
5803 #endif
5804 }
5805 
5806 void MacroAssembler::inline_layout_info(Register holder_klass, Register index, Register layout_info) {
5807   assert_different_registers(holder_klass, index, layout_info);
5808   InlineLayoutInfo array[2];
5809   int size = (char*)&array[1] - (char*)&array[0]; // computing size of array elements
5810   if (is_power_of_2(size)) {
5811     lsl(index, index, log2i_exact(size)); // Scale index by power of 2
5812   } else {
5813     mov(layout_info, size);
5814     mul(index, index, layout_info); // Scale the index to be the entry index * array_element_size
5815   }
5816   ldr(layout_info, Address(holder_klass, InstanceKlass::inline_layout_info_array_offset()));
5817   add(layout_info, layout_info, Array<InlineLayoutInfo>::base_offset_in_bytes());
5818   lea(layout_info, Address(layout_info, index));
5819 }
5820 
5821 // Writes to stack successive pages until offset reached to check for
5822 // stack overflow + shadow pages.  This clobbers tmp.
5823 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
5824   assert_different_registers(tmp, size, rscratch1);
5825   mov(tmp, sp);
5826   // Bang stack for total size given plus shadow page size.
5827   // Bang one page at a time because large size can bang beyond yellow and
5828   // red zones.
5829   Label loop;
5830   mov(rscratch1, (int)os::vm_page_size());
5831   bind(loop);
5832   lea(tmp, Address(tmp, -(int)os::vm_page_size()));
5833   subsw(size, size, rscratch1);
5834   str(size, Address(tmp));
5835   br(Assembler::GT, loop);
5836 
5837   // Bang down shadow pages too.
5838   // At this point, (tmp-0) is the last address touched, so don't
5839   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
5840   // was post-decremented.)  Skip this address by starting at i=1, and
5841   // touch a few more pages below.  N.B.  It is important to touch all
5842   // the way down to and including i=StackShadowPages.
5843   for (int i = 0; i < (int)(StackOverflow::stack_shadow_zone_size() / (int)os::vm_page_size()) - 1; i++) {
5844     // this could be any sized move but this is can be a debugging crumb
5845     // so the bigger the better.
5846     lea(tmp, Address(tmp, -(int)os::vm_page_size()));
5847     str(size, Address(tmp));
5848   }
5849 }
5850 
5851 // Move the address of the polling page into dest.
5852 void MacroAssembler::get_polling_page(Register dest, relocInfo::relocType rtype) {
5853   ldr(dest, Address(rthread, JavaThread::polling_page_offset()));
5854 }
5855 
5856 // Read the polling page.  The address of the polling page must
5857 // already be in r.
5858 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
5859   address mark;
5860   {
5861     InstructionMark im(this);
5862     code_section()->relocate(inst_mark(), rtype);
5863     ldrw(zr, Address(r, 0));
5864     mark = inst_mark();
5865   }
5866   verify_cross_modify_fence_not_required();
5867   return mark;
5868 }
5869 
5870 void MacroAssembler::adrp(Register reg1, const Address &dest, uint64_t &byte_offset) {
5871   uint64_t low_page = (uint64_t)CodeCache::low_bound() >> 12;
5872   uint64_t high_page = (uint64_t)(CodeCache::high_bound()-1) >> 12;
5873   uint64_t dest_page = (uint64_t)dest.target() >> 12;
5874   int64_t offset_low = dest_page - low_page;
5875   int64_t offset_high = dest_page - high_page;
5876 
5877   assert(is_valid_AArch64_address(dest.target()), "bad address");
5878   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
5879 
5880   InstructionMark im(this);
5881   code_section()->relocate(inst_mark(), dest.rspec());
5882   // 8143067: Ensure that the adrp can reach the dest from anywhere within
5883   // the code cache so that if it is relocated we know it will still reach
5884   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
5885     _adrp(reg1, dest.target());
5886   } else {
5887     uint64_t target = (uint64_t)dest.target();
5888     uint64_t adrp_target
5889       = (target & 0xffffffffULL) | ((uint64_t)pc() & 0xffff00000000ULL);
5890 
5891     _adrp(reg1, (address)adrp_target);
5892     movk(reg1, target >> 32, 32);
5893   }
5894   byte_offset = (uint64_t)dest.target() & 0xfff;
5895 }
5896 
5897 void MacroAssembler::load_byte_map_base(Register reg) {
5898 #if INCLUDE_CDS
5899   if (AOTCodeCache::is_on_for_dump()) {
5900     address byte_map_base_adr = AOTRuntimeConstants::card_table_base_address();
5901     lea(reg, ExternalAddress(byte_map_base_adr));
5902     ldr(reg, Address(reg));
5903     return;
5904   }
5905 #endif
5906   CardTableBarrierSet* ctbs = CardTableBarrierSet::barrier_set();
5907 
5908   // Strictly speaking the card table base isn't an address at all, and it might
5909   // even be negative. It is thus materialised as a constant.
5910   mov(reg, (uint64_t)ctbs->card_table_base_const());
5911 }
5912 
5913 void MacroAssembler::load_aotrc_address(Register reg, address a) {
5914 #if INCLUDE_CDS
5915   assert(AOTRuntimeConstants::contains(a), "address out of range for data area");
5916   if (AOTCodeCache::is_on_for_dump()) {
5917     // all aotrc field addresses should be registered in the AOTCodeCache address table
5918     lea(reg, ExternalAddress(a));
5919   } else {
5920     mov(reg, (uint64_t)a);
5921   }
5922 #else
5923   ShouldNotReachHere();
5924 #endif
5925 }
5926 
5927 #ifdef ASSERT
5928 void MacroAssembler::build_frame(int framesize) {
5929   build_frame(framesize, false);
5930 }
5931 #endif
5932 
5933 void MacroAssembler::build_frame(int framesize DEBUG_ONLY(COMMA bool zap_rfp_lr_spills)) {
5934   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
5935   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
5936   protect_return_address();
5937   if (framesize < ((1 << 9) + 2 * wordSize)) {
5938     sub(sp, sp, framesize);
5939     if (DEBUG_ONLY(zap_rfp_lr_spills ||) false) {
5940       mov_immediate64(rscratch1, ((uint64_t)badRegWordVal) << 32 | (uint64_t)badRegWordVal);
5941       stp(rscratch1, rscratch1, Address(sp, framesize - 2 * wordSize));
5942     } else {
5943       stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
5944     }
5945     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
5946   } else {
5947     if (DEBUG_ONLY(zap_rfp_lr_spills ||) false) {
5948       mov_immediate64(rscratch1, ((uint64_t)badRegWordVal) << 32 | (uint64_t)badRegWordVal);
5949       stp(rscratch1, rscratch1, Address(pre(sp, -2 * wordSize)));
5950     } else {
5951       stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
5952     }
5953     if (PreserveFramePointer) mov(rfp, sp);
5954     if (framesize < ((1 << 12) + 2 * wordSize))
5955       sub(sp, sp, framesize - 2 * wordSize);
5956     else {
5957       mov(rscratch1, framesize - 2 * wordSize);
5958       sub(sp, sp, rscratch1);
5959     }
5960   }
5961   verify_cross_modify_fence_not_required();
5962 }
5963 
5964 void MacroAssembler::remove_frame(int framesize) {
5965   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
5966   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
5967   if (framesize < ((1 << 9) + 2 * wordSize)) {
5968     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
5969     add(sp, sp, framesize);
5970   } else {
5971     if (framesize < ((1 << 12) + 2 * wordSize))
5972       add(sp, sp, framesize - 2 * wordSize);
5973     else {
5974       mov(rscratch1, framesize - 2 * wordSize);
5975       add(sp, sp, rscratch1);
5976     }
5977     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
5978   }
5979   authenticate_return_address();
5980 }
5981 
5982 void MacroAssembler::remove_frame(int initial_framesize, bool needs_stack_repair) {
5983   if (needs_stack_repair) {
5984     // The method has a scalarized entry point (where fields of value object arguments
5985     // are passed through registers and stack), and a non-scalarized entry point (where
5986     // value object arguments are given as oops). The non-scalarized entry point will
5987     // first load each field of value object arguments and store them in registers and on
5988     // the stack in a way compatible with the scalarized entry point. To do so, some extra
5989     // stack space might be reserved (if argument registers are not enough). On leaving the
5990     // method, this space must be freed.
5991     //
5992     // In case we used the non-scalarized entry point the stack looks like this:
5993     //
5994     // | Arguments from caller     |
5995     // |---------------------------|  <-- caller's SP
5996     // | Saved LR #1               |
5997     // | Saved FP #1               |
5998     // |---------------------------|
5999     // | Extension space for       |
6000     // |   inline arg (un)packing  |
6001     // |---------------------------|  <-- start of this method's frame
6002     // | Saved LR #2               |
6003     // | Saved FP #2               |
6004     // |---------------------------|  <-- FP (with -XX:+PreserveFramePointer)
6005     // | sp_inc                    |
6006     // | method locals             |
6007     // |---------------------------|  <-- SP
6008     //
6009     // There are two copies of FP and LR on the stack. They will be identical at
6010     // first, but that can change.
6011     // If the caller has been deoptimized, LR #1 will be patched to point at the
6012     // deopt blob, and LR #2 will still point into the old method.
6013     // If the saved FP (x29) was not used as the frame pointer, but to store an
6014     // oop, the GC will be aware only of FP #1 as the spilled location of x29 and
6015     // will fix only this one. Overall, FP/LR #2 are not reliable and are simply
6016     // needed to add space between the extension space and the locals, as there
6017     // would be between the real arguments and the locals if we don't need to
6018     // do unpacking (from the scalarized entry point).
6019     //
6020     // When restoring, one must then load FP #1 into x29, and LR #1 into x30,
6021     // while keeping in mind that from the scalarized entry point, there will be
6022     // only one copy of each. Indeed, in the case we used the scalarized calling
6023     // convention, the stack looks like this:
6024     //
6025     // | Arguments from caller     |
6026     // |---------------------------|  <-- caller's SP / start of this method's frame
6027     // | Saved LR                  |
6028     // | Saved FP                  |
6029     // |---------------------------|  <-- FP (with -XX:+PreserveFramePointer)
6030     // | sp_inc                    |
6031     // | method locals             |
6032     // |---------------------------|  <-- SP
6033     //
6034     // The sp_inc stack slot holds the total size of the frame including the
6035     // extension space minus two words for the saved FP and LR. That is how to
6036     // find FP/LR #1. This size is expressed in bytes. Be careful when using it
6037     // from C++ in pointer arithmetic; you might need to divide it by wordSize.
6038     //
6039     // One can find sp_inc since the start the method's frame is SP + initial_framesize.
6040 
6041     int sp_inc_offset = initial_framesize - 3 * wordSize;  // Immediately below saved LR and FP
6042 
6043     ldr(rscratch1, Address(sp, sp_inc_offset));
6044     add(sp, sp, rscratch1);
6045     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
6046   } else {
6047     remove_frame(initial_framesize);
6048   }
6049 }
6050 
6051 void MacroAssembler::save_stack_increment(int sp_inc, int frame_size) {
6052   int real_frame_size = frame_size + sp_inc;
6053   assert(sp_inc == 0 || sp_inc > 2*wordSize, "invalid sp_inc value");
6054   assert(real_frame_size >= 2*wordSize, "frame size must include FP/LR space");
6055   assert((real_frame_size & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6056 
6057   int sp_inc_offset = frame_size - 3 * wordSize;  // Immediately below saved LR and FP
6058 
6059   // Subtract two words for the saved FP and LR as these will be popped
6060   // separately. See remove_frame above.
6061   mov(rscratch1, real_frame_size - 2*wordSize);
6062   str(rscratch1, Address(sp, sp_inc_offset));
6063 }
6064 
6065 // This method counts leading positive bytes (highest bit not set) in provided byte array
6066 address MacroAssembler::count_positives(Register ary1, Register len, Register result) {
6067     // Simple and most common case of aligned small array which is not at the
6068     // end of memory page is placed here. All other cases are in stub.
6069     Label LOOP, END, STUB, STUB_LONG, SET_RESULT, DONE;
6070     const uint64_t UPPER_BIT_MASK=0x8080808080808080;
6071     assert_different_registers(ary1, len, result);
6072 
6073     mov(result, len);
6074     cmpw(len, 0);
6075     br(LE, DONE);
6076     cmpw(len, 4 * wordSize);
6077     br(GE, STUB_LONG); // size > 32 then go to stub
6078 
6079     int shift = 64 - exact_log2(os::vm_page_size());
6080     lsl(rscratch1, ary1, shift);
6081     mov(rscratch2, (size_t)(4 * wordSize) << shift);
6082     adds(rscratch2, rscratch1, rscratch2);  // At end of page?
6083     br(CS, STUB); // at the end of page then go to stub
6084     subs(len, len, wordSize);
6085     br(LT, END);
6086 
6087   BIND(LOOP);
6088     ldr(rscratch1, Address(post(ary1, wordSize)));
6089     tst(rscratch1, UPPER_BIT_MASK);
6090     br(NE, SET_RESULT);
6091     subs(len, len, wordSize);
6092     br(GE, LOOP);
6093     cmpw(len, -wordSize);
6094     br(EQ, DONE);
6095 
6096   BIND(END);
6097     ldr(rscratch1, Address(ary1));
6098     sub(rscratch2, zr, len, LSL, 3); // LSL 3 is to get bits from bytes
6099     lslv(rscratch1, rscratch1, rscratch2);
6100     tst(rscratch1, UPPER_BIT_MASK);
6101     br(NE, SET_RESULT);
6102     b(DONE);
6103 
6104   BIND(STUB);
6105     RuntimeAddress count_pos = RuntimeAddress(StubRoutines::aarch64::count_positives());
6106     assert(count_pos.target() != nullptr, "count_positives stub has not been generated");
6107     address tpc1 = trampoline_call(count_pos);
6108     if (tpc1 == nullptr) {
6109       DEBUG_ONLY(reset_labels(STUB_LONG, SET_RESULT, DONE));
6110       postcond(pc() == badAddress);
6111       return nullptr;
6112     }
6113     b(DONE);
6114 
6115   BIND(STUB_LONG);
6116     RuntimeAddress count_pos_long = RuntimeAddress(StubRoutines::aarch64::count_positives_long());
6117     assert(count_pos_long.target() != nullptr, "count_positives_long stub has not been generated");
6118     address tpc2 = trampoline_call(count_pos_long);
6119     if (tpc2 == nullptr) {
6120       DEBUG_ONLY(reset_labels(SET_RESULT, DONE));
6121       postcond(pc() == badAddress);
6122       return nullptr;
6123     }
6124     b(DONE);
6125 
6126   BIND(SET_RESULT);
6127 
6128     add(len, len, wordSize);
6129     sub(result, result, len);
6130 
6131   BIND(DONE);
6132   postcond(pc() != badAddress);
6133   return pc();
6134 }
6135 
6136 // Clobbers: rscratch1, rscratch2, rflags
6137 // May also clobber v0-v7 when (!UseSimpleArrayEquals && UseSIMDForArrayEquals)
6138 address MacroAssembler::arrays_equals(Register a1, Register a2, Register tmp3,
6139                                       Register tmp4, Register tmp5, Register result,
6140                                       Register cnt1, int elem_size) {
6141   Label DONE, SAME;
6142   Register tmp1 = rscratch1;
6143   Register tmp2 = rscratch2;
6144   int elem_per_word = wordSize/elem_size;
6145   int log_elem_size = exact_log2(elem_size);
6146   int klass_offset  = arrayOopDesc::klass_offset_in_bytes();
6147   int length_offset = arrayOopDesc::length_offset_in_bytes();
6148   int base_offset
6149     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
6150   // When the length offset is not aligned to 8 bytes,
6151   // then we align it down. This is valid because the new
6152   // offset will always be the klass which is the same
6153   // for type arrays.
6154   int start_offset = align_down(length_offset, BytesPerWord);
6155   int extra_length = base_offset - start_offset;
6156   assert(start_offset == length_offset || start_offset == klass_offset,
6157          "start offset must be 8-byte-aligned or be the klass offset");
6158   assert(base_offset != start_offset, "must include the length field");
6159   extra_length = extra_length / elem_size; // We count in elements, not bytes.
6160   int stubBytesThreshold = 3 * 64 + (UseSIMDForArrayEquals ? 0 : 16);
6161 
6162   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
6163   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
6164 
6165 #ifndef PRODUCT
6166   {
6167     const char kind = (elem_size == 2) ? 'U' : 'L';
6168     char comment[64];
6169     os::snprintf_checked(comment, sizeof comment, "array_equals%c{", kind);
6170     BLOCK_COMMENT(comment);
6171   }
6172 #endif
6173 
6174   // if (a1 == a2)
6175   //     return true;
6176   cmpoop(a1, a2); // May have read barriers for a1 and a2.
6177   br(EQ, SAME);
6178 
6179   if (UseSimpleArrayEquals) {
6180     Label NEXT_WORD, SHORT, TAIL03, TAIL01, A_MIGHT_BE_NULL, A_IS_NOT_NULL;
6181     // if (a1 == nullptr || a2 == nullptr)
6182     //     return false;
6183     // a1 & a2 == 0 means (some-pointer is null) or
6184     // (very-rare-or-even-probably-impossible-pointer-values)
6185     // so, we can save one branch in most cases
6186     tst(a1, a2);
6187     mov(result, false);
6188     br(EQ, A_MIGHT_BE_NULL);
6189     // if (a1.length != a2.length)
6190     //      return false;
6191     bind(A_IS_NOT_NULL);
6192     ldrw(cnt1, Address(a1, length_offset));
6193     ldrw(tmp5, Address(a2, length_offset));
6194     cmp(cnt1, tmp5);
6195     br(NE, DONE); // If lengths differ, return false
6196     // Increase loop counter by diff between base- and actual start-offset.
6197     addw(cnt1, cnt1, extra_length);
6198     lea(a1, Address(a1, start_offset));
6199     lea(a2, Address(a2, start_offset));
6200     // Check for short strings, i.e. smaller than wordSize.
6201     subs(cnt1, cnt1, elem_per_word);
6202     br(Assembler::LT, SHORT);
6203     // Main 8 byte comparison loop.
6204     bind(NEXT_WORD); {
6205       ldr(tmp1, Address(post(a1, wordSize)));
6206       ldr(tmp2, Address(post(a2, wordSize)));
6207       subs(cnt1, cnt1, elem_per_word);
6208       eor(tmp5, tmp1, tmp2);
6209       cbnz(tmp5, DONE);
6210     } br(GT, NEXT_WORD);
6211     // Last longword.  In the case where length == 4 we compare the
6212     // same longword twice, but that's still faster than another
6213     // conditional branch.
6214     // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
6215     // length == 4.
6216     if (log_elem_size > 0)
6217       lsl(cnt1, cnt1, log_elem_size);
6218     ldr(tmp3, Address(a1, cnt1));
6219     ldr(tmp4, Address(a2, cnt1));
6220     eor(tmp5, tmp3, tmp4);
6221     cbnz(tmp5, DONE);
6222     b(SAME);
6223     bind(A_MIGHT_BE_NULL);
6224     // in case both a1 and a2 are not-null, proceed with loads
6225     cbz(a1, DONE);
6226     cbz(a2, DONE);
6227     b(A_IS_NOT_NULL);
6228     bind(SHORT);
6229 
6230     tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
6231     {
6232       ldrw(tmp1, Address(post(a1, 4)));
6233       ldrw(tmp2, Address(post(a2, 4)));
6234       eorw(tmp5, tmp1, tmp2);
6235       cbnzw(tmp5, DONE);
6236     }
6237     bind(TAIL03);
6238     tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
6239     {
6240       ldrh(tmp3, Address(post(a1, 2)));
6241       ldrh(tmp4, Address(post(a2, 2)));
6242       eorw(tmp5, tmp3, tmp4);
6243       cbnzw(tmp5, DONE);
6244     }
6245     bind(TAIL01);
6246     if (elem_size == 1) { // Only needed when comparing byte arrays.
6247       tbz(cnt1, 0, SAME); // 0-1 bytes left.
6248       {
6249         ldrb(tmp1, a1);
6250         ldrb(tmp2, a2);
6251         eorw(tmp5, tmp1, tmp2);
6252         cbnzw(tmp5, DONE);
6253       }
6254     }
6255   } else {
6256     Label NEXT_DWORD, SHORT, TAIL, TAIL2, STUB,
6257         CSET_EQ, LAST_CHECK;
6258     mov(result, false);
6259     cbz(a1, DONE);
6260     ldrw(cnt1, Address(a1, length_offset));
6261     cbz(a2, DONE);
6262     ldrw(tmp5, Address(a2, length_offset));
6263     cmp(cnt1, tmp5);
6264     br(NE, DONE); // If lengths differ, return false
6265     // Increase loop counter by diff between base- and actual start-offset.
6266     addw(cnt1, cnt1, extra_length);
6267 
6268     // on most CPUs a2 is still "locked"(surprisingly) in ldrw and it's
6269     // faster to perform another branch before comparing a1 and a2
6270     cmp(cnt1, (u1)elem_per_word);
6271     br(LE, SHORT); // short or same
6272     ldr(tmp3, Address(pre(a1, start_offset)));
6273     subs(zr, cnt1, stubBytesThreshold);
6274     br(GE, STUB);
6275     ldr(tmp4, Address(pre(a2, start_offset)));
6276     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
6277 
6278     // Main 16 byte comparison loop with 2 exits
6279     bind(NEXT_DWORD); {
6280       ldr(tmp1, Address(pre(a1, wordSize)));
6281       ldr(tmp2, Address(pre(a2, wordSize)));
6282       subs(cnt1, cnt1, 2 * elem_per_word);
6283       br(LE, TAIL);
6284       eor(tmp4, tmp3, tmp4);
6285       cbnz(tmp4, DONE);
6286       ldr(tmp3, Address(pre(a1, wordSize)));
6287       ldr(tmp4, Address(pre(a2, wordSize)));
6288       cmp(cnt1, (u1)elem_per_word);
6289       br(LE, TAIL2);
6290       cmp(tmp1, tmp2);
6291     } br(EQ, NEXT_DWORD);
6292     b(DONE);
6293 
6294     bind(TAIL);
6295     eor(tmp4, tmp3, tmp4);
6296     eor(tmp2, tmp1, tmp2);
6297     lslv(tmp2, tmp2, tmp5);
6298     orr(tmp5, tmp4, tmp2);
6299     cmp(tmp5, zr);
6300     b(CSET_EQ);
6301 
6302     bind(TAIL2);
6303     eor(tmp2, tmp1, tmp2);
6304     cbnz(tmp2, DONE);
6305     b(LAST_CHECK);
6306 
6307     bind(STUB);
6308     ldr(tmp4, Address(pre(a2, start_offset)));
6309     if (elem_size == 2) { // convert to byte counter
6310       lsl(cnt1, cnt1, 1);
6311     }
6312     eor(tmp5, tmp3, tmp4);
6313     cbnz(tmp5, DONE);
6314     RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_array_equals());
6315     assert(stub.target() != nullptr, "array_equals_long stub has not been generated");
6316     address tpc = trampoline_call(stub);
6317     if (tpc == nullptr) {
6318       DEBUG_ONLY(reset_labels(SHORT, LAST_CHECK, CSET_EQ, SAME, DONE));
6319       postcond(pc() == badAddress);
6320       return nullptr;
6321     }
6322     b(DONE);
6323 
6324     // (a1 != null && a2 == null) || (a1 != null && a2 != null && a1 == a2)
6325     // so, if a2 == null => return false(0), else return true, so we can return a2
6326     mov(result, a2);
6327     b(DONE);
6328     bind(SHORT);
6329     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
6330     ldr(tmp3, Address(a1, start_offset));
6331     ldr(tmp4, Address(a2, start_offset));
6332     bind(LAST_CHECK);
6333     eor(tmp4, tmp3, tmp4);
6334     lslv(tmp5, tmp4, tmp5);
6335     cmp(tmp5, zr);
6336     bind(CSET_EQ);
6337     cset(result, EQ);
6338     b(DONE);
6339   }
6340 
6341   bind(SAME);
6342   mov(result, true);
6343   // That's it.
6344   bind(DONE);
6345 
6346   BLOCK_COMMENT("} array_equals");
6347   postcond(pc() != badAddress);
6348   return pc();
6349 }
6350 
6351 // Compare Strings
6352 
6353 // For Strings we're passed the address of the first characters in a1
6354 // and a2 and the length in cnt1.
6355 // There are two implementations.  For arrays >= 8 bytes, all
6356 // comparisons (including the final one, which may overlap) are
6357 // performed 8 bytes at a time.  For strings < 8 bytes, we compare a
6358 // halfword, then a short, and then a byte.
6359 
6360 void MacroAssembler::string_equals(Register a1, Register a2,
6361                                    Register result, Register cnt1)
6362 {
6363   Label SAME, DONE, SHORT, NEXT_WORD;
6364   Register tmp1 = rscratch1;
6365   Register tmp2 = rscratch2;
6366 
6367   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
6368 
6369 #ifndef PRODUCT
6370   {
6371     char comment[64];
6372     os::snprintf_checked(comment, sizeof comment, "{string_equalsL");
6373     BLOCK_COMMENT(comment);
6374   }
6375 #endif
6376 
6377   mov(result, false);
6378 
6379   // Check for short strings, i.e. smaller than wordSize.
6380   subs(cnt1, cnt1, wordSize);
6381   br(Assembler::LT, SHORT);
6382   // Main 8 byte comparison loop.
6383   bind(NEXT_WORD); {
6384     ldr(tmp1, Address(post(a1, wordSize)));
6385     ldr(tmp2, Address(post(a2, wordSize)));
6386     subs(cnt1, cnt1, wordSize);
6387     eor(tmp1, tmp1, tmp2);
6388     cbnz(tmp1, DONE);
6389   } br(GT, NEXT_WORD);
6390   // Last longword.  In the case where length == 4 we compare the
6391   // same longword twice, but that's still faster than another
6392   // conditional branch.
6393   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
6394   // length == 4.
6395   ldr(tmp1, Address(a1, cnt1));
6396   ldr(tmp2, Address(a2, cnt1));
6397   eor(tmp2, tmp1, tmp2);
6398   cbnz(tmp2, DONE);
6399   b(SAME);
6400 
6401   bind(SHORT);
6402   Label TAIL03, TAIL01;
6403 
6404   tbz(cnt1, 2, TAIL03); // 0-7 bytes left.
6405   {
6406     ldrw(tmp1, Address(post(a1, 4)));
6407     ldrw(tmp2, Address(post(a2, 4)));
6408     eorw(tmp1, tmp1, tmp2);
6409     cbnzw(tmp1, DONE);
6410   }
6411   bind(TAIL03);
6412   tbz(cnt1, 1, TAIL01); // 0-3 bytes left.
6413   {
6414     ldrh(tmp1, Address(post(a1, 2)));
6415     ldrh(tmp2, Address(post(a2, 2)));
6416     eorw(tmp1, tmp1, tmp2);
6417     cbnzw(tmp1, DONE);
6418   }
6419   bind(TAIL01);
6420   tbz(cnt1, 0, SAME); // 0-1 bytes left.
6421     {
6422     ldrb(tmp1, a1);
6423     ldrb(tmp2, a2);
6424     eorw(tmp1, tmp1, tmp2);
6425     cbnzw(tmp1, DONE);
6426   }
6427   // Arrays are equal.
6428   bind(SAME);
6429   mov(result, true);
6430 
6431   // That's it.
6432   bind(DONE);
6433   BLOCK_COMMENT("} string_equals");
6434 }
6435 
6436 
6437 // The size of the blocks erased by the zero_blocks stub.  We must
6438 // handle anything smaller than this ourselves in zero_words().
6439 const int MacroAssembler::zero_words_block_size = 8;
6440 
6441 // zero_words() is used by C2 ClearArray patterns and by
6442 // C1_MacroAssembler.  It is as small as possible, handling small word
6443 // counts locally and delegating anything larger to the zero_blocks
6444 // stub.  It is expanded many times in compiled code, so it is
6445 // important to keep it short.
6446 
6447 // ptr:   Address of a buffer to be zeroed.
6448 // cnt:   Count in HeapWords.
6449 //
6450 // ptr, cnt, rscratch1, and rscratch2 are clobbered.
6451 address MacroAssembler::zero_words(Register ptr, Register cnt)
6452 {
6453   assert(is_power_of_2(zero_words_block_size), "adjust this");
6454 
6455   BLOCK_COMMENT("zero_words {");
6456   assert(ptr == r10 && cnt == r11, "mismatch in register usage");
6457   RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
6458   assert(zero_blocks.target() != nullptr, "zero_blocks stub has not been generated");
6459 
6460   subs(rscratch1, cnt, zero_words_block_size);
6461   Label around;
6462   br(LO, around);
6463   {
6464     RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
6465     assert(zero_blocks.target() != nullptr, "zero_blocks stub has not been generated");
6466     // Make sure this is a C2 compilation. C1 allocates space only for
6467     // trampoline stubs generated by Call LIR ops, and in any case it
6468     // makes sense for a C1 compilation task to proceed as quickly as
6469     // possible.
6470     CompileTask* task;
6471     if (StubRoutines::aarch64::complete()
6472         && Thread::current()->is_Compiler_thread()
6473         && (task = ciEnv::current()->task())
6474         && is_c2_compile(task->comp_level())) {
6475       address tpc = trampoline_call(zero_blocks);
6476       if (tpc == nullptr) {
6477         DEBUG_ONLY(reset_labels(around));
6478         return nullptr;
6479       }
6480     } else {
6481       far_call(zero_blocks);
6482     }
6483   }
6484   bind(around);
6485 
6486   // We have a few words left to do. zero_blocks has adjusted r10 and r11
6487   // for us.
6488   for (int i = zero_words_block_size >> 1; i > 1; i >>= 1) {
6489     Label l;
6490     tbz(cnt, exact_log2(i), l);
6491     for (int j = 0; j < i; j += 2) {
6492       stp(zr, zr, post(ptr, 2 * BytesPerWord));
6493     }
6494     bind(l);
6495   }
6496   {
6497     Label l;
6498     tbz(cnt, 0, l);
6499     str(zr, Address(ptr));
6500     bind(l);
6501   }
6502 
6503   BLOCK_COMMENT("} zero_words");
6504   return pc();
6505 }
6506 
6507 // base:         Address of a buffer to be zeroed, 8 bytes aligned.
6508 // cnt:          Immediate count in HeapWords.
6509 //
6510 // r10, r11, rscratch1, and rscratch2 are clobbered.
6511 address MacroAssembler::zero_words(Register base, uint64_t cnt)
6512 {
6513   assert(wordSize <= BlockZeroingLowLimit,
6514             "increase BlockZeroingLowLimit");
6515   address result = nullptr;
6516   if (cnt <= (uint64_t)BlockZeroingLowLimit / BytesPerWord) {
6517 #ifndef PRODUCT
6518     {
6519       char buf[64];
6520       os::snprintf_checked(buf, sizeof buf, "zero_words (count = %" PRIu64 ") {", cnt);
6521       BLOCK_COMMENT(buf);
6522     }
6523 #endif
6524     if (cnt >= 16) {
6525       uint64_t loops = cnt/16;
6526       if (loops > 1) {
6527         mov(rscratch2, loops - 1);
6528       }
6529       {
6530         Label loop;
6531         bind(loop);
6532         for (int i = 0; i < 16; i += 2) {
6533           stp(zr, zr, Address(base, i * BytesPerWord));
6534         }
6535         add(base, base, 16 * BytesPerWord);
6536         if (loops > 1) {
6537           subs(rscratch2, rscratch2, 1);
6538           br(GE, loop);
6539         }
6540       }
6541     }
6542     cnt %= 16;
6543     int i = cnt & 1;  // store any odd word to start
6544     if (i) str(zr, Address(base));
6545     for (; i < (int)cnt; i += 2) {
6546       stp(zr, zr, Address(base, i * wordSize));
6547     }
6548     BLOCK_COMMENT("} zero_words");
6549     result = pc();
6550   } else {
6551     mov(r10, base); mov(r11, cnt);
6552     result = zero_words(r10, r11);
6553   }
6554   return result;
6555 }
6556 
6557 // Zero blocks of memory by using DC ZVA.
6558 //
6559 // Aligns the base address first sufficiently for DC ZVA, then uses
6560 // DC ZVA repeatedly for every full block.  cnt is the size to be
6561 // zeroed in HeapWords.  Returns the count of words left to be zeroed
6562 // in cnt.
6563 //
6564 // NOTE: This is intended to be used in the zero_blocks() stub.  If
6565 // you want to use it elsewhere, note that cnt must be >= 2*zva_length.
6566 void MacroAssembler::zero_dcache_blocks(Register base, Register cnt) {
6567   Register tmp = rscratch1;
6568   Register tmp2 = rscratch2;
6569   int zva_length = VM_Version::zva_length();
6570   Label initial_table_end, loop_zva;
6571   Label fini;
6572 
6573   // Base must be 16 byte aligned. If not just return and let caller handle it
6574   tst(base, 0x0f);
6575   br(Assembler::NE, fini);
6576   // Align base with ZVA length.
6577   neg(tmp, base);
6578   andr(tmp, tmp, zva_length - 1);
6579 
6580   // tmp: the number of bytes to be filled to align the base with ZVA length.
6581   add(base, base, tmp);
6582   sub(cnt, cnt, tmp, Assembler::ASR, 3);
6583   adr(tmp2, initial_table_end);
6584   sub(tmp2, tmp2, tmp, Assembler::LSR, 2);
6585   br(tmp2);
6586 
6587   for (int i = -zva_length + 16; i < 0; i += 16)
6588     stp(zr, zr, Address(base, i));
6589   bind(initial_table_end);
6590 
6591   sub(cnt, cnt, zva_length >> 3);
6592   bind(loop_zva);
6593   dc(Assembler::ZVA, base);
6594   subs(cnt, cnt, zva_length >> 3);
6595   add(base, base, zva_length);
6596   br(Assembler::GE, loop_zva);
6597   add(cnt, cnt, zva_length >> 3); // count not zeroed by DC ZVA
6598   bind(fini);
6599 }
6600 
6601 // base:   Address of a buffer to be filled, 8 bytes aligned.
6602 // cnt:    Count in 8-byte unit.
6603 // value:  Value to be filled with.
6604 // base will point to the end of the buffer after filling.
6605 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
6606 {
6607 //  Algorithm:
6608 //
6609 //    if (cnt == 0) {
6610 //      return;
6611 //    }
6612 //    if ((p & 8) != 0) {
6613 //      *p++ = v;
6614 //    }
6615 //
6616 //    scratch1 = cnt & 14;
6617 //    cnt -= scratch1;
6618 //    p += scratch1;
6619 //    switch (scratch1 / 2) {
6620 //      do {
6621 //        cnt -= 16;
6622 //          p[-16] = v;
6623 //          p[-15] = v;
6624 //        case 7:
6625 //          p[-14] = v;
6626 //          p[-13] = v;
6627 //        case 6:
6628 //          p[-12] = v;
6629 //          p[-11] = v;
6630 //          // ...
6631 //        case 1:
6632 //          p[-2] = v;
6633 //          p[-1] = v;
6634 //        case 0:
6635 //          p += 16;
6636 //      } while (cnt);
6637 //    }
6638 //    if ((cnt & 1) == 1) {
6639 //      *p++ = v;
6640 //    }
6641 
6642   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
6643 
6644   Label fini, skip, entry, loop;
6645   const int unroll = 8; // Number of stp instructions we'll unroll
6646 
6647   cbz(cnt, fini);
6648   tbz(base, 3, skip);
6649   str(value, Address(post(base, 8)));
6650   sub(cnt, cnt, 1);
6651   bind(skip);
6652 
6653   andr(rscratch1, cnt, (unroll-1) * 2);
6654   sub(cnt, cnt, rscratch1);
6655   add(base, base, rscratch1, Assembler::LSL, 3);
6656   adr(rscratch2, entry);
6657   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
6658   br(rscratch2);
6659 
6660   bind(loop);
6661   add(base, base, unroll * 16);
6662   for (int i = -unroll; i < 0; i++)
6663     stp(value, value, Address(base, i * 16));
6664   bind(entry);
6665   subs(cnt, cnt, unroll * 2);
6666   br(Assembler::GE, loop);
6667 
6668   tbz(cnt, 0, fini);
6669   str(value, Address(post(base, 8)));
6670   bind(fini);
6671 }
6672 
6673 // Intrinsic for
6674 //
6675 // - sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6676 //   Encodes char[] to byte[] in ISO-8859-1
6677 //
6678 // - java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6679 //   Encodes byte[] (containing UTF-16) to byte[] in ISO-8859-1
6680 //
6681 // - java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6682 //   Encodes char[] to byte[] in ASCII
6683 //
6684 // This version always returns the number of characters copied, and does not
6685 // clobber the 'len' register. A successful copy will complete with the post-
6686 // condition: 'res' == 'len', while an unsuccessful copy will exit with the
6687 // post-condition: 0 <= 'res' < 'len'.
6688 //
6689 // NOTE: Attempts to use 'ld2' (and 'umaxv' in the ISO part) has proven to
6690 //       degrade performance (on Ampere Altra - Neoverse N1), to an extent
6691 //       beyond the acceptable, even though the footprint would be smaller.
6692 //       Using 'umaxv' in the ASCII-case comes with a small penalty but does
6693 //       avoid additional bloat.
6694 //
6695 // Clobbers: src, dst, res, rscratch1, rscratch2, rflags
6696 void MacroAssembler::encode_iso_array(Register src, Register dst,
6697                                       Register len, Register res, bool ascii,
6698                                       FloatRegister vtmp0, FloatRegister vtmp1,
6699                                       FloatRegister vtmp2, FloatRegister vtmp3,
6700                                       FloatRegister vtmp4, FloatRegister vtmp5)
6701 {
6702   Register cnt = res;
6703   Register max = rscratch1;
6704   Register chk = rscratch2;
6705 
6706   prfm(Address(src), PLDL1STRM);
6707   movw(cnt, len);
6708 
6709 #define ASCII(insn) do { if (ascii) { insn; } } while (0)
6710 
6711   Label LOOP_32, DONE_32, FAIL_32;
6712 
6713   BIND(LOOP_32);
6714   {
6715     cmpw(cnt, 32);
6716     br(LT, DONE_32);
6717     ld1(vtmp0, vtmp1, vtmp2, vtmp3, T8H, Address(post(src, 64)));
6718     // Extract lower bytes.
6719     FloatRegister vlo0 = vtmp4;
6720     FloatRegister vlo1 = vtmp5;
6721     uzp1(vlo0, T16B, vtmp0, vtmp1);
6722     uzp1(vlo1, T16B, vtmp2, vtmp3);
6723     // Merge bits...
6724     orr(vtmp0, T16B, vtmp0, vtmp1);
6725     orr(vtmp2, T16B, vtmp2, vtmp3);
6726     // Extract merged upper bytes.
6727     FloatRegister vhix = vtmp0;
6728     uzp2(vhix, T16B, vtmp0, vtmp2);
6729     // ISO-check on hi-parts (all zero).
6730     //                          ASCII-check on lo-parts (no sign).
6731     FloatRegister vlox = vtmp1; // Merge lower bytes.
6732                                 ASCII(orr(vlox, T16B, vlo0, vlo1));
6733     umov(chk, vhix, D, 1);      ASCII(cm(LT, vlox, T16B, vlox));
6734     fmovd(max, vhix);           ASCII(umaxv(vlox, T16B, vlox));
6735     orr(chk, chk, max);         ASCII(umov(max, vlox, B, 0));
6736                                 ASCII(orr(chk, chk, max));
6737     cbnz(chk, FAIL_32);
6738     subw(cnt, cnt, 32);
6739     st1(vlo0, vlo1, T16B, Address(post(dst, 32)));
6740     b(LOOP_32);
6741   }
6742   BIND(FAIL_32);
6743   sub(src, src, 64);
6744   BIND(DONE_32);
6745 
6746   Label LOOP_8, SKIP_8;
6747 
6748   BIND(LOOP_8);
6749   {
6750     cmpw(cnt, 8);
6751     br(LT, SKIP_8);
6752     FloatRegister vhi = vtmp0;
6753     FloatRegister vlo = vtmp1;
6754     ld1(vtmp3, T8H, src);
6755     uzp1(vlo, T16B, vtmp3, vtmp3);
6756     uzp2(vhi, T16B, vtmp3, vtmp3);
6757     // ISO-check on hi-parts (all zero).
6758     //                          ASCII-check on lo-parts (no sign).
6759                                 ASCII(cm(LT, vtmp2, T16B, vlo));
6760     fmovd(chk, vhi);            ASCII(umaxv(vtmp2, T16B, vtmp2));
6761                                 ASCII(umov(max, vtmp2, B, 0));
6762                                 ASCII(orr(chk, chk, max));
6763     cbnz(chk, SKIP_8);
6764 
6765     strd(vlo, Address(post(dst, 8)));
6766     subw(cnt, cnt, 8);
6767     add(src, src, 16);
6768     b(LOOP_8);
6769   }
6770   BIND(SKIP_8);
6771 
6772 #undef ASCII
6773 
6774   Label LOOP, DONE;
6775 
6776   cbz(cnt, DONE);
6777   BIND(LOOP);
6778   {
6779     Register chr = rscratch1;
6780     ldrh(chr, Address(post(src, 2)));
6781     tst(chr, ascii ? 0xff80 : 0xff00);
6782     br(NE, DONE);
6783     strb(chr, Address(post(dst, 1)));
6784     subs(cnt, cnt, 1);
6785     br(GT, LOOP);
6786   }
6787   BIND(DONE);
6788   // Return index where we stopped.
6789   subw(res, len, cnt);
6790 }
6791 
6792 // Inflate byte[] array to char[].
6793 // Clobbers: src, dst, len, rflags, rscratch1, v0-v6
6794 address MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
6795                                            FloatRegister vtmp1, FloatRegister vtmp2,
6796                                            FloatRegister vtmp3, Register tmp4) {
6797   Label big, done, after_init, to_stub;
6798 
6799   assert_different_registers(src, dst, len, tmp4, rscratch1);
6800 
6801   fmovd(vtmp1, 0.0);
6802   lsrw(tmp4, len, 3);
6803   bind(after_init);
6804   cbnzw(tmp4, big);
6805   // Short string: less than 8 bytes.
6806   {
6807     Label loop, tiny;
6808 
6809     cmpw(len, 4);
6810     br(LT, tiny);
6811     // Use SIMD to do 4 bytes.
6812     ldrs(vtmp2, post(src, 4));
6813     zip1(vtmp3, T8B, vtmp2, vtmp1);
6814     subw(len, len, 4);
6815     strd(vtmp3, post(dst, 8));
6816 
6817     cbzw(len, done);
6818 
6819     // Do the remaining bytes by steam.
6820     bind(loop);
6821     ldrb(tmp4, post(src, 1));
6822     strh(tmp4, post(dst, 2));
6823     subw(len, len, 1);
6824 
6825     bind(tiny);
6826     cbnz(len, loop);
6827 
6828     b(done);
6829   }
6830 
6831   if (SoftwarePrefetchHintDistance >= 0) {
6832     bind(to_stub);
6833       RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_byte_array_inflate());
6834       assert(stub.target() != nullptr, "large_byte_array_inflate stub has not been generated");
6835       address tpc = trampoline_call(stub);
6836       if (tpc == nullptr) {
6837         DEBUG_ONLY(reset_labels(big, done));
6838         postcond(pc() == badAddress);
6839         return nullptr;
6840       }
6841       b(after_init);
6842   }
6843 
6844   // Unpack the bytes 8 at a time.
6845   bind(big);
6846   {
6847     Label loop, around, loop_last, loop_start;
6848 
6849     if (SoftwarePrefetchHintDistance >= 0) {
6850       const int large_loop_threshold = (64 + 16)/8;
6851       ldrd(vtmp2, post(src, 8));
6852       andw(len, len, 7);
6853       cmp(tmp4, (u1)large_loop_threshold);
6854       br(GE, to_stub);
6855       b(loop_start);
6856 
6857       bind(loop);
6858       ldrd(vtmp2, post(src, 8));
6859       bind(loop_start);
6860       subs(tmp4, tmp4, 1);
6861       br(EQ, loop_last);
6862       zip1(vtmp2, T16B, vtmp2, vtmp1);
6863       ldrd(vtmp3, post(src, 8));
6864       st1(vtmp2, T8H, post(dst, 16));
6865       subs(tmp4, tmp4, 1);
6866       zip1(vtmp3, T16B, vtmp3, vtmp1);
6867       st1(vtmp3, T8H, post(dst, 16));
6868       br(NE, loop);
6869       b(around);
6870       bind(loop_last);
6871       zip1(vtmp2, T16B, vtmp2, vtmp1);
6872       st1(vtmp2, T8H, post(dst, 16));
6873       bind(around);
6874       cbz(len, done);
6875     } else {
6876       andw(len, len, 7);
6877       bind(loop);
6878       ldrd(vtmp2, post(src, 8));
6879       sub(tmp4, tmp4, 1);
6880       zip1(vtmp3, T16B, vtmp2, vtmp1);
6881       st1(vtmp3, T8H, post(dst, 16));
6882       cbnz(tmp4, loop);
6883     }
6884   }
6885 
6886   // Do the tail of up to 8 bytes.
6887   add(src, src, len);
6888   ldrd(vtmp3, Address(src, -8));
6889   add(dst, dst, len, ext::uxtw, 1);
6890   zip1(vtmp3, T16B, vtmp3, vtmp1);
6891   strq(vtmp3, Address(dst, -16));
6892 
6893   bind(done);
6894   postcond(pc() != badAddress);
6895   return pc();
6896 }
6897 
6898 // Compress char[] array to byte[].
6899 // Intrinsic for java.lang.StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
6900 // Return the array length if every element in array can be encoded,
6901 // otherwise, the index of first non-latin1 (> 0xff) character.
6902 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
6903                                          Register res,
6904                                          FloatRegister tmp0, FloatRegister tmp1,
6905                                          FloatRegister tmp2, FloatRegister tmp3,
6906                                          FloatRegister tmp4, FloatRegister tmp5) {
6907   encode_iso_array(src, dst, len, res, false, tmp0, tmp1, tmp2, tmp3, tmp4, tmp5);
6908 }
6909 
6910 // java.math.round(double a)
6911 // Returns the closest long to the argument, with ties rounding to
6912 // positive infinity.  This requires some fiddling for corner
6913 // cases. We take care to avoid double rounding in e.g. (jlong)(a + 0.5).
6914 void MacroAssembler::java_round_double(Register dst, FloatRegister src,
6915                                        FloatRegister ftmp) {
6916   Label DONE;
6917   BLOCK_COMMENT("java_round_double: { ");
6918   fmovd(rscratch1, src);
6919   // Use RoundToNearestTiesAway unless src small and -ve.
6920   fcvtasd(dst, src);
6921   // Test if src >= 0 || abs(src) >= 0x1.0p52
6922   eor(rscratch1, rscratch1, UCONST64(1) << 63); // flip sign bit
6923   mov(rscratch2, julong_cast(0x1.0p52));
6924   cmp(rscratch1, rscratch2);
6925   br(HS, DONE); {
6926     // src < 0 && abs(src) < 0x1.0p52
6927     // src may have a fractional part, so add 0.5
6928     fmovd(ftmp, 0.5);
6929     faddd(ftmp, src, ftmp);
6930     // Convert double to jlong, use RoundTowardsNegative
6931     fcvtmsd(dst, ftmp);
6932   }
6933   bind(DONE);
6934   BLOCK_COMMENT("} java_round_double");
6935 }
6936 
6937 void MacroAssembler::java_round_float(Register dst, FloatRegister src,
6938                                       FloatRegister ftmp) {
6939   Label DONE;
6940   BLOCK_COMMENT("java_round_float: { ");
6941   fmovs(rscratch1, src);
6942   // Use RoundToNearestTiesAway unless src small and -ve.
6943   fcvtassw(dst, src);
6944   // Test if src >= 0 || abs(src) >= 0x1.0p23
6945   eor(rscratch1, rscratch1, 0x80000000); // flip sign bit
6946   mov(rscratch2, jint_cast(0x1.0p23f));
6947   cmp(rscratch1, rscratch2);
6948   br(HS, DONE); {
6949     // src < 0 && |src| < 0x1.0p23
6950     // src may have a fractional part, so add 0.5
6951     fmovs(ftmp, 0.5f);
6952     fadds(ftmp, src, ftmp);
6953     // Convert float to jint, use RoundTowardsNegative
6954     fcvtmssw(dst, ftmp);
6955   }
6956   bind(DONE);
6957   BLOCK_COMMENT("} java_round_float");
6958 }
6959 
6960 // get_thread() can be called anywhere inside generated code so we
6961 // need to save whatever non-callee save context might get clobbered
6962 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
6963 // the call setup code.
6964 //
6965 // On Linux and Windows, aarch64_get_thread_helper() is implemented in
6966 // assembly and clobbers only r0, r1, and flags.
6967 // On other systems, the helper is a usual C function.
6968 //
6969 void MacroAssembler::get_thread(Register dst) {
6970   RegSet saved_regs =
6971     BSD_ONLY(RegSet::range(r0, r17) + lr - dst)
6972     NOT_BSD (RegSet::range(r0, r1)  + lr - dst);
6973 
6974   protect_return_address();
6975   push(saved_regs, sp);
6976 
6977   mov(lr, ExternalAddress(CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper)));
6978   blr(lr);
6979   if (dst != c_rarg0) {
6980     mov(dst, c_rarg0);
6981   }
6982 
6983   pop(saved_regs, sp);
6984   authenticate_return_address();
6985 }
6986 
6987 #ifdef COMPILER2
6988 // C2 compiled method's prolog code
6989 // Moved here from aarch64.ad to support Valhalla code below
6990 void MacroAssembler::verified_entry(Compile* C, int sp_inc) {
6991   if (C->clinit_barrier_on_entry()) {
6992     assert(!C->method()->holder()->is_not_initialized(), "initialization should have been started");
6993 
6994     Label L_skip_barrier;
6995 
6996     mov_metadata(rscratch2, C->method()->holder()->constant_encoding());
6997     clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
6998     far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
6999     bind(L_skip_barrier);
7000   }
7001 
7002   if (C->max_vector_size() > 0) {
7003     reinitialize_ptrue();
7004   }
7005 
7006   int bangsize = C->output()->bang_size_in_bytes();
7007   if (C->output()->need_stack_bang(bangsize))
7008     generate_stack_overflow_check(bangsize);
7009 
7010   // n.b. frame size includes space for return pc and rfp
7011   const long framesize = C->output()->frame_size_in_bytes();
7012   build_frame(framesize DEBUG_ONLY(COMMA sp_inc != 0));
7013 
7014   if (C->needs_stack_repair()) {
7015     save_stack_increment(sp_inc, framesize);
7016   }
7017 
7018   if (VerifyStackAtCalls) {
7019     Unimplemented();
7020   }
7021 }
7022 #endif // COMPILER2
7023 
7024 int MacroAssembler::store_inline_type_fields_to_buf(ciInlineKlass* vk, bool from_interpreter) {
7025   assert(InlineTypeReturnedAsFields, "Inline types should never be returned as fields");
7026   // An inline type might be returned. If fields are in registers we
7027   // need to allocate an inline type instance and initialize it with
7028   // the value of the fields.
7029   Label skip;
7030   // We only need a new buffered inline type if a new one is not returned
7031   tbz(r0, 0, skip);
7032   int call_offset = -1;
7033 
7034   // Be careful not to clobber r1-7 which hold returned fields
7035   // Also do not use callee-saved registers as these may be live in the interpreter
7036   Register tmp1 = r13, tmp2 = r14, klass = r15, r0_preserved = r12;
7037 
7038   // The following code is similar to the instance allocation code in TemplateTable::_new
7039   //  but has some slight differences,
7040   // e.g. object size is always not zero, sometimes it's constant; storing klass ptr after
7041   // allocating is not necessary if vk != nullptr, etc.
7042   Label slow_case;
7043   // 1. Try to allocate a new buffered inline instance either from TLAB or eden space
7044   mov(r0_preserved, r0); // save r0 for slow_case since *_allocate may corrupt it when allocation failed
7045 
7046   if (vk != nullptr) {
7047     // Called from C1, where the return type is statically known.
7048     movptr(klass, (intptr_t)vk->get_InlineKlass());
7049     jint lh = vk->layout_helper();
7050     assert(lh != Klass::_lh_neutral_value, "inline class in return type must have been resolved");
7051     if (UseTLAB && !Klass::layout_helper_needs_slow_path(lh)) {
7052       tlab_allocate(r0, noreg, lh, tmp1, tmp2, slow_case);
7053     } else {
7054       b(slow_case);
7055     }
7056   } else {
7057     // Call from interpreter. R0 contains ((the InlineKlass* of the return type) | 0x01)
7058     andr(klass, r0, -2);
7059     if (UseTLAB) {
7060       ldrw(tmp2, Address(klass, Klass::layout_helper_offset()));
7061       tst(tmp2, Klass::_lh_instance_slow_path_bit);
7062       br(Assembler::NE, slow_case);
7063       tlab_allocate(r0, tmp2, 0, tmp1, tmp2, slow_case);
7064     } else {
7065       b(slow_case);
7066     }
7067   }
7068   if (UseTLAB) {
7069     // 2. Initialize buffered inline instance header
7070     Register buffer_obj = r0;
7071     if (UseCompactObjectHeaders) {
7072       ldr(rscratch1, Address(klass, Klass::prototype_header_offset()));
7073       str(rscratch1, Address(buffer_obj, oopDesc::mark_offset_in_bytes()));
7074     } else {
7075       mov(rscratch1, (intptr_t)markWord::inline_type_prototype().value());
7076       str(rscratch1, Address(buffer_obj, oopDesc::mark_offset_in_bytes()));
7077       store_klass_gap(buffer_obj, zr);
7078       if (vk == nullptr) {
7079         // store_klass corrupts klass, so save it for later use (interpreter case only).
7080         mov(tmp1, klass);
7081       }
7082       store_klass(buffer_obj, klass);
7083       klass = tmp1;
7084     }
7085     // 3. Initialize its fields with an inline class specific handler
7086     if (vk != nullptr) {
7087       far_call(RuntimeAddress(vk->pack_handler())); // no need for call info as this will not safepoint.
7088     } else {
7089       ldr(tmp1, Address(klass, InlineKlass::adr_members_offset()));
7090       ldr(tmp1, Address(tmp1, InlineKlass::pack_handler_offset()));
7091       blr(tmp1);
7092     }
7093 
7094     membar(Assembler::StoreStore);
7095     b(skip);
7096   } else {
7097     // Must have already branched to slow_case above.
7098     DEBUG_ONLY(should_not_reach_here());
7099   }
7100   bind(slow_case);
7101   // We failed to allocate a new inline type, fall back to a runtime
7102   // call. Some oop field may be live in some registers but we can't
7103   // tell. That runtime call will take care of preserving them
7104   // across a GC if there's one.
7105   mov(r0, r0_preserved);
7106 
7107   if (from_interpreter) {
7108     super_call_VM_leaf(StubRoutines::store_inline_type_fields_to_buf());
7109   } else {
7110     far_call(RuntimeAddress(StubRoutines::store_inline_type_fields_to_buf()));
7111     call_offset = offset();
7112   }
7113   membar(Assembler::StoreStore);
7114 
7115   bind(skip);
7116   return call_offset;
7117 }
7118 
7119 // Move a value between registers/stack slots and update the reg_state
7120 bool MacroAssembler::move_helper(VMReg from, VMReg to, BasicType bt, RegState reg_state[]) {
7121   assert(from->is_valid() && to->is_valid(), "source and destination must be valid");
7122   if (reg_state[to->value()] == reg_written) {
7123     return true; // Already written
7124   }
7125 
7126   if (from != to && bt != T_VOID) {
7127     if (reg_state[to->value()] == reg_readonly) {
7128       return false; // Not yet writable
7129     }
7130     if (from->is_reg()) {
7131       if (to->is_reg()) {
7132         if (from->is_Register() && to->is_Register()) {
7133           mov(to->as_Register(), from->as_Register());
7134         } else if (from->is_FloatRegister() && to->is_FloatRegister()) {
7135           fmovd(to->as_FloatRegister(), from->as_FloatRegister());
7136         } else {
7137           ShouldNotReachHere();
7138         }
7139       } else {
7140         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size;
7141         Address to_addr = Address(sp, st_off);
7142         if (from->is_FloatRegister()) {
7143           if (bt == T_DOUBLE) {
7144              strd(from->as_FloatRegister(), to_addr);
7145           } else {
7146              assert(bt == T_FLOAT, "must be float");
7147              strs(from->as_FloatRegister(), to_addr);
7148           }
7149         } else {
7150           str(from->as_Register(), to_addr);
7151         }
7152       }
7153     } else {
7154       Address from_addr = Address(sp, from->reg2stack() * VMRegImpl::stack_slot_size);
7155       if (to->is_reg()) {
7156         if (to->is_FloatRegister()) {
7157           if (bt == T_DOUBLE) {
7158             ldrd(to->as_FloatRegister(), from_addr);
7159           } else {
7160             assert(bt == T_FLOAT, "must be float");
7161             ldrs(to->as_FloatRegister(), from_addr);
7162           }
7163         } else {
7164           ldr(to->as_Register(), from_addr);
7165         }
7166       } else {
7167         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size;
7168         ldr(rscratch1, from_addr);
7169         str(rscratch1, Address(sp, st_off));
7170       }
7171     }
7172   }
7173 
7174   // Update register states
7175   reg_state[from->value()] = reg_writable;
7176   reg_state[to->value()] = reg_written;
7177   return true;
7178 }
7179 
7180 // Calculate the extra stack space required for packing or unpacking inline
7181 // args and adjust the stack pointer
7182 int MacroAssembler::extend_stack_for_inline_args(int args_on_stack) {
7183   int sp_inc = args_on_stack * VMRegImpl::stack_slot_size;
7184   sp_inc = align_up(sp_inc, StackAlignmentInBytes);
7185   assert(sp_inc > 0, "sanity");
7186 
7187   // Save a copy of the FP and LR here for deoptimization patching and frame walking
7188   stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
7189 
7190   // Adjust the stack pointer. This will be repaired on return by MacroAssembler::remove_frame
7191   if (sp_inc < (1 << 9)) {
7192     sub(sp, sp, sp_inc);   // Fits in an immediate
7193   } else {
7194     mov(rscratch1, sp_inc);
7195     sub(sp, sp, rscratch1);
7196   }
7197 
7198   return sp_inc + 2 * wordSize;  // Account for the FP/LR space
7199 }
7200 
7201 // Read all fields from an inline type oop and store the values in registers/stack slots
7202 bool MacroAssembler::unpack_inline_helper(const GrowableArray<SigEntry>* sig, int& sig_index,
7203                                           VMReg from, int& from_index, VMRegPair* to, int to_count, int& to_index,
7204                                           RegState reg_state[]) {
7205   assert(sig->at(sig_index)._bt == T_VOID, "should be at end delimiter");
7206   assert(from->is_valid(), "source must be valid");
7207   bool progress = false;
7208 #ifdef ASSERT
7209   const int start_offset = offset();
7210 #endif
7211 
7212   Label L_null, L_notNull;
7213   // Don't use r14 as tmp because it's used for spilling (see MacroAssembler::spill_reg_for)
7214   Register tmp1 = r10;
7215   Register tmp2 = r11;
7216 
7217 #ifdef ASSERT
7218   RegSet clobbered_gp_regs = MacroAssembler::call_clobbered_gp_registers();
7219   assert(clobbered_gp_regs.contains(tmp1), "tmp1 must be saved explicitly if it's not a clobber");
7220   assert(clobbered_gp_regs.contains(tmp2), "tmp2 must be saved explicitly if it's not a clobber");
7221   assert(clobbered_gp_regs.contains(r14), "r14 must be saved explicitly if it's not a clobber");
7222 #endif
7223 
7224   Register fromReg = noreg;
7225   ScalarizedInlineArgsStream stream(sig, sig_index, to, to_count, to_index, true);
7226   bool done = true;
7227   bool mark_done = true;
7228   VMReg toReg;
7229   BasicType bt;
7230   // Check if argument requires a null check
7231   bool null_check = false;
7232   VMReg nullCheckReg;
7233   while (stream.next(nullCheckReg, bt)) {
7234     if (sig->at(stream.sig_index())._offset == -1) {
7235       null_check = true;
7236       break;
7237     }
7238   }
7239   stream.reset(sig_index, to_index);
7240   while (stream.next(toReg, bt)) {
7241     assert(toReg->is_valid(), "destination must be valid");
7242     int idx = (int)toReg->value();
7243     if (reg_state[idx] == reg_readonly) {
7244       if (idx != from->value()) {
7245         mark_done = false;
7246       }
7247       done = false;
7248       continue;
7249     } else if (reg_state[idx] == reg_written) {
7250       continue;
7251     }
7252     assert(reg_state[idx] == reg_writable, "must be writable");
7253     reg_state[idx] = reg_written;
7254     progress = true;
7255 
7256     if (fromReg == noreg) {
7257       if (from->is_reg()) {
7258         fromReg = from->as_Register();
7259       } else {
7260         int st_off = from->reg2stack() * VMRegImpl::stack_slot_size;
7261         ldr(tmp1, Address(sp, st_off));
7262         fromReg = tmp1;
7263       }
7264       if (null_check) {
7265         // Nullable inline type argument, emit null check
7266         cbz(fromReg, L_null);
7267       }
7268     }
7269     int off = sig->at(stream.sig_index())._offset;
7270     if (off == -1) {
7271       assert(null_check, "Missing null check at");
7272       if (toReg->is_stack()) {
7273         int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
7274         mov(tmp2, 1);
7275         str(tmp2, Address(sp, st_off));
7276       } else {
7277         mov(toReg->as_Register(), 1);
7278       }
7279       continue;
7280     }
7281     if (sig->at(stream.sig_index())._vt_oop) {
7282       if (toReg->is_stack()) {
7283         int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
7284         str(fromReg, Address(sp, st_off));
7285       } else {
7286         mov(toReg->as_Register(), fromReg);
7287       }
7288       continue;
7289     }
7290     assert(off > 0, "offset in object should be positive");
7291     Address fromAddr = Address(fromReg, off);
7292     if (!toReg->is_FloatRegister()) {
7293       Register dst = toReg->is_stack() ? tmp2 : toReg->as_Register();
7294       if (is_reference_type(bt)) {
7295         load_heap_oop(dst, fromAddr, rscratch1, rscratch2);
7296       } else {
7297         bool is_signed = (bt != T_CHAR) && (bt != T_BOOLEAN);
7298         load_sized_value(dst, fromAddr, type2aelembytes(bt), is_signed);
7299       }
7300       if (toReg->is_stack()) {
7301         int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
7302         str(dst, Address(sp, st_off));
7303       }
7304     } else if (bt == T_DOUBLE) {
7305       ldrd(toReg->as_FloatRegister(), fromAddr);
7306     } else {
7307       assert(bt == T_FLOAT, "must be float");
7308       ldrs(toReg->as_FloatRegister(), fromAddr);
7309     }
7310   }
7311   if (progress && null_check) {
7312     if (done) {
7313       b(L_notNull);
7314       bind(L_null);
7315       // Set null marker to zero to signal that the argument is null.
7316       // Also set all fields to zero since the runtime requires a canonical
7317       // representation of a flat null.
7318       stream.reset(sig_index, to_index);
7319       while (stream.next(toReg, bt)) {
7320         if (toReg->is_stack()) {
7321           int st_off = toReg->reg2stack() * VMRegImpl::stack_slot_size;
7322           str(zr, Address(sp, st_off));
7323         } else if (toReg->is_FloatRegister()) {
7324           mov(toReg->as_FloatRegister(), T2S, 0);
7325         } else {
7326           mov(toReg->as_Register(), zr);
7327         }
7328       }
7329       bind(L_notNull);
7330     } else {
7331       bind(L_null);
7332     }
7333   }
7334 
7335   sig_index = stream.sig_index();
7336   to_index = stream.regs_index();
7337 
7338   if (mark_done && reg_state[from->value()] != reg_written) {
7339     // This is okay because no one else will write to that slot
7340     reg_state[from->value()] = reg_writable;
7341   }
7342   from_index--;
7343   assert(progress || (start_offset == offset()), "should not emit code");
7344   return done;
7345 }
7346 
7347 // Pack fields back into an inline type oop
7348 bool MacroAssembler::pack_inline_helper(const GrowableArray<SigEntry>* sig, int& sig_index, int vtarg_index,
7349                                         VMRegPair* from, int from_count, int& from_index, VMReg to,
7350                                         RegState reg_state[], Register val_array) {
7351   assert(sig->at(sig_index)._bt == T_METADATA, "should be at delimiter");
7352   assert(to->is_valid(), "destination must be valid");
7353 
7354   if (reg_state[to->value()] == reg_written) {
7355     skip_unpacked_fields(sig, sig_index, from, from_count, from_index);
7356     return true; // Already written
7357   }
7358 
7359   // The GC barrier expanded by store_heap_oop below may call into the
7360   // runtime so use callee-saved registers for any values that need to be
7361   // preserved. The GC barrier assembler should take care of saving the
7362   // Java argument registers.
7363   // Be careful with r14 because it's used for spilling (see MacroAssembler::spill_reg_for).
7364   Register val_obj_tmp = r21;
7365   Register from_reg_tmp = r22;
7366   Register tmp1 = r14;
7367   Register tmp2 = r13;
7368   Register tmp3 = r12;
7369   Register val_obj = to->is_stack() ? val_obj_tmp : to->as_Register();
7370 
7371   assert_different_registers(val_obj_tmp, from_reg_tmp, tmp1, tmp2, tmp3, val_array);
7372 
7373   if (reg_state[to->value()] == reg_readonly) {
7374     if (!is_reg_in_unpacked_fields(sig, sig_index, to, from, from_count, from_index)) {
7375       skip_unpacked_fields(sig, sig_index, from, from_count, from_index);
7376       return false; // Not yet writable
7377     }
7378     val_obj = val_obj_tmp;
7379   }
7380 
7381   ScalarizedInlineArgsStream stream(sig, sig_index, from, from_count, from_index);
7382   VMReg fromReg;
7383   BasicType bt;
7384   Label L_null;
7385   while (stream.next(fromReg, bt)) {
7386     assert(fromReg->is_valid(), "source must be valid");
7387     reg_state[fromReg->value()] = reg_writable;
7388 
7389     int off = sig->at(stream.sig_index())._offset;
7390     if (off == -1) {
7391       // Nullable inline type argument, emit null check
7392       Label L_notNull;
7393       if (fromReg->is_stack()) {
7394         int ld_off = fromReg->reg2stack() * VMRegImpl::stack_slot_size;
7395         ldrb(tmp2, Address(sp, ld_off));
7396         cbnz(tmp2, L_notNull);
7397       } else {
7398         cbnz(fromReg->as_Register(), L_notNull);
7399       }
7400       mov(val_obj, 0);
7401       b(L_null);
7402       bind(L_notNull);
7403       continue;
7404     }
7405     if (sig->at(stream.sig_index())._vt_oop) {
7406       if (fromReg->is_stack()) {
7407         int ld_off = fromReg->reg2stack() * VMRegImpl::stack_slot_size;
7408         ldr(val_obj, Address(sp, ld_off));
7409       } else {
7410         mov(val_obj, fromReg->as_Register());
7411       }
7412       cbnz(val_obj, L_null);
7413       // get the buffer from the just allocated pool of buffers
7414       int index = arrayOopDesc::base_offset_in_bytes(T_OBJECT) + vtarg_index * type2aelembytes(T_OBJECT);
7415       load_heap_oop(val_obj, Address(val_array, index), rscratch1, rscratch2);
7416       continue;
7417     }
7418 
7419     assert(off > 0, "offset in object should be positive");
7420     size_t size_in_bytes = is_java_primitive(bt) ? type2aelembytes(bt) : wordSize;
7421 
7422     // Pack the scalarized field into the value object.
7423     Address dst(val_obj, off);
7424     if (!fromReg->is_FloatRegister()) {
7425       Register src;
7426       if (fromReg->is_stack()) {
7427         src = from_reg_tmp;
7428         int ld_off = fromReg->reg2stack() * VMRegImpl::stack_slot_size;
7429         load_sized_value(src, Address(sp, ld_off), size_in_bytes, /* is_signed */ false);
7430       } else {
7431         src = fromReg->as_Register();
7432       }
7433       assert_different_registers(dst.base(), src, tmp1, tmp2, tmp3, val_array);
7434       if (is_reference_type(bt)) {
7435         // store_heap_oop transitively calls oop_store_at which corrupts to.base(). We need to keep val_obj valid.
7436         mov(tmp3, val_obj);
7437         Address dst_with_tmp3(tmp3, off);
7438         store_heap_oop(dst_with_tmp3, src, tmp1, tmp2, tmp3, IN_HEAP | ACCESS_WRITE | IS_DEST_UNINITIALIZED);
7439       } else {
7440         store_sized_value(dst, src, size_in_bytes);
7441       }
7442     } else if (bt == T_DOUBLE) {
7443       strd(fromReg->as_FloatRegister(), dst);
7444     } else {
7445       assert(bt == T_FLOAT, "must be float");
7446       strs(fromReg->as_FloatRegister(), dst);
7447     }
7448   }
7449   bind(L_null);
7450   sig_index = stream.sig_index();
7451   from_index = stream.regs_index();
7452 
7453   assert(reg_state[to->value()] == reg_writable, "must have already been read");
7454   bool success = move_helper(val_obj->as_VMReg(), to, T_OBJECT, reg_state);
7455   assert(success, "to register must be writable");
7456   return true;
7457 }
7458 
7459 VMReg MacroAssembler::spill_reg_for(VMReg reg) {
7460   return (reg->is_FloatRegister()) ? v8->as_VMReg() : r14->as_VMReg();
7461 }
7462 
7463 void MacroAssembler::cache_wb(Address line) {
7464   assert(line.getMode() == Address::base_plus_offset, "mode should be base_plus_offset");
7465   assert(line.index() == noreg, "index should be noreg");
7466   assert(line.offset() == 0, "offset should be 0");
7467   // would like to assert this
7468   // assert(line._ext.shift == 0, "shift should be zero");
7469   if (VM_Version::supports_dcpop()) {
7470     // writeback using clear virtual address to point of persistence
7471     dc(Assembler::CVAP, line.base());
7472   } else {
7473     // no need to generate anything as Unsafe.writebackMemory should
7474     // never invoke this stub
7475   }
7476 }
7477 
7478 void MacroAssembler::cache_wbsync(bool is_pre) {
7479   // we only need a barrier post sync
7480   if (!is_pre) {
7481     membar(Assembler::AnyAny);
7482   }
7483 }
7484 
7485 void MacroAssembler::verify_sve_vector_length(Register tmp) {
7486   if (!UseSVE || VM_Version::get_max_supported_sve_vector_length() == FloatRegister::sve_vl_min) {
7487     return;
7488   }
7489   // Make sure that native code does not change SVE vector length.
7490   Label verify_ok;
7491   movw(tmp, zr);
7492   sve_inc(tmp, B);
7493   subsw(zr, tmp, VM_Version::get_initial_sve_vector_length());
7494   br(EQ, verify_ok);
7495   stop("Error: SVE vector length has changed since jvm startup");
7496   bind(verify_ok);
7497 }
7498 
7499 void MacroAssembler::verify_ptrue() {
7500   Label verify_ok;
7501   if (!UseSVE) {
7502     return;
7503   }
7504   sve_cntp(rscratch1, B, ptrue, ptrue); // get true elements count.
7505   sve_dec(rscratch1, B);
7506   cbz(rscratch1, verify_ok);
7507   stop("Error: the preserved predicate register (p7) elements are not all true");
7508   bind(verify_ok);
7509 }
7510 
7511 void MacroAssembler::safepoint_isb() {
7512   isb();
7513 #ifndef PRODUCT
7514   if (VerifyCrossModifyFence) {
7515     // Clear the thread state.
7516     strb(zr, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
7517   }
7518 #endif
7519 }
7520 
7521 #ifndef PRODUCT
7522 void MacroAssembler::verify_cross_modify_fence_not_required() {
7523   if (VerifyCrossModifyFence) {
7524     // Check if thread needs a cross modify fence.
7525     ldrb(rscratch1, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
7526     Label fence_not_required;
7527     cbz(rscratch1, fence_not_required);
7528     // If it does then fail.
7529     lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::verify_cross_modify_fence_failure)));
7530     mov(c_rarg0, rthread);
7531     blr(rscratch1);
7532     bind(fence_not_required);
7533   }
7534 }
7535 #endif
7536 
7537 void MacroAssembler::spin_wait() {
7538   block_comment("spin_wait {");
7539   for (int i = 0; i < VM_Version::spin_wait_desc().inst_count(); ++i) {
7540     switch (VM_Version::spin_wait_desc().inst()) {
7541       case SpinWait::NOP:
7542         nop();
7543         break;
7544       case SpinWait::ISB:
7545         isb();
7546         break;
7547       case SpinWait::YIELD:
7548         yield();
7549         break;
7550       case SpinWait::SB:
7551         assert(VM_Version::supports_sb(), "current CPU does not support SB instruction");
7552         sb();
7553         break;
7554       case SpinWait::WFET:
7555         spin_wait_wfet(VM_Version::spin_wait_desc().delay());
7556         break;
7557       default:
7558         ShouldNotReachHere();
7559     }
7560   }
7561   block_comment("}");
7562 }
7563 
7564 void MacroAssembler::spin_wait_wfet(int delay_ns) {
7565   // The sequence assumes CNTFRQ_EL0 is fixed to 1GHz. The assumption is valid
7566   // starting from Armv8.6, according to the "D12.1.2 The system counter" of the
7567   // Arm Architecture Reference Manual for A-profile architecture version M.a.a.
7568   // This is sufficient because FEAT_WFXT is introduced from Armv8.6.
7569   Register target = rscratch1;
7570   Register current = rscratch2;
7571   get_cntvctss_el0(current);
7572   add(target, current, delay_ns);
7573 
7574   Label L_wait_loop;
7575   bind(L_wait_loop);
7576 
7577   wfet(target);
7578   get_cntvctss_el0(current);
7579 
7580   cmp(current, target);
7581   br(LT, L_wait_loop);
7582 
7583   sb();
7584 }
7585 
7586 // Stack frame creation/removal
7587 
7588 void MacroAssembler::enter(bool strip_ret_addr) {
7589   if (strip_ret_addr) {
7590     // Addresses can only be signed once. If there are multiple nested frames being created
7591     // in the same function, then the return address needs stripping first.
7592     strip_return_address();
7593   }
7594   protect_return_address();
7595   stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
7596   mov(rfp, sp);
7597 }
7598 
7599 void MacroAssembler::leave() {
7600   mov(sp, rfp);
7601   ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
7602   authenticate_return_address();
7603 }
7604 
7605 // ROP Protection
7606 // Use the AArch64 PAC feature to add ROP protection for generated code. Use whenever creating/
7607 // destroying stack frames or whenever directly loading/storing the LR to memory.
7608 // If ROP protection is not set then these functions are no-ops.
7609 // For more details on PAC see pauth_aarch64.hpp.
7610 
7611 // Sign the LR. Use during construction of a stack frame, before storing the LR to memory.
7612 // Uses value zero as the modifier.
7613 //
7614 void MacroAssembler::protect_return_address() {
7615   if (VM_Version::use_rop_protection()) {
7616     check_return_address();
7617     paciaz();
7618   }
7619 }
7620 
7621 // Sign the return value in the given register. Use before updating the LR in the existing stack
7622 // frame for the current function.
7623 // Uses value zero as the modifier.
7624 //
7625 void MacroAssembler::protect_return_address(Register return_reg) {
7626   if (VM_Version::use_rop_protection()) {
7627     check_return_address(return_reg);
7628     paciza(return_reg);
7629   }
7630 }
7631 
7632 // Authenticate the LR. Use before function return, after restoring FP and loading LR from memory.
7633 // Uses value zero as the modifier.
7634 //
7635 void MacroAssembler::authenticate_return_address() {
7636   if (VM_Version::use_rop_protection()) {
7637     autiaz();
7638     check_return_address();
7639   }
7640 }
7641 
7642 // Authenticate the return value in the given register. Use before updating the LR in the existing
7643 // stack frame for the current function.
7644 // Uses value zero as the modifier.
7645 //
7646 void MacroAssembler::authenticate_return_address(Register return_reg) {
7647   if (VM_Version::use_rop_protection()) {
7648     autiza(return_reg);
7649     check_return_address(return_reg);
7650   }
7651 }
7652 
7653 // Strip any PAC data from LR without performing any authentication. Use with caution - only if
7654 // there is no guaranteed way of authenticating the LR.
7655 //
7656 void MacroAssembler::strip_return_address() {
7657   if (VM_Version::use_rop_protection()) {
7658     xpaclri();
7659   }
7660 }
7661 
7662 #ifndef PRODUCT
7663 // PAC failures can be difficult to debug. After an authentication failure, a segfault will only
7664 // occur when the pointer is used - ie when the program returns to the invalid LR. At this point
7665 // it is difficult to debug back to the callee function.
7666 // This function simply loads from the address in the given register.
7667 // Use directly after authentication to catch authentication failures.
7668 // Also use before signing to check that the pointer is valid and hasn't already been signed.
7669 //
7670 void MacroAssembler::check_return_address(Register return_reg) {
7671   if (VM_Version::use_rop_protection()) {
7672     ldr(zr, Address(return_reg));
7673   }
7674 }
7675 #endif
7676 
7677 // The java_calling_convention describes stack locations as ideal slots on
7678 // a frame with no abi restrictions. Since we must observe abi restrictions
7679 // (like the placement of the register window) the slots must be biased by
7680 // the following value.
7681 static int reg2offset_in(VMReg r) {
7682   // Account for saved rfp and lr
7683   // This should really be in_preserve_stack_slots
7684   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
7685 }
7686 
7687 static int reg2offset_out(VMReg r) {
7688   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
7689 }
7690 
7691 // On 64bit we will store integer like items to the stack as
7692 // 64bits items (AArch64 ABI) even though java would only store
7693 // 32bits for a parameter. On 32bit it will simply be 32bits
7694 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
7695 void MacroAssembler::move32_64(VMRegPair src, VMRegPair dst, Register tmp) {
7696   if (src.first()->is_stack()) {
7697     if (dst.first()->is_stack()) {
7698       // stack to stack
7699       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7700       str(tmp, Address(sp, reg2offset_out(dst.first())));
7701     } else {
7702       // stack to reg
7703       ldrsw(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
7704     }
7705   } else if (dst.first()->is_stack()) {
7706     // reg to stack
7707     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
7708   } else {
7709     if (dst.first() != src.first()) {
7710       sxtw(dst.first()->as_Register(), src.first()->as_Register());
7711     }
7712   }
7713 }
7714 
7715 // An oop arg. Must pass a handle not the oop itself
7716 void MacroAssembler::object_move(
7717                         OopMap* map,
7718                         int oop_handle_offset,
7719                         int framesize_in_slots,
7720                         VMRegPair src,
7721                         VMRegPair dst,
7722                         bool is_receiver,
7723                         int* receiver_offset) {
7724 
7725   // must pass a handle. First figure out the location we use as a handle
7726 
7727   Register rHandle = dst.first()->is_stack() ? rscratch2 : dst.first()->as_Register();
7728 
7729   // See if oop is null if it is we need no handle
7730 
7731   if (src.first()->is_stack()) {
7732 
7733     // Oop is already on the stack as an argument
7734     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
7735     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
7736     if (is_receiver) {
7737       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
7738     }
7739 
7740     ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
7741     lea(rHandle, Address(rfp, reg2offset_in(src.first())));
7742     // conditionally move a null
7743     cmp(rscratch1, zr);
7744     csel(rHandle, zr, rHandle, Assembler::EQ);
7745   } else {
7746 
7747     // Oop is in an a register we must store it to the space we reserve
7748     // on the stack for oop_handles and pass a handle if oop is non-null
7749 
7750     const Register rOop = src.first()->as_Register();
7751     int oop_slot;
7752     if (rOop == j_rarg0)
7753       oop_slot = 0;
7754     else if (rOop == j_rarg1)
7755       oop_slot = 1;
7756     else if (rOop == j_rarg2)
7757       oop_slot = 2;
7758     else if (rOop == j_rarg3)
7759       oop_slot = 3;
7760     else if (rOop == j_rarg4)
7761       oop_slot = 4;
7762     else if (rOop == j_rarg5)
7763       oop_slot = 5;
7764     else if (rOop == j_rarg6)
7765       oop_slot = 6;
7766     else {
7767       assert(rOop == j_rarg7, "wrong register");
7768       oop_slot = 7;
7769     }
7770 
7771     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
7772     int offset = oop_slot*VMRegImpl::stack_slot_size;
7773 
7774     map->set_oop(VMRegImpl::stack2reg(oop_slot));
7775     // Store oop in handle area, may be null
7776     str(rOop, Address(sp, offset));
7777     if (is_receiver) {
7778       *receiver_offset = offset;
7779     }
7780 
7781     cmp(rOop, zr);
7782     lea(rHandle, Address(sp, offset));
7783     // conditionally move a null
7784     csel(rHandle, zr, rHandle, Assembler::EQ);
7785   }
7786 
7787   // If arg is on the stack then place it otherwise it is already in correct reg.
7788   if (dst.first()->is_stack()) {
7789     str(rHandle, Address(sp, reg2offset_out(dst.first())));
7790   }
7791 }
7792 
7793 // A float arg may have to do float reg int reg conversion
7794 void MacroAssembler::float_move(VMRegPair src, VMRegPair dst, Register tmp) {
7795  if (src.first()->is_stack()) {
7796     if (dst.first()->is_stack()) {
7797       ldrw(tmp, Address(rfp, reg2offset_in(src.first())));
7798       strw(tmp, Address(sp, reg2offset_out(dst.first())));
7799     } else {
7800       ldrs(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
7801     }
7802   } else if (src.first() != dst.first()) {
7803     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
7804       fmovs(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
7805     else
7806       strs(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
7807   }
7808 }
7809 
7810 // A long move
7811 void MacroAssembler::long_move(VMRegPair src, VMRegPair dst, Register tmp) {
7812   if (src.first()->is_stack()) {
7813     if (dst.first()->is_stack()) {
7814       // stack to stack
7815       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7816       str(tmp, Address(sp, reg2offset_out(dst.first())));
7817     } else {
7818       // stack to reg
7819       ldr(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
7820     }
7821   } else if (dst.first()->is_stack()) {
7822     // reg to stack
7823     // Do we really have to sign extend???
7824     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
7825     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
7826   } else {
7827     if (dst.first() != src.first()) {
7828       mov(dst.first()->as_Register(), src.first()->as_Register());
7829     }
7830   }
7831 }
7832 
7833 
7834 // A double move
7835 void MacroAssembler::double_move(VMRegPair src, VMRegPair dst, Register tmp) {
7836  if (src.first()->is_stack()) {
7837     if (dst.first()->is_stack()) {
7838       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7839       str(tmp, Address(sp, reg2offset_out(dst.first())));
7840     } else {
7841       ldrd(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
7842     }
7843   } else if (src.first() != dst.first()) {
7844     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
7845       fmovd(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
7846     else
7847       strd(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
7848   }
7849 }
7850 
7851 // Implements fast-locking.
7852 //
7853 //  - obj: the object to be locked
7854 //  - t1, t2, t3: temporary registers, will be destroyed
7855 //  - slow: branched to if locking fails, absolute offset may larger than 32KB (imm14 encoding).
7856 void MacroAssembler::fast_lock(Register basic_lock, Register obj, Register t1, Register t2, Register t3, Label& slow) {
7857   assert_different_registers(basic_lock, obj, t1, t2, t3, rscratch1);
7858 
7859   Label push;
7860   const Register top = t1;
7861   const Register mark = t2;
7862   const Register t = t3;
7863 
7864   // Preload the markWord. It is important that this is the first
7865   // instruction emitted as it is part of C1's null check semantics.
7866   ldr(mark, Address(obj, oopDesc::mark_offset_in_bytes()));
7867 
7868   if (UseObjectMonitorTable) {
7869     // Clear cache in case fast locking succeeds or we need to take the slow-path.
7870     str(zr, Address(basic_lock, BasicObjectLock::lock_offset() + in_ByteSize((BasicLock::object_monitor_cache_offset_in_bytes()))));
7871   }
7872 
7873   if (DiagnoseSyncOnValueBasedClasses != 0) {
7874     load_klass(t1, obj);
7875     ldrb(t1, Address(t1, Klass::misc_flags_offset()));
7876     tst(t1, KlassFlags::_misc_is_value_based_class);
7877     br(Assembler::NE, slow);
7878   }
7879 
7880   // Check if the lock-stack is full.
7881   ldrw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7882   cmpw(top, (unsigned)LockStack::end_offset());
7883   br(Assembler::GE, slow);
7884 
7885   // Check for recursion.
7886   subw(t, top, oopSize);
7887   ldr(t, Address(rthread, t));
7888   cmp(obj, t);
7889   br(Assembler::EQ, push);
7890 
7891   // Check header for monitor (0b10).
7892   tst(mark, markWord::monitor_value);
7893   br(Assembler::NE, slow);
7894 
7895   // Try to lock. Transition lock bits 0b01 => 0b00
7896   assert(oopDesc::mark_offset_in_bytes() == 0, "required to avoid lea");
7897   orr(mark, mark, markWord::unlocked_value);
7898   // Mask inline_type bit such that we go to the slow path if object is an inline type
7899   andr(mark, mark, ~((int) markWord::inline_type_bit_in_place));
7900 
7901   eor(t, mark, markWord::unlocked_value);
7902   cmpxchg(/*addr*/ obj, /*expected*/ mark, /*new*/ t, Assembler::xword,
7903           /*acquire*/ true, /*release*/ false, /*weak*/ false, noreg);
7904   br(Assembler::NE, slow);
7905 
7906   bind(push);
7907   // After successful lock, push object on lock-stack.
7908   str(obj, Address(rthread, top));
7909   addw(top, top, oopSize);
7910   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7911 }
7912 
7913 // Implements fast-unlocking.
7914 //
7915 // - obj: the object to be unlocked
7916 // - t1, t2, t3: temporary registers
7917 // - slow: branched to if unlocking fails, absolute offset may larger than 32KB (imm14 encoding).
7918 void MacroAssembler::fast_unlock(Register obj, Register t1, Register t2, Register t3, Label& slow) {
7919   // cmpxchg clobbers rscratch1.
7920   assert_different_registers(obj, t1, t2, t3, rscratch1);
7921 
7922 #ifdef ASSERT
7923   {
7924     // Check for lock-stack underflow.
7925     Label stack_ok;
7926     ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
7927     cmpw(t1, (unsigned)LockStack::start_offset());
7928     br(Assembler::GE, stack_ok);
7929     STOP("Lock-stack underflow");
7930     bind(stack_ok);
7931   }
7932 #endif
7933 
7934   Label unlocked, push_and_slow;
7935   const Register top = t1;
7936   const Register mark = t2;
7937   const Register t = t3;
7938 
7939   // Check if obj is top of lock-stack.
7940   ldrw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7941   subw(top, top, oopSize);
7942   ldr(t, Address(rthread, top));
7943   cmp(obj, t);
7944   br(Assembler::NE, slow);
7945 
7946   // Pop lock-stack.
7947   DEBUG_ONLY(str(zr, Address(rthread, top));)
7948   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7949 
7950   // Check if recursive.
7951   subw(t, top, oopSize);
7952   ldr(t, Address(rthread, t));
7953   cmp(obj, t);
7954   br(Assembler::EQ, unlocked);
7955 
7956   // Not recursive. Check header for monitor (0b10).
7957   ldr(mark, Address(obj, oopDesc::mark_offset_in_bytes()));
7958   tbnz(mark, log2i_exact(markWord::monitor_value), push_and_slow);
7959 
7960 #ifdef ASSERT
7961   // Check header not unlocked (0b01).
7962   Label not_unlocked;
7963   tbz(mark, log2i_exact(markWord::unlocked_value), not_unlocked);
7964   stop("fast_unlock already unlocked");
7965   bind(not_unlocked);
7966 #endif
7967 
7968   // Try to unlock. Transition lock bits 0b00 => 0b01
7969   assert(oopDesc::mark_offset_in_bytes() == 0, "required to avoid lea");
7970   orr(t, mark, markWord::unlocked_value);
7971   cmpxchg(obj, mark, t, Assembler::xword,
7972           /*acquire*/ false, /*release*/ true, /*weak*/ false, noreg);
7973   br(Assembler::EQ, unlocked);
7974 
7975   bind(push_and_slow);
7976   // Restore lock-stack and handle the unlock in runtime.
7977   DEBUG_ONLY(str(obj, Address(rthread, top));)
7978   addw(top, top, oopSize);
7979   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7980   b(slow);
7981 
7982   bind(unlocked);
7983 }
7984 
7985 // Rotate using USHR and SLI instructions (or copy, if rotate count is zero)
7986 void MacroAssembler::neon_vector_rotate(FloatRegister dst, SIMD_Arrangement T,
7987                                         FloatRegister src, int shift_amount) {
7988   assert(src != dst, "did not expect src and dst to be the same register");
7989 
7990   int esize = BitsPerByte << (T / 2);
7991   int lshift = shift_amount & (esize - 1);
7992 
7993   if (lshift == 0) {
7994     // T & 1 == 0 => 64-bit arrangements, else 128-bit arrangements
7995     orr(dst, (T & 1) == 0 ? T8B : T16B, src, src);
7996   } else {
7997     ushr(dst, T, src, esize - lshift);
7998     sli(dst, T, src, lshift);
7999   }
8000 }
8001 
8002 void MacroAssembler::try_to_replace_prev_vector_copy_with_movprfx(FloatRegister dst) {
8003   if (code_section()->is_empty()) {
8004     return;
8005   }
8006 
8007   address prev = pc() - NativeInstruction::instruction_size;
8008   uint32_t insn = nativeInstruction_at(prev)->encoding();
8009   if (!NativeInstruction::is_neon_vector_mov_alias(insn) &&
8010       !NativeInstruction::is_sve_vector_mov_alias(insn)) {
8011     return;
8012   }
8013 
8014   // The destructive instruction must reuse the mov alias destination.
8015   uint32_t rd = Instruction_aarch64::extract(insn, 4, 0);
8016   if (rd != (uint32_t)dst->encoding()) {
8017     return;
8018   }
8019 
8020   uint32_t rn = Instruction_aarch64::extract(insn, 9, 5);
8021   Instruction_aarch64::patch(prev, 31, 0,
8022                              NativeInstruction::encode_sve_movprfx(rd, rn));
8023 }