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