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