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