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