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