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