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