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(/*addr*/ rscratch2, /*expected*/ zr, /*new*/ recv, Assembler::xword,
2235           /*acquire*/ false, /*release*/ false, /*weak*/ true, noreg);
2236 
2237   // CAS success means the slot now has the receiver we want. CAS failure means
2238   // something had claimed the slot concurrently: it can be the same receiver we want,
2239   // or something else. Since this is a slow path, we can optimize for code density,
2240   // and just restart the search from the beginning.
2241   b(L_restart);
2242 
2243   // Found a receiver, convert its slot offset to corresponding count offset.
2244   bind(L_found_recv);
2245   add(offset, offset, receiver_to_count_step);
2246 
2247   // Finally, update the counter
2248   bind(L_count_update);
2249   increment(Address(mdp, offset), DataLayout::counter_increment);
2250 }
2251 
2252 
2253 void MacroAssembler::call_VM_leaf_base(address entry_point,
2254                                        int number_of_arguments,
2255                                        Label *retaddr) {
2256   Label E, L;
2257 
2258   stp(rscratch1, rmethod, Address(pre(sp, -2 * wordSize)));
2259 
2260   mov(rscratch1, RuntimeAddress(entry_point));
2261   blr(rscratch1);
2262   if (retaddr)
2263     bind(*retaddr);
2264 
2265   ldp(rscratch1, rmethod, Address(post(sp, 2 * wordSize)));
2266 }
2267 
2268 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2269   call_VM_leaf_base(entry_point, number_of_arguments);
2270 }
2271 
2272 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2273   pass_arg0(this, arg_0);
2274   call_VM_leaf_base(entry_point, 1);
2275 }
2276 
2277 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2278   assert_different_registers(arg_1, c_rarg0);
2279   pass_arg0(this, arg_0);
2280   pass_arg1(this, arg_1);
2281   call_VM_leaf_base(entry_point, 2);
2282 }
2283 
2284 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0,
2285                                   Register arg_1, Register arg_2) {
2286   assert_different_registers(arg_1, c_rarg0);
2287   assert_different_registers(arg_2, c_rarg0, c_rarg1);
2288   pass_arg0(this, arg_0);
2289   pass_arg1(this, arg_1);
2290   pass_arg2(this, arg_2);
2291   call_VM_leaf_base(entry_point, 3);
2292 }
2293 
2294 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2295   pass_arg0(this, arg_0);
2296   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2297 }
2298 
2299 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2300 
2301   assert_different_registers(arg_0, c_rarg1);
2302   pass_arg1(this, arg_1);
2303   pass_arg0(this, arg_0);
2304   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2305 }
2306 
2307 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2308   assert_different_registers(arg_0, c_rarg1, c_rarg2);
2309   assert_different_registers(arg_1, c_rarg2);
2310   pass_arg2(this, arg_2);
2311   pass_arg1(this, arg_1);
2312   pass_arg0(this, arg_0);
2313   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2314 }
2315 
2316 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2317   assert_different_registers(arg_0, c_rarg1, c_rarg2, c_rarg3);
2318   assert_different_registers(arg_1, c_rarg2, c_rarg3);
2319   assert_different_registers(arg_2, c_rarg3);
2320   pass_arg3(this, arg_3);
2321   pass_arg2(this, arg_2);
2322   pass_arg1(this, arg_1);
2323   pass_arg0(this, arg_0);
2324   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2325 }
2326 
2327 void MacroAssembler::null_check(Register reg, int offset) {
2328   if (needs_explicit_null_check(offset)) {
2329     // provoke OS null exception if reg is null by
2330     // accessing M[reg] w/o changing any registers
2331     // NOTE: this is plenty to provoke a segv
2332     ldr(zr, Address(reg));
2333   } else {
2334     // nothing to do, (later) access of M[reg + offset]
2335     // will provoke OS null exception if reg is null
2336   }
2337 }
2338 
2339 // MacroAssembler protected routines needed to implement
2340 // public methods
2341 
2342 void MacroAssembler::mov(Register r, Address dest) {
2343   code_section()->relocate(pc(), dest.rspec());
2344   uint64_t imm64 = (uint64_t)dest.target();
2345   movptr(r, imm64);
2346 }
2347 
2348 // Move a constant pointer into r.  In AArch64 mode the virtual
2349 // address space is 48 bits in size, so we only need three
2350 // instructions to create a patchable instruction sequence that can
2351 // reach anywhere.
2352 void MacroAssembler::movptr(Register r, uintptr_t imm64) {
2353 #ifndef PRODUCT
2354   {
2355     char buffer[64];
2356     os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX64, (uint64_t)imm64);
2357     block_comment(buffer);
2358   }
2359 #endif
2360   assert(imm64 < (1ull << 48), "48-bit overflow in address constant");
2361   movz(r, imm64 & 0xffff);
2362   imm64 >>= 16;
2363   movk(r, imm64 & 0xffff, 16);
2364   imm64 >>= 16;
2365   movk(r, imm64 & 0xffff, 32);
2366 }
2367 
2368 // Macro to mov replicated immediate to vector register.
2369 // imm64: only the lower 8/16/32 bits are considered for B/H/S type. That is,
2370 //        the upper 56/48/32 bits must be zeros for B/H/S type.
2371 // Vd will get the following values for different arrangements in T
2372 //   imm64 == hex 000000gh  T8B:  Vd = ghghghghghghghgh
2373 //   imm64 == hex 000000gh  T16B: Vd = ghghghghghghghghghghghghghghghgh
2374 //   imm64 == hex 0000efgh  T4H:  Vd = efghefghefghefgh
2375 //   imm64 == hex 0000efgh  T8H:  Vd = efghefghefghefghefghefghefghefgh
2376 //   imm64 == hex abcdefgh  T2S:  Vd = abcdefghabcdefgh
2377 //   imm64 == hex abcdefgh  T4S:  Vd = abcdefghabcdefghabcdefghabcdefgh
2378 //   imm64 == hex abcdefgh  T1D:  Vd = 00000000abcdefgh
2379 //   imm64 == hex abcdefgh  T2D:  Vd = 00000000abcdefgh00000000abcdefgh
2380 // Clobbers rscratch1
2381 void MacroAssembler::mov(FloatRegister Vd, SIMD_Arrangement T, uint64_t imm64) {
2382   assert(T != T1Q, "unsupported");
2383   if (T == T1D || T == T2D) {
2384     int imm = operand_valid_for_movi_immediate(imm64, T);
2385     if (-1 != imm) {
2386       movi(Vd, T, imm);
2387     } else {
2388       mov(rscratch1, imm64);
2389       dup(Vd, T, rscratch1);
2390     }
2391     return;
2392   }
2393 
2394 #ifdef ASSERT
2395   if (T == T8B || T == T16B) assert((imm64 & ~0xff) == 0, "extraneous bits (T8B/T16B)");
2396   if (T == T4H || T == T8H) assert((imm64  & ~0xffff) == 0, "extraneous bits (T4H/T8H)");
2397   if (T == T2S || T == T4S) assert((imm64  & ~0xffffffff) == 0, "extraneous bits (T2S/T4S)");
2398 #endif
2399   int shift = operand_valid_for_movi_immediate(imm64, T);
2400   uint32_t imm32 = imm64 & 0xffffffffULL;
2401   if (shift >= 0) {
2402     movi(Vd, T, (imm32 >> shift) & 0xff, shift);
2403   } else {
2404     movw(rscratch1, imm32);
2405     dup(Vd, T, rscratch1);
2406   }
2407 }
2408 
2409 void MacroAssembler::mov_immediate64(Register dst, uint64_t imm64)
2410 {
2411 #ifndef PRODUCT
2412   {
2413     char buffer[64];
2414     os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX64, imm64);
2415     block_comment(buffer);
2416   }
2417 #endif
2418   if (operand_valid_for_logical_immediate(false, imm64)) {
2419     orr(dst, zr, imm64);
2420   } else {
2421     // we can use a combination of MOVZ or MOVN with
2422     // MOVK to build up the constant
2423     uint64_t imm_h[4];
2424     int zero_count = 0;
2425     int neg_count = 0;
2426     int i;
2427     for (i = 0; i < 4; i++) {
2428       imm_h[i] = ((imm64 >> (i * 16)) & 0xffffL);
2429       if (imm_h[i] == 0) {
2430         zero_count++;
2431       } else if (imm_h[i] == 0xffffL) {
2432         neg_count++;
2433       }
2434     }
2435     if (zero_count == 4) {
2436       // one MOVZ will do
2437       movz(dst, 0);
2438     } else if (neg_count == 4) {
2439       // one MOVN will do
2440       movn(dst, 0);
2441     } else if (zero_count == 3) {
2442       for (i = 0; i < 4; i++) {
2443         if (imm_h[i] != 0L) {
2444           movz(dst, (uint32_t)imm_h[i], (i << 4));
2445           break;
2446         }
2447       }
2448     } else if (neg_count == 3) {
2449       // one MOVN will do
2450       for (int i = 0; i < 4; i++) {
2451         if (imm_h[i] != 0xffffL) {
2452           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2453           break;
2454         }
2455       }
2456     } else if (zero_count == 2) {
2457       // one MOVZ and one MOVK will do
2458       for (i = 0; i < 3; i++) {
2459         if (imm_h[i] != 0L) {
2460           movz(dst, (uint32_t)imm_h[i], (i << 4));
2461           i++;
2462           break;
2463         }
2464       }
2465       for (;i < 4; i++) {
2466         if (imm_h[i] != 0L) {
2467           movk(dst, (uint32_t)imm_h[i], (i << 4));
2468         }
2469       }
2470     } else if (neg_count == 2) {
2471       // one MOVN and one MOVK will do
2472       for (i = 0; i < 4; i++) {
2473         if (imm_h[i] != 0xffffL) {
2474           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2475           i++;
2476           break;
2477         }
2478       }
2479       for (;i < 4; i++) {
2480         if (imm_h[i] != 0xffffL) {
2481           movk(dst, (uint32_t)imm_h[i], (i << 4));
2482         }
2483       }
2484     } else if (zero_count == 1) {
2485       // one MOVZ and two MOVKs will do
2486       for (i = 0; i < 4; i++) {
2487         if (imm_h[i] != 0L) {
2488           movz(dst, (uint32_t)imm_h[i], (i << 4));
2489           i++;
2490           break;
2491         }
2492       }
2493       for (;i < 4; i++) {
2494         if (imm_h[i] != 0x0L) {
2495           movk(dst, (uint32_t)imm_h[i], (i << 4));
2496         }
2497       }
2498     } else if (neg_count == 1) {
2499       // one MOVN and two MOVKs will do
2500       for (i = 0; i < 4; i++) {
2501         if (imm_h[i] != 0xffffL) {
2502           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2503           i++;
2504           break;
2505         }
2506       }
2507       for (;i < 4; i++) {
2508         if (imm_h[i] != 0xffffL) {
2509           movk(dst, (uint32_t)imm_h[i], (i << 4));
2510         }
2511       }
2512     } else {
2513       // use a MOVZ and 3 MOVKs (makes it easier to debug)
2514       movz(dst, (uint32_t)imm_h[0], 0);
2515       for (i = 1; i < 4; i++) {
2516         movk(dst, (uint32_t)imm_h[i], (i << 4));
2517       }
2518     }
2519   }
2520 }
2521 
2522 void MacroAssembler::mov_immediate32(Register dst, uint32_t imm32)
2523 {
2524 #ifndef PRODUCT
2525     {
2526       char buffer[64];
2527       os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX32, imm32);
2528       block_comment(buffer);
2529     }
2530 #endif
2531   if (operand_valid_for_logical_immediate(true, imm32)) {
2532     orrw(dst, zr, imm32);
2533   } else {
2534     // we can use MOVZ, MOVN or two calls to MOVK to build up the
2535     // constant
2536     uint32_t imm_h[2];
2537     imm_h[0] = imm32 & 0xffff;
2538     imm_h[1] = ((imm32 >> 16) & 0xffff);
2539     if (imm_h[0] == 0) {
2540       movzw(dst, imm_h[1], 16);
2541     } else if (imm_h[0] == 0xffff) {
2542       movnw(dst, imm_h[1] ^ 0xffff, 16);
2543     } else if (imm_h[1] == 0) {
2544       movzw(dst, imm_h[0], 0);
2545     } else if (imm_h[1] == 0xffff) {
2546       movnw(dst, imm_h[0] ^ 0xffff, 0);
2547     } else {
2548       // use a MOVZ and MOVK (makes it easier to debug)
2549       movzw(dst, imm_h[0], 0);
2550       movkw(dst, imm_h[1], 16);
2551     }
2552   }
2553 }
2554 
2555 // Form an address from base + offset in Rd.  Rd may or may
2556 // not actually be used: you must use the Address that is returned.
2557 // It is up to you to ensure that the shift provided matches the size
2558 // of your data.
2559 Address MacroAssembler::form_address(Register Rd, Register base, int64_t byte_offset, int shift) {
2560   if (Address::offset_ok_for_immed(byte_offset, shift))
2561     // It fits; no need for any heroics
2562     return Address(base, byte_offset);
2563 
2564   // Don't do anything clever with negative or misaligned offsets
2565   unsigned mask = (1 << shift) - 1;
2566   if (byte_offset < 0 || byte_offset & mask) {
2567     mov(Rd, byte_offset);
2568     add(Rd, base, Rd);
2569     return Address(Rd);
2570   }
2571 
2572   // See if we can do this with two 12-bit offsets
2573   {
2574     uint64_t word_offset = byte_offset >> shift;
2575     uint64_t masked_offset = word_offset & 0xfff000;
2576     if (Address::offset_ok_for_immed(word_offset - masked_offset, 0)
2577         && Assembler::operand_valid_for_add_sub_immediate(masked_offset << shift)) {
2578       add(Rd, base, masked_offset << shift);
2579       word_offset -= masked_offset;
2580       return Address(Rd, word_offset << shift);
2581     }
2582   }
2583 
2584   // Do it the hard way
2585   mov(Rd, byte_offset);
2586   add(Rd, base, Rd);
2587   return Address(Rd);
2588 }
2589 
2590 int MacroAssembler::corrected_idivl(Register result, Register ra, Register rb,
2591                                     bool want_remainder, Register scratch)
2592 {
2593   // Full implementation of Java idiv and irem.  The function
2594   // returns the (pc) offset of the div instruction - may be needed
2595   // for implicit exceptions.
2596   //
2597   // constraint : ra/rb =/= scratch
2598   //         normal case
2599   //
2600   // input : ra: dividend
2601   //         rb: divisor
2602   //
2603   // result: either
2604   //         quotient  (= ra idiv rb)
2605   //         remainder (= ra irem rb)
2606 
2607   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
2608 
2609   int idivl_offset = offset();
2610   if (! want_remainder) {
2611     sdivw(result, ra, rb);
2612   } else {
2613     sdivw(scratch, ra, rb);
2614     Assembler::msubw(result, scratch, rb, ra);
2615   }
2616 
2617   return idivl_offset;
2618 }
2619 
2620 int MacroAssembler::corrected_idivq(Register result, Register ra, Register rb,
2621                                     bool want_remainder, Register scratch)
2622 {
2623   // Full implementation of Java ldiv and lrem.  The function
2624   // returns the (pc) offset of the div instruction - may be needed
2625   // for implicit exceptions.
2626   //
2627   // constraint : ra/rb =/= scratch
2628   //         normal case
2629   //
2630   // input : ra: dividend
2631   //         rb: divisor
2632   //
2633   // result: either
2634   //         quotient  (= ra idiv rb)
2635   //         remainder (= ra irem rb)
2636 
2637   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
2638 
2639   int idivq_offset = offset();
2640   if (! want_remainder) {
2641     sdiv(result, ra, rb);
2642   } else {
2643     sdiv(scratch, ra, rb);
2644     Assembler::msub(result, scratch, rb, ra);
2645   }
2646 
2647   return idivq_offset;
2648 }
2649 
2650 void MacroAssembler::membar(Membar_mask_bits order_constraint) {
2651   address prev = pc() - NativeMembar::instruction_size;
2652   address last = code()->last_merge_candidate();
2653   if (last != nullptr && nativeInstruction_at(last)->is_Membar() && prev == last) {
2654     NativeMembar *bar = NativeMembar_at(prev);
2655     if (AlwaysMergeDMB) {
2656       bar->set_kind(bar->get_kind() | order_constraint);
2657       BLOCK_COMMENT("merged membar(always)");
2658       return;
2659     }
2660     // Don't promote DMB ST|DMB LD to DMB (a full barrier) because
2661     // doing so would introduce a StoreLoad which the caller did not
2662     // intend
2663     if (bar->get_kind() == order_constraint
2664         || bar->get_kind() == AnyAny
2665         || order_constraint == AnyAny) {
2666       // We are merging two memory barrier instructions.  On AArch64 we
2667       // can do this simply by ORing them together.
2668       bar->set_kind(bar->get_kind() | order_constraint);
2669       BLOCK_COMMENT("merged membar");
2670       return;
2671     } else {
2672       // A special case like "DMB ST;DMB LD;DMB ST", the last DMB can be skipped.
2673       // We need to check the second-to-last instruction, only if it is inside
2674       // the current code section.
2675       address prev2 = prev - NativeMembar::instruction_size;
2676       if (prev2 >= begin() && last != code()->last_label() && nativeInstruction_at(prev2)->is_Membar()) {
2677         NativeMembar *bar2 = NativeMembar_at(prev2);
2678         assert(bar2->get_kind() == order_constraint, "it should be merged before");
2679         BLOCK_COMMENT("merged membar(elided)");
2680         return;
2681       }
2682     }
2683   }
2684   code()->set_last_merge_candidate(pc());
2685   dmb(Assembler::barrier(order_constraint));
2686 }
2687 
2688 bool MacroAssembler::try_merge_ldst(Register rt, const Address &adr, size_t size_in_bytes, bool is_store) {
2689   if (ldst_can_merge(rt, adr, size_in_bytes, is_store)) {
2690     merge_ldst(rt, adr, size_in_bytes, is_store);
2691     code()->clear_last_merge_candidate();
2692     return true;
2693   } else {
2694     assert(size_in_bytes == 8 || size_in_bytes == 4, "only 8 bytes or 4 bytes load/store is supported.");
2695     const uint64_t mask = size_in_bytes - 1;
2696     if (adr.getMode() == Address::base_plus_offset &&
2697         (adr.offset() & mask) == 0) { // only supports base_plus_offset.
2698       code()->set_last_merge_candidate(pc());
2699     }
2700     return false;
2701   }
2702 }
2703 
2704 void MacroAssembler::ldr(Register Rx, const Address &adr) {
2705   // We always try to merge two adjacent loads into one ldp.
2706   if (!try_merge_ldst(Rx, adr, 8, false)) {
2707     Assembler::ldr(Rx, adr);
2708   }
2709 }
2710 
2711 void MacroAssembler::ldrw(Register Rw, const Address &adr) {
2712   // We always try to merge two adjacent loads into one ldp.
2713   if (!try_merge_ldst(Rw, adr, 4, false)) {
2714     Assembler::ldrw(Rw, adr);
2715   }
2716 }
2717 
2718 void MacroAssembler::str(Register Rx, const Address &adr) {
2719   // We always try to merge two adjacent stores into one stp.
2720   if (!try_merge_ldst(Rx, adr, 8, true)) {
2721     Assembler::str(Rx, adr);
2722   }
2723 }
2724 
2725 void MacroAssembler::strw(Register Rw, const Address &adr) {
2726   // We always try to merge two adjacent stores into one stp.
2727   if (!try_merge_ldst(Rw, adr, 4, true)) {
2728     Assembler::strw(Rw, adr);
2729   }
2730 }
2731 
2732 // MacroAssembler routines found actually to be needed
2733 
2734 void MacroAssembler::push(Register src)
2735 {
2736   str(src, Address(pre(esp, -1 * wordSize)));
2737 }
2738 
2739 void MacroAssembler::pop(Register dst)
2740 {
2741   ldr(dst, Address(post(esp, 1 * wordSize)));
2742 }
2743 
2744 // Note: load_unsigned_short used to be called load_unsigned_word.
2745 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
2746   int off = offset();
2747   ldrh(dst, src);
2748   return off;
2749 }
2750 
2751 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
2752   int off = offset();
2753   ldrb(dst, src);
2754   return off;
2755 }
2756 
2757 int MacroAssembler::load_signed_short(Register dst, Address src) {
2758   int off = offset();
2759   ldrsh(dst, src);
2760   return off;
2761 }
2762 
2763 int MacroAssembler::load_signed_byte(Register dst, Address src) {
2764   int off = offset();
2765   ldrsb(dst, src);
2766   return off;
2767 }
2768 
2769 int MacroAssembler::load_signed_short32(Register dst, Address src) {
2770   int off = offset();
2771   ldrshw(dst, src);
2772   return off;
2773 }
2774 
2775 int MacroAssembler::load_signed_byte32(Register dst, Address src) {
2776   int off = offset();
2777   ldrsbw(dst, src);
2778   return off;
2779 }
2780 
2781 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed) {
2782   switch (size_in_bytes) {
2783   case  8:  ldr(dst, src); break;
2784   case  4:  ldrw(dst, src); break;
2785   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
2786   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
2787   default:  ShouldNotReachHere();
2788   }
2789 }
2790 
2791 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes) {
2792   switch (size_in_bytes) {
2793   case  8:  str(src, dst); break;
2794   case  4:  strw(src, dst); break;
2795   case  2:  strh(src, dst); break;
2796   case  1:  strb(src, dst); break;
2797   default:  ShouldNotReachHere();
2798   }
2799 }
2800 
2801 void MacroAssembler::narrow_subword_type(Register reg, BasicType bt) {
2802   assert(is_subword_type(bt), "required");
2803   switch (bt) {
2804   case T_BOOLEAN: andw(reg, reg, 1); break;
2805   case T_BYTE:    sxtbw(reg, reg); break;
2806   case T_CHAR:    uxthw(reg, reg); break;
2807   case T_SHORT:   sxthw(reg, reg); break;
2808   default:        ShouldNotReachHere();
2809   }
2810 }
2811 
2812 void MacroAssembler::decrementw(Register reg, int value)
2813 {
2814   if (value < 0)  { incrementw(reg, -value);      return; }
2815   if (value == 0) {                               return; }
2816   if (value < (1 << 12)) { subw(reg, reg, value); return; }
2817   /* else */ {
2818     guarantee(reg != rscratch2, "invalid dst for register decrement");
2819     movw(rscratch2, (unsigned)value);
2820     subw(reg, reg, rscratch2);
2821   }
2822 }
2823 
2824 void MacroAssembler::decrement(Register reg, int value)
2825 {
2826   if (value < 0)  { increment(reg, -value);      return; }
2827   if (value == 0) {                              return; }
2828   if (value < (1 << 12)) { sub(reg, reg, value); return; }
2829   /* else */ {
2830     assert(reg != rscratch2, "invalid dst for register decrement");
2831     mov(rscratch2, (uint64_t)value);
2832     sub(reg, reg, rscratch2);
2833   }
2834 }
2835 
2836 void MacroAssembler::decrementw(Address dst, int value)
2837 {
2838   assert(!dst.uses(rscratch1), "invalid dst for address decrement");
2839   if (dst.getMode() == Address::literal) {
2840     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2841     lea(rscratch2, dst);
2842     dst = Address(rscratch2);
2843   }
2844   ldrw(rscratch1, dst);
2845   decrementw(rscratch1, value);
2846   strw(rscratch1, dst);
2847 }
2848 
2849 void MacroAssembler::decrement(Address dst, int value)
2850 {
2851   assert(!dst.uses(rscratch1), "invalid address for decrement");
2852   if (dst.getMode() == Address::literal) {
2853     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2854     lea(rscratch2, dst);
2855     dst = Address(rscratch2);
2856   }
2857   ldr(rscratch1, dst);
2858   decrement(rscratch1, value);
2859   str(rscratch1, dst);
2860 }
2861 
2862 void MacroAssembler::incrementw(Register reg, int value)
2863 {
2864   if (value < 0)  { decrementw(reg, -value);      return; }
2865   if (value == 0) {                               return; }
2866   if (value < (1 << 12)) { addw(reg, reg, value); return; }
2867   /* else */ {
2868     assert(reg != rscratch2, "invalid dst for register increment");
2869     movw(rscratch2, (unsigned)value);
2870     addw(reg, reg, rscratch2);
2871   }
2872 }
2873 
2874 void MacroAssembler::increment(Register reg, int value)
2875 {
2876   if (value < 0)  { decrement(reg, -value);      return; }
2877   if (value == 0) {                              return; }
2878   if (value < (1 << 12)) { add(reg, reg, value); return; }
2879   /* else */ {
2880     assert(reg != rscratch2, "invalid dst for register increment");
2881     movw(rscratch2, (unsigned)value);
2882     add(reg, reg, rscratch2);
2883   }
2884 }
2885 
2886 void MacroAssembler::incrementw(Address dst, int value)
2887 {
2888   assert(!dst.uses(rscratch1), "invalid dst for address increment");
2889   if (dst.getMode() == Address::literal) {
2890     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2891     lea(rscratch2, dst);
2892     dst = Address(rscratch2);
2893   }
2894   ldrw(rscratch1, dst);
2895   incrementw(rscratch1, value);
2896   strw(rscratch1, dst);
2897 }
2898 
2899 void MacroAssembler::increment(Address dst, int value)
2900 {
2901   assert(!dst.uses(rscratch1), "invalid dst for address increment");
2902   if (dst.getMode() == Address::literal) {
2903     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2904     lea(rscratch2, dst);
2905     dst = Address(rscratch2);
2906   }
2907   ldr(rscratch1, dst);
2908   increment(rscratch1, value);
2909   str(rscratch1, dst);
2910 }
2911 
2912 // Push lots of registers in the bit set supplied.  Don't push sp.
2913 // Return the number of words pushed
2914 int MacroAssembler::push(RegSet regset, Register stack) {
2915   if (regset.bits() == 0) {
2916     return 0;
2917   }
2918   auto bitset = integer_cast<unsigned int>(regset.bits());
2919   int words_pushed = 0;
2920 
2921   // Scan bitset to accumulate register pairs
2922   unsigned char regs[32];
2923   int count = 0;
2924   for (int reg = 0; reg <= 30; reg++) {
2925     if (1 & bitset)
2926       regs[count++] = reg;
2927     bitset >>= 1;
2928   }
2929   regs[count++] = zr->raw_encoding();
2930   count &= ~1;  // Only push an even number of regs
2931 
2932   if (count) {
2933     stp(as_Register(regs[0]), as_Register(regs[1]),
2934        Address(pre(stack, -count * wordSize)));
2935     words_pushed += 2;
2936   }
2937   for (int i = 2; i < count; i += 2) {
2938     stp(as_Register(regs[i]), as_Register(regs[i+1]),
2939        Address(stack, i * wordSize));
2940     words_pushed += 2;
2941   }
2942 
2943   assert(words_pushed == count, "oops, pushed != count");
2944 
2945   return count;
2946 }
2947 
2948 int MacroAssembler::pop(RegSet regset, Register stack) {
2949   if (regset.bits() == 0) {
2950     return 0;
2951   }
2952   auto bitset = integer_cast<unsigned int>(regset.bits());
2953   int words_pushed = 0;
2954 
2955   // Scan bitset to accumulate register pairs
2956   unsigned char regs[32];
2957   int count = 0;
2958   for (int reg = 0; reg <= 30; reg++) {
2959     if (1 & bitset)
2960       regs[count++] = reg;
2961     bitset >>= 1;
2962   }
2963   regs[count++] = zr->raw_encoding();
2964   count &= ~1;
2965 
2966   for (int i = 2; i < count; i += 2) {
2967     ldp(as_Register(regs[i]), as_Register(regs[i+1]),
2968        Address(stack, i * wordSize));
2969     words_pushed += 2;
2970   }
2971   if (count) {
2972     ldp(as_Register(regs[0]), as_Register(regs[1]),
2973        Address(post(stack, count * wordSize)));
2974     words_pushed += 2;
2975   }
2976 
2977   assert(words_pushed == count, "oops, pushed != count");
2978 
2979   return count;
2980 }
2981 
2982 // Push lots of registers in the bit set supplied.  Don't push sp.
2983 // Return the number of dwords pushed
2984 int MacroAssembler::push_fp(FloatRegSet regset, Register stack, FpPushPopMode mode) {
2985   if (regset.bits() == 0) {
2986     return 0;
2987   }
2988   auto bitset = integer_cast<unsigned int>(regset.bits());
2989   int words_pushed = 0;
2990   bool use_sve = false;
2991   int sve_vector_size_in_bytes = 0;
2992 
2993 #ifdef COMPILER2
2994   use_sve = Matcher::supports_scalable_vector();
2995   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
2996 #endif
2997 
2998   // Scan bitset to accumulate register pairs
2999   unsigned char regs[32];
3000   int count = 0;
3001   for (int reg = 0; reg <= 31; reg++) {
3002     if (1 & bitset)
3003       regs[count++] = reg;
3004     bitset >>= 1;
3005   }
3006 
3007   if (count == 0) {
3008     return 0;
3009   }
3010 
3011   if (mode == PushPopFull) {
3012     if (use_sve && sve_vector_size_in_bytes > 16) {
3013       mode = PushPopSVE;
3014     } else {
3015       mode = PushPopNeon;
3016     }
3017   }
3018 
3019 #ifndef PRODUCT
3020   {
3021     char buffer[48];
3022     if (mode == PushPopSVE) {
3023       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d SVE registers", count);
3024     } else if (mode == PushPopNeon) {
3025       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d Neon registers", count);
3026     } else {
3027       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d fp registers", count);
3028     }
3029     block_comment(buffer);
3030   }
3031 #endif
3032 
3033   if (mode == PushPopSVE) {
3034     sub(stack, stack, sve_vector_size_in_bytes * count);
3035     for (int i = 0; i < count; i++) {
3036       sve_str(as_FloatRegister(regs[i]), Address(stack, i));
3037     }
3038     return count * sve_vector_size_in_bytes / 8;
3039   }
3040 
3041   if (mode == PushPopNeon) {
3042     if (count == 1) {
3043       strq(as_FloatRegister(regs[0]), Address(pre(stack, -wordSize * 2)));
3044       return 2;
3045     }
3046 
3047     bool odd = (count & 1) == 1;
3048     int push_slots = count + (odd ? 1 : 0);
3049 
3050     // Always pushing full 128 bit registers.
3051     stpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize * 2)));
3052     words_pushed += 2;
3053 
3054     for (int i = 2; i + 1 < count; i += 2) {
3055       stpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
3056       words_pushed += 2;
3057     }
3058 
3059     if (odd) {
3060       strq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
3061       words_pushed++;
3062     }
3063 
3064     assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
3065     return count * 2;
3066   }
3067 
3068   if (mode == PushPopFp) {
3069     bool odd = (count & 1) == 1;
3070     int push_slots = count + (odd ? 1 : 0);
3071 
3072     if (count == 1) {
3073       // Stack pointer must be 16 bytes aligned
3074       strd(as_FloatRegister(regs[0]), Address(pre(stack, -push_slots * wordSize)));
3075       return 1;
3076     }
3077 
3078     stpd(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize)));
3079     words_pushed += 2;
3080 
3081     for (int i = 2; i + 1 < count; i += 2) {
3082       stpd(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize));
3083       words_pushed += 2;
3084     }
3085 
3086     if (odd) {
3087       // Stack pointer must be 16 bytes aligned
3088       strd(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize));
3089       words_pushed++;
3090     }
3091 
3092     assert(words_pushed == count, "oops, pushed != count");
3093 
3094     return count;
3095   }
3096 
3097   return 0;
3098 }
3099 
3100 // Return the number of dwords popped
3101 int MacroAssembler::pop_fp(FloatRegSet regset, Register stack, FpPushPopMode mode) {
3102   if (regset.bits() == 0) {
3103     return 0;
3104   }
3105   auto bitset = integer_cast<unsigned int>(regset.bits());
3106   int words_pushed = 0;
3107   bool use_sve = false;
3108   int sve_vector_size_in_bytes = 0;
3109 
3110 #ifdef COMPILER2
3111   use_sve = Matcher::supports_scalable_vector();
3112   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
3113 #endif
3114   // Scan bitset to accumulate register pairs
3115   unsigned char regs[32];
3116   int count = 0;
3117   for (int reg = 0; reg <= 31; reg++) {
3118     if (1 & bitset)
3119       regs[count++] = reg;
3120     bitset >>= 1;
3121   }
3122 
3123   if (count == 0) {
3124     return 0;
3125   }
3126 
3127   if (mode == PushPopFull) {
3128     if (use_sve && sve_vector_size_in_bytes > 16) {
3129       mode = PushPopSVE;
3130     } else {
3131       mode = PushPopNeon;
3132     }
3133   }
3134 
3135 #ifndef PRODUCT
3136   {
3137     char buffer[48];
3138     if (mode == PushPopSVE) {
3139       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d SVE registers", count);
3140     } else if (mode == PushPopNeon) {
3141       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d Neon registers", count);
3142     } else {
3143       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d fp registers", count);
3144     }
3145     block_comment(buffer);
3146   }
3147 #endif
3148 
3149   if (mode == PushPopSVE) {
3150     for (int i = count - 1; i >= 0; i--) {
3151       sve_ldr(as_FloatRegister(regs[i]), Address(stack, i));
3152     }
3153     add(stack, stack, sve_vector_size_in_bytes * count);
3154     return count * sve_vector_size_in_bytes / 8;
3155   }
3156 
3157   if (mode == PushPopNeon) {
3158     if (count == 1) {
3159       ldrq(as_FloatRegister(regs[0]), Address(post(stack, wordSize * 2)));
3160       return 2;
3161     }
3162 
3163     bool odd = (count & 1) == 1;
3164     int push_slots = count + (odd ? 1 : 0);
3165 
3166     if (odd) {
3167       ldrq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
3168       words_pushed++;
3169     }
3170 
3171     for (int i = 2; i + 1 < count; i += 2) {
3172       ldpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
3173       words_pushed += 2;
3174     }
3175 
3176     ldpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize * 2)));
3177     words_pushed += 2;
3178 
3179     assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
3180 
3181     return count * 2;
3182   }
3183 
3184   if (mode == PushPopFp) {
3185     bool odd = (count & 1) == 1;
3186     int push_slots = count + (odd ? 1 : 0);
3187 
3188     if (count == 1) {
3189       ldrd(as_FloatRegister(regs[0]), Address(post(stack, push_slots * wordSize)));
3190       return 1;
3191     }
3192 
3193     if (odd) {
3194       ldrd(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize));
3195       words_pushed++;
3196     }
3197 
3198     for (int i = 2; i + 1 < count; i += 2) {
3199       ldpd(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize));
3200       words_pushed += 2;
3201     }
3202 
3203     ldpd(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize)));
3204     words_pushed += 2;
3205 
3206     assert(words_pushed == count, "oops, pushed != count");
3207 
3208     return count;
3209   }
3210 
3211   return 0;
3212 }
3213 
3214 // Return the number of dwords pushed
3215 int MacroAssembler::push_p(PRegSet regset, Register stack) {
3216   if (regset.bits() == 0) {
3217     return 0;
3218   }
3219   auto bitset = integer_cast<unsigned int>(regset.bits());
3220   bool use_sve = false;
3221   int sve_predicate_size_in_slots = 0;
3222 
3223 #ifdef COMPILER2
3224   use_sve = Matcher::supports_scalable_vector();
3225   if (use_sve) {
3226     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
3227   }
3228 #endif
3229 
3230   if (!use_sve) {
3231     return 0;
3232   }
3233 
3234   unsigned char regs[PRegister::number_of_registers];
3235   int count = 0;
3236   for (int reg = 0; reg < PRegister::number_of_registers; reg++) {
3237     if (1 & bitset)
3238       regs[count++] = reg;
3239     bitset >>= 1;
3240   }
3241 
3242   if (count == 0) {
3243     return 0;
3244   }
3245 
3246   int total_push_bytes = align_up(sve_predicate_size_in_slots *
3247                                   VMRegImpl::stack_slot_size * count, 16);
3248   sub(stack, stack, total_push_bytes);
3249   for (int i = 0; i < count; i++) {
3250     sve_str(as_PRegister(regs[i]), Address(stack, i));
3251   }
3252   return total_push_bytes / 8;
3253 }
3254 
3255 // Return the number of dwords popped
3256 int MacroAssembler::pop_p(PRegSet regset, Register stack) {
3257   if (regset.bits() == 0) {
3258     return 0;
3259   }
3260   auto bitset = integer_cast<unsigned int>(regset.bits());
3261   bool use_sve = false;
3262   int sve_predicate_size_in_slots = 0;
3263 
3264 #ifdef COMPILER2
3265   use_sve = Matcher::supports_scalable_vector();
3266   if (use_sve) {
3267     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
3268   }
3269 #endif
3270 
3271   if (!use_sve) {
3272     return 0;
3273   }
3274 
3275   unsigned char regs[PRegister::number_of_registers];
3276   int count = 0;
3277   for (int reg = 0; reg < PRegister::number_of_registers; reg++) {
3278     if (1 & bitset)
3279       regs[count++] = reg;
3280     bitset >>= 1;
3281   }
3282 
3283   if (count == 0) {
3284     return 0;
3285   }
3286 
3287   int total_pop_bytes = align_up(sve_predicate_size_in_slots *
3288                                  VMRegImpl::stack_slot_size * count, 16);
3289   for (int i = count - 1; i >= 0; i--) {
3290     sve_ldr(as_PRegister(regs[i]), Address(stack, i));
3291   }
3292   add(stack, stack, total_pop_bytes);
3293   return total_pop_bytes / 8;
3294 }
3295 
3296 #ifdef ASSERT
3297 void MacroAssembler::verify_heapbase(const char* msg) {
3298 #if 0
3299   assert (Universe::heap() != nullptr, "java heap should be initialized");
3300   if (!UseCompressedOops || Universe::ptr_base() == nullptr) {
3301     // rheapbase is allocated as general register
3302     return;
3303   }
3304   if (CheckCompressedOops) {
3305     Label ok;
3306     push(1 << rscratch1->encoding(), sp); // cmpptr trashes rscratch1
3307     cmpptr(rheapbase, ExternalAddress(CompressedOops::base_addr()));
3308     br(Assembler::EQ, ok);
3309     stop(msg);
3310     bind(ok);
3311     pop(1 << rscratch1->encoding(), sp);
3312   }
3313 #endif
3314 }
3315 #endif
3316 
3317 void MacroAssembler::resolve_jobject(Register value, Register tmp1, Register tmp2) {
3318   assert_different_registers(value, tmp1, tmp2);
3319   Label done, tagged, weak_tagged;
3320 
3321   cbz(value, done);           // Use null as-is.
3322   tst(value, JNIHandles::tag_mask); // Test for tag.
3323   br(Assembler::NE, tagged);
3324 
3325   // Resolve local handle
3326   access_load_at(T_OBJECT, IN_NATIVE | AS_RAW, value, Address(value, 0), tmp1, tmp2);
3327   verify_oop(value);
3328   b(done);
3329 
3330   bind(tagged);
3331   STATIC_ASSERT(JNIHandles::TypeTag::weak_global == 0b1);
3332   tbnz(value, 0, weak_tagged);    // Test for weak tag.
3333 
3334   // Resolve global handle
3335   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, -JNIHandles::TypeTag::global), tmp1, tmp2);
3336   verify_oop(value);
3337   b(done);
3338 
3339   bind(weak_tagged);
3340   // Resolve jweak.
3341   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
3342                  value, Address(value, -JNIHandles::TypeTag::weak_global), tmp1, tmp2);
3343   verify_oop(value);
3344 
3345   bind(done);
3346 }
3347 
3348 void MacroAssembler::resolve_global_jobject(Register value, Register tmp1, Register tmp2) {
3349   assert_different_registers(value, tmp1, tmp2);
3350   Label done;
3351 
3352   cbz(value, done);           // Use null as-is.
3353 
3354 #ifdef ASSERT
3355   {
3356     STATIC_ASSERT(JNIHandles::TypeTag::global == 0b10);
3357     Label valid_global_tag;
3358     tbnz(value, 1, valid_global_tag); // Test for global tag
3359     stop("non global jobject using resolve_global_jobject");
3360     bind(valid_global_tag);
3361   }
3362 #endif
3363 
3364   // Resolve global handle
3365   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, -JNIHandles::TypeTag::global), tmp1, tmp2);
3366   verify_oop(value);
3367 
3368   bind(done);
3369 }
3370 
3371 void MacroAssembler::stop(const char* msg) {
3372   // Skip AOT caching C strings in scratch buffer.
3373   const char* str = (code_section()->scratch_emit()) ? msg : AOTCodeCache::add_C_string(msg);
3374   BLOCK_COMMENT(str);
3375   // load msg into r0 so we can access it from the signal handler
3376   // ExternalAddress enables saving and restoring via the code cache
3377   lea(c_rarg0, ExternalAddress((address) str));
3378   dcps1(0xdeae);
3379 }
3380 
3381 void MacroAssembler::unimplemented(const char* what) {
3382   const char* buf = nullptr;
3383   {
3384     ResourceMark rm;
3385     stringStream ss;
3386     ss.print("unimplemented: %s", what);
3387     buf = code_string(ss.as_string());
3388   }
3389   stop(buf);
3390 }
3391 
3392 void MacroAssembler::_assert_asm(Assembler::Condition cc, const char* msg) {
3393 #ifdef ASSERT
3394   Label OK;
3395   br(cc, OK);
3396   stop(msg);
3397   bind(OK);
3398 #endif
3399 }
3400 
3401 // If a constant does not fit in an immediate field, generate some
3402 // number of MOV instructions and then perform the operation.
3403 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, uint64_t imm,
3404                                            add_sub_imm_insn insn1,
3405                                            add_sub_reg_insn insn2,
3406                                            bool is32) {
3407   assert(Rd != zr, "Rd = zr and not setting flags?");
3408   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
3409   if (fits) {
3410     (this->*insn1)(Rd, Rn, imm);
3411   } else {
3412     if (g_uabs(imm) < (1 << 24)) {
3413        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
3414        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
3415     } else {
3416        assert_different_registers(Rd, Rn);
3417        mov(Rd, imm);
3418        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
3419     }
3420   }
3421 }
3422 
3423 // Separate vsn which sets the flags. Optimisations are more restricted
3424 // because we must set the flags correctly.
3425 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, uint64_t imm,
3426                                              add_sub_imm_insn insn1,
3427                                              add_sub_reg_insn insn2,
3428                                              bool is32) {
3429   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
3430   if (fits) {
3431     (this->*insn1)(Rd, Rn, imm);
3432   } else {
3433     assert_different_registers(Rd, Rn);
3434     assert(Rd != zr, "overflow in immediate operand");
3435     mov(Rd, imm);
3436     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
3437   }
3438 }
3439 
3440 
3441 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
3442   if (increment.is_register()) {
3443     add(Rd, Rn, increment.as_register());
3444   } else {
3445     add(Rd, Rn, increment.as_constant());
3446   }
3447 }
3448 
3449 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
3450   if (increment.is_register()) {
3451     addw(Rd, Rn, increment.as_register());
3452   } else {
3453     addw(Rd, Rn, increment.as_constant());
3454   }
3455 }
3456 
3457 void MacroAssembler::sub(Register Rd, Register Rn, RegisterOrConstant decrement) {
3458   if (decrement.is_register()) {
3459     sub(Rd, Rn, decrement.as_register());
3460   } else {
3461     sub(Rd, Rn, decrement.as_constant());
3462   }
3463 }
3464 
3465 void MacroAssembler::subw(Register Rd, Register Rn, RegisterOrConstant decrement) {
3466   if (decrement.is_register()) {
3467     subw(Rd, Rn, decrement.as_register());
3468   } else {
3469     subw(Rd, Rn, decrement.as_constant());
3470   }
3471 }
3472 
3473 void MacroAssembler::reinit_heapbase()
3474 {
3475   if (UseCompressedOops) {
3476     if (Universe::is_fully_initialized() && !AOTCodeCache::is_on_for_dump()) {
3477       mov(rheapbase, CompressedOops::base());
3478     } else {
3479       lea(rheapbase, ExternalAddress(CompressedOops::base_addr()));
3480       ldr(rheapbase, Address(rheapbase));
3481     }
3482   }
3483 }
3484 
3485 // A generic CAS; success or failure is in the EQ flag.  A weak CAS
3486 // doesn't retry and may fail spuriously.  If the oldval is wanted,
3487 // Pass a register for the result, otherwise pass noreg.
3488 
3489 // Clobbers rscratch1
3490 void MacroAssembler::cmpxchg(Register addr, Register expected,
3491                              Register new_val,
3492                              enum operand_size size,
3493                              bool acquire, bool release,
3494                              bool weak,
3495                              Register result) {
3496   if (result == noreg)  result = rscratch1;
3497   BLOCK_COMMENT("cmpxchg {");
3498   if (UseLSE) {
3499     mov(result, expected);
3500     lse_cas(result, new_val, addr, size, acquire, release, /*not_pair*/ true);
3501     compare_eq(result, expected, size);
3502 #ifdef ASSERT
3503     // Poison rscratch1 which is written on !UseLSE branch
3504     mov(rscratch1, 0x1f1f1f1f1f1f1f1f);
3505 #endif
3506   } else {
3507     Label retry_load, done;
3508     prfm(Address(addr), PSTL1STRM);
3509     bind(retry_load);
3510     load_exclusive(result, addr, size, acquire);
3511     compare_eq(result, expected, size);
3512     br(Assembler::NE, done);
3513     store_exclusive(rscratch1, new_val, addr, size, release);
3514     if (weak) {
3515       cmpw(rscratch1, 0u);  // If the store fails, return NE to our caller.
3516     } else {
3517       cbnzw(rscratch1, retry_load);
3518     }
3519     bind(done);
3520   }
3521   BLOCK_COMMENT("} cmpxchg");
3522 }
3523 
3524 // A generic comparison. Only compares for equality, clobbers rscratch1.
3525 void MacroAssembler::compare_eq(Register rm, Register rn, enum operand_size size) {
3526   if (size == xword) {
3527     cmp(rm, rn);
3528   } else if (size == word) {
3529     cmpw(rm, rn);
3530   } else if (size == halfword) {
3531     eorw(rscratch1, rm, rn);
3532     ands(zr, rscratch1, 0xffff);
3533   } else if (size == byte) {
3534     eorw(rscratch1, rm, rn);
3535     ands(zr, rscratch1, 0xff);
3536   } else {
3537     ShouldNotReachHere();
3538   }
3539 }
3540 
3541 
3542 static bool different(Register a, RegisterOrConstant b, Register c) {
3543   if (b.is_constant())
3544     return a != c;
3545   else
3546     return a != b.as_register() && a != c && b.as_register() != c;
3547 }
3548 
3549 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
3550 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
3551   if (UseLSE) {                                                         \
3552     prev = prev->is_valid() ? prev : zr;                                \
3553     if (incr.is_register()) {                                           \
3554       AOP(sz, incr.as_register(), prev, addr);                          \
3555     } else {                                                            \
3556       mov(rscratch2, incr.as_constant());                               \
3557       AOP(sz, rscratch2, prev, addr);                                   \
3558     }                                                                   \
3559     return;                                                             \
3560   }                                                                     \
3561   Register result = rscratch2;                                          \
3562   if (prev->is_valid())                                                 \
3563     result = different(prev, incr, addr) ? prev : rscratch2;            \
3564                                                                         \
3565   Label retry_load;                                                     \
3566   prfm(Address(addr), PSTL1STRM);                                       \
3567   bind(retry_load);                                                     \
3568   LDXR(result, addr);                                                   \
3569   OP(rscratch1, result, incr);                                          \
3570   STXR(rscratch2, rscratch1, addr);                                     \
3571   cbnzw(rscratch2, retry_load);                                         \
3572   if (prev->is_valid() && prev != result) {                             \
3573     IOP(prev, rscratch1, incr);                                         \
3574   }                                                                     \
3575 }
3576 
3577 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
3578 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
3579 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
3580 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
3581 
3582 #undef ATOMIC_OP
3583 
3584 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
3585 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
3586   if (UseLSE) {                                                         \
3587     prev = prev->is_valid() ? prev : zr;                                \
3588     AOP(sz, newv, prev, addr);                                          \
3589     return;                                                             \
3590   }                                                                     \
3591   Register result = rscratch2;                                          \
3592   if (prev->is_valid())                                                 \
3593     result = different(prev, newv, addr) ? prev : rscratch2;            \
3594                                                                         \
3595   Label retry_load;                                                     \
3596   prfm(Address(addr), PSTL1STRM);                                       \
3597   bind(retry_load);                                                     \
3598   LDXR(result, addr);                                                   \
3599   STXR(rscratch1, newv, addr);                                          \
3600   cbnzw(rscratch1, retry_load);                                         \
3601   if (prev->is_valid() && prev != result)                               \
3602     mov(prev, result);                                                  \
3603 }
3604 
3605 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
3606 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
3607 ATOMIC_XCHG(xchgl, swpl, ldxr, stlxr, Assembler::xword)
3608 ATOMIC_XCHG(xchglw, swpl, ldxrw, stlxrw, Assembler::word)
3609 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
3610 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
3611 
3612 #undef ATOMIC_XCHG
3613 
3614 #ifndef PRODUCT
3615 extern "C" void findpc(intptr_t x);
3616 #endif
3617 
3618 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
3619 {
3620   // In order to get locks to work, we need to fake a in_VM state
3621   if (ShowMessageBoxOnError) {
3622     JavaThread* thread = JavaThread::current();
3623     thread->set_thread_state(_thread_in_vm);
3624 #ifndef PRODUCT
3625     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
3626       ttyLocker ttyl;
3627       BytecodeCounter::print();
3628     }
3629 #endif
3630     if (os::message_box(msg, "Execution stopped, print registers?")) {
3631       ttyLocker ttyl;
3632       tty->print_cr(" pc = 0x%016" PRIx64, pc);
3633 #ifndef PRODUCT
3634       tty->cr();
3635       findpc(pc);
3636       tty->cr();
3637 #endif
3638       tty->print_cr(" r0 = 0x%016" PRIx64, regs[0]);
3639       tty->print_cr(" r1 = 0x%016" PRIx64, regs[1]);
3640       tty->print_cr(" r2 = 0x%016" PRIx64, regs[2]);
3641       tty->print_cr(" r3 = 0x%016" PRIx64, regs[3]);
3642       tty->print_cr(" r4 = 0x%016" PRIx64, regs[4]);
3643       tty->print_cr(" r5 = 0x%016" PRIx64, regs[5]);
3644       tty->print_cr(" r6 = 0x%016" PRIx64, regs[6]);
3645       tty->print_cr(" r7 = 0x%016" PRIx64, regs[7]);
3646       tty->print_cr(" r8 = 0x%016" PRIx64, regs[8]);
3647       tty->print_cr(" r9 = 0x%016" PRIx64, regs[9]);
3648       tty->print_cr("r10 = 0x%016" PRIx64, regs[10]);
3649       tty->print_cr("r11 = 0x%016" PRIx64, regs[11]);
3650       tty->print_cr("r12 = 0x%016" PRIx64, regs[12]);
3651       tty->print_cr("r13 = 0x%016" PRIx64, regs[13]);
3652       tty->print_cr("r14 = 0x%016" PRIx64, regs[14]);
3653       tty->print_cr("r15 = 0x%016" PRIx64, regs[15]);
3654       tty->print_cr("r16 = 0x%016" PRIx64, regs[16]);
3655       tty->print_cr("r17 = 0x%016" PRIx64, regs[17]);
3656       tty->print_cr("r18 = 0x%016" PRIx64, regs[18]);
3657       tty->print_cr("r19 = 0x%016" PRIx64, regs[19]);
3658       tty->print_cr("r20 = 0x%016" PRIx64, regs[20]);
3659       tty->print_cr("r21 = 0x%016" PRIx64, regs[21]);
3660       tty->print_cr("r22 = 0x%016" PRIx64, regs[22]);
3661       tty->print_cr("r23 = 0x%016" PRIx64, regs[23]);
3662       tty->print_cr("r24 = 0x%016" PRIx64, regs[24]);
3663       tty->print_cr("r25 = 0x%016" PRIx64, regs[25]);
3664       tty->print_cr("r26 = 0x%016" PRIx64, regs[26]);
3665       tty->print_cr("r27 = 0x%016" PRIx64, regs[27]);
3666       tty->print_cr("r28 = 0x%016" PRIx64, regs[28]);
3667       tty->print_cr("r30 = 0x%016" PRIx64, regs[30]);
3668       tty->print_cr("r31 = 0x%016" PRIx64, regs[31]);
3669       BREAKPOINT;
3670     }
3671   }
3672   fatal("DEBUG MESSAGE: %s", msg);
3673 }
3674 
3675 RegSet MacroAssembler::call_clobbered_gp_registers() {
3676   RegSet regs = RegSet::range(r0, r17) - RegSet::of(rscratch1, rscratch2);
3677 #ifndef R18_RESERVED
3678   regs += r18_tls;
3679 #endif
3680   return regs;
3681 }
3682 
3683 void MacroAssembler::push_call_clobbered_registers_except(RegSet exclude) {
3684   int step = 4 * wordSize;
3685   push(call_clobbered_gp_registers() - exclude, sp);
3686   sub(sp, sp, step);
3687   mov(rscratch1, -step);
3688   // Push v0-v7, v16-v31.
3689   for (int i = 31; i>= 4; i -= 4) {
3690     if (i <= v7->encoding() || i >= v16->encoding())
3691       st1(as_FloatRegister(i-3), as_FloatRegister(i-2), as_FloatRegister(i-1),
3692           as_FloatRegister(i), T1D, Address(post(sp, rscratch1)));
3693   }
3694   st1(as_FloatRegister(0), as_FloatRegister(1), as_FloatRegister(2),
3695       as_FloatRegister(3), T1D, Address(sp));
3696 }
3697 
3698 void MacroAssembler::pop_call_clobbered_registers_except(RegSet exclude) {
3699   for (int i = 0; i < 32; i += 4) {
3700     if (i <= v7->encoding() || i >= v16->encoding())
3701       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3702           as_FloatRegister(i+3), T1D, Address(post(sp, 4 * wordSize)));
3703   }
3704 
3705   reinitialize_ptrue();
3706 
3707   pop(call_clobbered_gp_registers() - exclude, sp);
3708 }
3709 
3710 void MacroAssembler::push_CPU_state(bool save_vectors, bool use_sve,
3711                                     int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
3712   push(RegSet::range(r0, r29), sp); // integer registers except lr & sp
3713   if (save_vectors && use_sve && sve_vector_size_in_bytes > 16) {
3714     sub(sp, sp, sve_vector_size_in_bytes * FloatRegister::number_of_registers);
3715     for (int i = 0; i < FloatRegister::number_of_registers; i++) {
3716       sve_str(as_FloatRegister(i), Address(sp, i));
3717     }
3718   } else {
3719     int step = (save_vectors ? 8 : 4) * wordSize;
3720     mov(rscratch1, -step);
3721     sub(sp, sp, step);
3722     for (int i = 28; i >= 4; i -= 4) {
3723       st1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3724           as_FloatRegister(i+3), save_vectors ? T2D : T1D, Address(post(sp, rscratch1)));
3725     }
3726     st1(v0, v1, v2, v3, save_vectors ? T2D : T1D, sp);
3727   }
3728   if (save_vectors && use_sve && total_predicate_in_bytes > 0) {
3729     sub(sp, sp, total_predicate_in_bytes);
3730     for (int i = 0; i < PRegister::number_of_registers; i++) {
3731       sve_str(as_PRegister(i), Address(sp, i));
3732     }
3733   }
3734 }
3735 
3736 void MacroAssembler::pop_CPU_state(bool restore_vectors, bool use_sve,
3737                                    int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
3738   if (restore_vectors && use_sve && total_predicate_in_bytes > 0) {
3739     for (int i = PRegister::number_of_registers - 1; i >= 0; i--) {
3740       sve_ldr(as_PRegister(i), Address(sp, i));
3741     }
3742     add(sp, sp, total_predicate_in_bytes);
3743   }
3744   if (restore_vectors && use_sve && sve_vector_size_in_bytes > 16) {
3745     for (int i = FloatRegister::number_of_registers - 1; i >= 0; i--) {
3746       sve_ldr(as_FloatRegister(i), Address(sp, i));
3747     }
3748     add(sp, sp, sve_vector_size_in_bytes * FloatRegister::number_of_registers);
3749   } else {
3750     int step = (restore_vectors ? 8 : 4) * wordSize;
3751     for (int i = 0; i <= 28; i += 4)
3752       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3753           as_FloatRegister(i+3), restore_vectors ? T2D : T1D, Address(post(sp, step)));
3754   }
3755 
3756   // We may use predicate registers and rely on ptrue with SVE,
3757   // regardless of wide vector (> 8 bytes) used or not.
3758   if (use_sve) {
3759     reinitialize_ptrue();
3760   }
3761 
3762   // integer registers except lr & sp
3763   pop(RegSet::range(r0, r17), sp);
3764 #ifdef R18_RESERVED
3765   ldp(zr, r19, Address(post(sp, 2 * wordSize)));
3766   pop(RegSet::range(r20, r29), sp);
3767 #else
3768   pop(RegSet::range(r18_tls, r29), sp);
3769 #endif
3770 }
3771 
3772 /**
3773  * Helpers for multiply_to_len().
3774  */
3775 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
3776                                      Register src1, Register src2) {
3777   adds(dest_lo, dest_lo, src1);
3778   adc(dest_hi, dest_hi, zr);
3779   adds(dest_lo, dest_lo, src2);
3780   adc(final_dest_hi, dest_hi, zr);
3781 }
3782 
3783 // Generate an address from (r + r1 extend offset).  "size" is the
3784 // size of the operand.  The result may be in rscratch2.
3785 Address MacroAssembler::offsetted_address(Register r, Register r1,
3786                                           Address::extend ext, int offset, int size) {
3787   if (offset || (ext.shift() % size != 0)) {
3788     lea(rscratch2, Address(r, r1, ext));
3789     return Address(rscratch2, offset);
3790   } else {
3791     return Address(r, r1, ext);
3792   }
3793 }
3794 
3795 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
3796 {
3797   assert(offset >= 0, "spill to negative address?");
3798   // Offset reachable ?
3799   //   Not aligned - 9 bits signed offset
3800   //   Aligned - 12 bits unsigned offset shifted
3801   Register base = sp;
3802   if ((offset & (size-1)) && offset >= (1<<8)) {
3803     add(tmp, base, offset & ((1<<12)-1));
3804     base = tmp;
3805     offset &= -1u<<12;
3806   }
3807 
3808   if (offset >= (1<<12) * size) {
3809     add(tmp, base, offset & (((1<<12)-1)<<12));
3810     base = tmp;
3811     offset &= ~(((1<<12)-1)<<12);
3812   }
3813 
3814   return Address(base, offset);
3815 }
3816 
3817 Address MacroAssembler::sve_spill_address(int sve_reg_size_in_bytes, int offset, Register tmp) {
3818   assert(offset >= 0, "spill to negative address?");
3819 
3820   Register base = sp;
3821 
3822   // An immediate offset in the range 0 to 255 which is multiplied
3823   // by the current vector or predicate register size in bytes.
3824   if (offset % sve_reg_size_in_bytes == 0 && offset < ((1<<8)*sve_reg_size_in_bytes)) {
3825     return Address(base, offset / sve_reg_size_in_bytes);
3826   }
3827 
3828   add(tmp, base, offset);
3829   return Address(tmp);
3830 }
3831 
3832 // Checks whether offset is aligned.
3833 // Returns true if it is, else false.
3834 bool MacroAssembler::merge_alignment_check(Register base,
3835                                            size_t size,
3836                                            int64_t cur_offset,
3837                                            int64_t prev_offset) const {
3838   if (AvoidUnalignedAccesses) {
3839     if (base == sp) {
3840       // Checks whether low offset if aligned to pair of registers.
3841       int64_t pair_mask = size * 2 - 1;
3842       int64_t offset = prev_offset > cur_offset ? cur_offset : prev_offset;
3843       return (offset & pair_mask) == 0;
3844     } else { // If base is not sp, we can't guarantee the access is aligned.
3845       return false;
3846     }
3847   } else {
3848     int64_t mask = size - 1;
3849     // Load/store pair instruction only supports element size aligned offset.
3850     return (cur_offset & mask) == 0 && (prev_offset & mask) == 0;
3851   }
3852 }
3853 
3854 // Checks whether current and previous loads/stores can be merged.
3855 // Returns true if it can be merged, else false.
3856 bool MacroAssembler::ldst_can_merge(Register rt,
3857                                     const Address &adr,
3858                                     size_t cur_size_in_bytes,
3859                                     bool is_store) const {
3860   address prev = pc() - NativeInstruction::instruction_size;
3861   address last = code()->last_merge_candidate();
3862 
3863   if (last == nullptr || !nativeInstruction_at(last)->is_Imm_LdSt()) {
3864     return false;
3865   }
3866 
3867   if (adr.getMode() != Address::base_plus_offset || prev != last) {
3868     return false;
3869   }
3870 
3871   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
3872   size_t prev_size_in_bytes = prev_ldst->size_in_bytes();
3873 
3874   assert(prev_size_in_bytes == 4 || prev_size_in_bytes == 8, "only supports 64/32bit merging.");
3875   assert(cur_size_in_bytes == 4 || cur_size_in_bytes == 8, "only supports 64/32bit merging.");
3876 
3877   if (cur_size_in_bytes != prev_size_in_bytes || is_store != prev_ldst->is_store()) {
3878     return false;
3879   }
3880 
3881   int64_t max_offset = 63 * prev_size_in_bytes;
3882   int64_t min_offset = -64 * prev_size_in_bytes;
3883 
3884   assert(prev_ldst->is_not_pre_post_index(), "pre-index or post-index is not supported to be merged.");
3885 
3886   // Only same base can be merged.
3887   if (adr.base() != prev_ldst->base()) {
3888     return false;
3889   }
3890 
3891   int64_t cur_offset = adr.offset();
3892   int64_t prev_offset = prev_ldst->offset();
3893   size_t diff = abs(cur_offset - prev_offset);
3894   if (diff != prev_size_in_bytes) {
3895     return false;
3896   }
3897 
3898   // Following cases can not be merged:
3899   // ldr x2, [x2, #8]
3900   // ldr x3, [x2, #16]
3901   // or:
3902   // ldr x2, [x3, #8]
3903   // ldr x2, [x3, #16]
3904   // If t1 and t2 is the same in "ldp t1, t2, [xn, #imm]", we'll get SIGILL.
3905   if (!is_store && (adr.base() == prev_ldst->target() || rt == prev_ldst->target())) {
3906     return false;
3907   }
3908 
3909   int64_t low_offset = prev_offset > cur_offset ? cur_offset : prev_offset;
3910   // Offset range must be in ldp/stp instruction's range.
3911   if (low_offset > max_offset || low_offset < min_offset) {
3912     return false;
3913   }
3914 
3915   if (merge_alignment_check(adr.base(), prev_size_in_bytes, cur_offset, prev_offset)) {
3916     return true;
3917   }
3918 
3919   return false;
3920 }
3921 
3922 // Merge current load/store with previous load/store into ldp/stp.
3923 void MacroAssembler::merge_ldst(Register rt,
3924                                 const Address &adr,
3925                                 size_t cur_size_in_bytes,
3926                                 bool is_store) {
3927 
3928   assert(ldst_can_merge(rt, adr, cur_size_in_bytes, is_store) == true, "cur and prev must be able to be merged.");
3929 
3930   Register rt_low, rt_high;
3931   address prev = pc() - NativeInstruction::instruction_size;
3932   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
3933 
3934   int64_t offset;
3935 
3936   if (adr.offset() < prev_ldst->offset()) {
3937     offset = adr.offset();
3938     rt_low = rt;
3939     rt_high = prev_ldst->target();
3940   } else {
3941     offset = prev_ldst->offset();
3942     rt_low = prev_ldst->target();
3943     rt_high = rt;
3944   }
3945 
3946   Address adr_p = Address(prev_ldst->base(), offset);
3947   // Overwrite previous generated binary.
3948   code_section()->set_end(prev);
3949 
3950   const size_t sz = prev_ldst->size_in_bytes();
3951   assert(sz == 8 || sz == 4, "only supports 64/32bit merging.");
3952   if (!is_store) {
3953     BLOCK_COMMENT("merged ldr pair");
3954     if (sz == 8) {
3955       ldp(rt_low, rt_high, adr_p);
3956     } else {
3957       ldpw(rt_low, rt_high, adr_p);
3958     }
3959   } else {
3960     BLOCK_COMMENT("merged str pair");
3961     if (sz == 8) {
3962       stp(rt_low, rt_high, adr_p);
3963     } else {
3964       stpw(rt_low, rt_high, adr_p);
3965     }
3966   }
3967 }
3968 
3969 /**
3970  * Multiply 64 bit by 64 bit first loop.
3971  */
3972 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
3973                                            Register y, Register y_idx, Register z,
3974                                            Register carry, Register product,
3975                                            Register idx, Register kdx) {
3976   //
3977   //  jlong carry, x[], y[], z[];
3978   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
3979   //    huge_128 product = y[idx] * x[xstart] + carry;
3980   //    z[kdx] = (jlong)product;
3981   //    carry  = (jlong)(product >>> 64);
3982   //  }
3983   //  z[xstart] = carry;
3984   //
3985 
3986   Label L_first_loop, L_first_loop_exit;
3987   Label L_one_x, L_one_y, L_multiply;
3988 
3989   subsw(xstart, xstart, 1);
3990   br(Assembler::MI, L_one_x);
3991 
3992   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
3993   ldr(x_xstart, Address(rscratch1));
3994   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
3995 
3996   bind(L_first_loop);
3997   subsw(idx, idx, 1);
3998   br(Assembler::MI, L_first_loop_exit);
3999   subsw(idx, idx, 1);
4000   br(Assembler::MI, L_one_y);
4001   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4002   ldr(y_idx, Address(rscratch1));
4003   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
4004   bind(L_multiply);
4005 
4006   // AArch64 has a multiply-accumulate instruction that we can't use
4007   // here because it has no way to process carries, so we have to use
4008   // separate add and adc instructions.  Bah.
4009   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
4010   mul(product, x_xstart, y_idx);
4011   adds(product, product, carry);
4012   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
4013 
4014   subw(kdx, kdx, 2);
4015   ror(product, product, 32); // back to big-endian
4016   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
4017 
4018   b(L_first_loop);
4019 
4020   bind(L_one_y);
4021   ldrw(y_idx, Address(y,  0));
4022   b(L_multiply);
4023 
4024   bind(L_one_x);
4025   ldrw(x_xstart, Address(x,  0));
4026   b(L_first_loop);
4027 
4028   bind(L_first_loop_exit);
4029 }
4030 
4031 /**
4032  * Multiply 128 bit by 128. Unrolled inner loop.
4033  *
4034  */
4035 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
4036                                              Register carry, Register carry2,
4037                                              Register idx, Register jdx,
4038                                              Register yz_idx1, Register yz_idx2,
4039                                              Register tmp, Register tmp3, Register tmp4,
4040                                              Register tmp6, Register product_hi) {
4041 
4042   //   jlong carry, x[], y[], z[];
4043   //   int kdx = ystart+1;
4044   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
4045   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
4046   //     jlong carry2  = (jlong)(tmp3 >>> 64);
4047   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
4048   //     carry  = (jlong)(tmp4 >>> 64);
4049   //     z[kdx+idx+1] = (jlong)tmp3;
4050   //     z[kdx+idx] = (jlong)tmp4;
4051   //   }
4052   //   idx += 2;
4053   //   if (idx > 0) {
4054   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
4055   //     z[kdx+idx] = (jlong)yz_idx1;
4056   //     carry  = (jlong)(yz_idx1 >>> 64);
4057   //   }
4058   //
4059 
4060   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
4061 
4062   lsrw(jdx, idx, 2);
4063 
4064   bind(L_third_loop);
4065 
4066   subsw(jdx, jdx, 1);
4067   br(Assembler::MI, L_third_loop_exit);
4068   subw(idx, idx, 4);
4069 
4070   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4071 
4072   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
4073 
4074   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4075 
4076   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
4077   ror(yz_idx2, yz_idx2, 32);
4078 
4079   ldp(rscratch2, rscratch1, Address(tmp6, 0));
4080 
4081   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
4082   umulh(tmp4, product_hi, yz_idx1);
4083 
4084   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
4085   ror(rscratch2, rscratch2, 32);
4086 
4087   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
4088   umulh(carry2, product_hi, yz_idx2);
4089 
4090   // propagate sum of both multiplications into carry:tmp4:tmp3
4091   adds(tmp3, tmp3, carry);
4092   adc(tmp4, tmp4, zr);
4093   adds(tmp3, tmp3, rscratch1);
4094   adcs(tmp4, tmp4, tmp);
4095   adc(carry, carry2, zr);
4096   adds(tmp4, tmp4, rscratch2);
4097   adc(carry, carry, zr);
4098 
4099   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
4100   ror(tmp4, tmp4, 32);
4101   stp(tmp4, tmp3, Address(tmp6, 0));
4102 
4103   b(L_third_loop);
4104   bind (L_third_loop_exit);
4105 
4106   andw (idx, idx, 0x3);
4107   cbz(idx, L_post_third_loop_done);
4108 
4109   Label L_check_1;
4110   subsw(idx, idx, 2);
4111   br(Assembler::MI, L_check_1);
4112 
4113   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4114   ldr(yz_idx1, Address(rscratch1, 0));
4115   ror(yz_idx1, yz_idx1, 32);
4116   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
4117   umulh(tmp4, product_hi, yz_idx1);
4118   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4119   ldr(yz_idx2, Address(rscratch1, 0));
4120   ror(yz_idx2, yz_idx2, 32);
4121 
4122   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
4123 
4124   ror(tmp3, tmp3, 32);
4125   str(tmp3, Address(rscratch1, 0));
4126 
4127   bind (L_check_1);
4128 
4129   andw (idx, idx, 0x1);
4130   subsw(idx, idx, 1);
4131   br(Assembler::MI, L_post_third_loop_done);
4132   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4133   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
4134   umulh(carry2, tmp4, product_hi);
4135   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4136 
4137   add2_with_carry(carry2, tmp3, tmp4, carry);
4138 
4139   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4140   extr(carry, carry2, tmp3, 32);
4141 
4142   bind(L_post_third_loop_done);
4143 }
4144 
4145 /**
4146  * Code for BigInteger::multiplyToLen() intrinsic.
4147  *
4148  * r0: x
4149  * r1: xlen
4150  * r2: y
4151  * r3: ylen
4152  * r4:  z
4153  * r5: tmp0
4154  * r10: tmp1
4155  * r11: tmp2
4156  * r12: tmp3
4157  * r13: tmp4
4158  * r14: tmp5
4159  * r15: tmp6
4160  * r16: tmp7
4161  *
4162  */
4163 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
4164                                      Register z, Register tmp0,
4165                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
4166                                      Register tmp5, Register tmp6, Register product_hi) {
4167 
4168   assert_different_registers(x, xlen, y, ylen, z, tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, product_hi);
4169 
4170   const Register idx = tmp1;
4171   const Register kdx = tmp2;
4172   const Register xstart = tmp3;
4173 
4174   const Register y_idx = tmp4;
4175   const Register carry = tmp5;
4176   const Register product  = xlen;
4177   const Register x_xstart = tmp0;
4178 
4179   // First Loop.
4180   //
4181   //  final static long LONG_MASK = 0xffffffffL;
4182   //  int xstart = xlen - 1;
4183   //  int ystart = ylen - 1;
4184   //  long carry = 0;
4185   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
4186   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
4187   //    z[kdx] = (int)product;
4188   //    carry = product >>> 32;
4189   //  }
4190   //  z[xstart] = (int)carry;
4191   //
4192 
4193   movw(idx, ylen);       // idx = ylen;
4194   addw(kdx, xlen, ylen); // kdx = xlen+ylen;
4195   mov(carry, zr);        // carry = 0;
4196 
4197   Label L_done;
4198 
4199   movw(xstart, xlen);
4200   subsw(xstart, xstart, 1);
4201   br(Assembler::MI, L_done);
4202 
4203   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
4204 
4205   Label L_second_loop;
4206   cbzw(kdx, L_second_loop);
4207 
4208   Label L_carry;
4209   subw(kdx, kdx, 1);
4210   cbzw(kdx, L_carry);
4211 
4212   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
4213   lsr(carry, carry, 32);
4214   subw(kdx, kdx, 1);
4215 
4216   bind(L_carry);
4217   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
4218 
4219   // Second and third (nested) loops.
4220   //
4221   // for (int i = xstart-1; i >= 0; i--) { // Second loop
4222   //   carry = 0;
4223   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
4224   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
4225   //                    (z[k] & LONG_MASK) + carry;
4226   //     z[k] = (int)product;
4227   //     carry = product >>> 32;
4228   //   }
4229   //   z[i] = (int)carry;
4230   // }
4231   //
4232   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
4233 
4234   const Register jdx = tmp1;
4235 
4236   bind(L_second_loop);
4237   mov(carry, zr);                // carry = 0;
4238   movw(jdx, ylen);               // j = ystart+1
4239 
4240   subsw(xstart, xstart, 1);      // i = xstart-1;
4241   br(Assembler::MI, L_done);
4242 
4243   str(z, Address(pre(sp, -4 * wordSize)));
4244 
4245   Label L_last_x;
4246   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
4247   subsw(xstart, xstart, 1);       // i = xstart-1;
4248   br(Assembler::MI, L_last_x);
4249 
4250   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
4251   ldr(product_hi, Address(rscratch1));
4252   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
4253 
4254   Label L_third_loop_prologue;
4255   bind(L_third_loop_prologue);
4256 
4257   str(ylen, Address(sp, wordSize));
4258   stp(x, xstart, Address(sp, 2 * wordSize));
4259   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
4260                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
4261   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
4262   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
4263 
4264   addw(tmp3, xlen, 1);
4265   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
4266   subsw(tmp3, tmp3, 1);
4267   br(Assembler::MI, L_done);
4268 
4269   lsr(carry, carry, 32);
4270   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
4271   b(L_second_loop);
4272 
4273   // Next infrequent code is moved outside loops.
4274   bind(L_last_x);
4275   ldrw(product_hi, Address(x,  0));
4276   b(L_third_loop_prologue);
4277 
4278   bind(L_done);
4279 }
4280 
4281 // Code for BigInteger::mulAdd intrinsic
4282 // out     = r0
4283 // in      = r1
4284 // offset  = r2  (already out.length-offset)
4285 // len     = r3
4286 // k       = r4
4287 //
4288 // pseudo code from java implementation:
4289 // carry = 0;
4290 // offset = out.length-offset - 1;
4291 // for (int j=len-1; j >= 0; j--) {
4292 //     product = (in[j] & LONG_MASK) * kLong + (out[offset] & LONG_MASK) + carry;
4293 //     out[offset--] = (int)product;
4294 //     carry = product >>> 32;
4295 // }
4296 // return (int)carry;
4297 void MacroAssembler::mul_add(Register out, Register in, Register offset,
4298       Register len, Register k) {
4299     Label LOOP, END;
4300     // pre-loop
4301     cmp(len, zr); // cmp, not cbz/cbnz: to use condition twice => less branches
4302     csel(out, zr, out, Assembler::EQ);
4303     br(Assembler::EQ, END);
4304     add(in, in, len, LSL, 2); // in[j+1] address
4305     add(offset, out, offset, LSL, 2); // out[offset + 1] address
4306     mov(out, zr); // used to keep carry now
4307     BIND(LOOP);
4308     ldrw(rscratch1, Address(pre(in, -4)));
4309     madd(rscratch1, rscratch1, k, out);
4310     ldrw(rscratch2, Address(pre(offset, -4)));
4311     add(rscratch1, rscratch1, rscratch2);
4312     strw(rscratch1, Address(offset));
4313     lsr(out, rscratch1, 32);
4314     subs(len, len, 1);
4315     br(Assembler::NE, LOOP);
4316     BIND(END);
4317 }
4318 
4319 /**
4320  * Emits code to update CRC-32 with a byte value according to constants in table
4321  *
4322  * @param [in,out]crc   Register containing the crc.
4323  * @param [in]val       Register containing the byte to fold into the CRC.
4324  * @param [in]table     Register containing the table of crc constants.
4325  *
4326  * uint32_t crc;
4327  * val = crc_table[(val ^ crc) & 0xFF];
4328  * crc = val ^ (crc >> 8);
4329  *
4330  */
4331 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
4332   eor(val, val, crc);
4333   andr(val, val, 0xff);
4334   ldrw(val, Address(table, val, Address::lsl(2)));
4335   eor(crc, val, crc, Assembler::LSR, 8);
4336 }
4337 
4338 /**
4339  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
4340  *
4341  * @param [in,out]crc   Register containing the crc.
4342  * @param [in]v         Register containing the 32-bit to fold into the CRC.
4343  * @param [in]table0    Register containing table 0 of crc constants.
4344  * @param [in]table1    Register containing table 1 of crc constants.
4345  * @param [in]table2    Register containing table 2 of crc constants.
4346  * @param [in]table3    Register containing table 3 of crc constants.
4347  *
4348  * uint32_t crc;
4349  *   v = crc ^ v
4350  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
4351  *
4352  */
4353 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
4354         Register table0, Register table1, Register table2, Register table3,
4355         bool upper) {
4356   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
4357   uxtb(tmp, v);
4358   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
4359   ubfx(tmp, v, 8, 8);
4360   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
4361   eor(crc, crc, tmp);
4362   ubfx(tmp, v, 16, 8);
4363   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
4364   eor(crc, crc, tmp);
4365   ubfx(tmp, v, 24, 8);
4366   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
4367   eor(crc, crc, tmp);
4368 }
4369 
4370 void MacroAssembler::kernel_crc32_using_crypto_pmull(Register crc, Register buf,
4371         Register len, Register tmp0, Register tmp1, Register tmp2, Register tmp3) {
4372     Label CRC_by4_loop, CRC_by1_loop, CRC_less128, CRC_by128_pre, CRC_by32_loop, CRC_less32, L_exit;
4373     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
4374 
4375     subs(tmp0, len, 384);
4376     mvnw(crc, crc);
4377     br(Assembler::GE, CRC_by128_pre);
4378   BIND(CRC_less128);
4379     subs(len, len, 32);
4380     br(Assembler::GE, CRC_by32_loop);
4381   BIND(CRC_less32);
4382     adds(len, len, 32 - 4);
4383     br(Assembler::GE, CRC_by4_loop);
4384     adds(len, len, 4);
4385     br(Assembler::GT, CRC_by1_loop);
4386     b(L_exit);
4387 
4388   BIND(CRC_by32_loop);
4389     ldp(tmp0, tmp1, Address(buf));
4390     crc32x(crc, crc, tmp0);
4391     ldp(tmp2, tmp3, Address(buf, 16));
4392     crc32x(crc, crc, tmp1);
4393     add(buf, buf, 32);
4394     crc32x(crc, crc, tmp2);
4395     subs(len, len, 32);
4396     crc32x(crc, crc, tmp3);
4397     br(Assembler::GE, CRC_by32_loop);
4398     cmn(len, (u1)32);
4399     br(Assembler::NE, CRC_less32);
4400     b(L_exit);
4401 
4402   BIND(CRC_by4_loop);
4403     ldrw(tmp0, Address(post(buf, 4)));
4404     subs(len, len, 4);
4405     crc32w(crc, crc, tmp0);
4406     br(Assembler::GE, CRC_by4_loop);
4407     adds(len, len, 4);
4408     br(Assembler::LE, L_exit);
4409   BIND(CRC_by1_loop);
4410     ldrb(tmp0, Address(post(buf, 1)));
4411     subs(len, len, 1);
4412     crc32b(crc, crc, tmp0);
4413     br(Assembler::GT, CRC_by1_loop);
4414     b(L_exit);
4415 
4416   BIND(CRC_by128_pre);
4417     kernel_crc32_common_fold_using_crypto_pmull(crc, buf, len, tmp0, tmp1, tmp2,
4418       4*256*sizeof(juint) + 8*sizeof(juint));
4419     mov(crc, 0);
4420     crc32x(crc, crc, tmp0);
4421     crc32x(crc, crc, tmp1);
4422 
4423     cbnz(len, CRC_less128);
4424 
4425   BIND(L_exit);
4426     mvnw(crc, crc);
4427 }
4428 
4429 void MacroAssembler::kernel_crc32_using_crc32(Register crc, Register buf,
4430         Register len, Register tmp0, Register tmp1, Register tmp2,
4431         Register tmp3) {
4432     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
4433     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
4434 
4435     mvnw(crc, crc);
4436 
4437     subs(len, len, 128);
4438     br(Assembler::GE, CRC_by64_pre);
4439   BIND(CRC_less64);
4440     adds(len, len, 128-32);
4441     br(Assembler::GE, CRC_by32_loop);
4442   BIND(CRC_less32);
4443     adds(len, len, 32-4);
4444     br(Assembler::GE, CRC_by4_loop);
4445     adds(len, len, 4);
4446     br(Assembler::GT, CRC_by1_loop);
4447     b(L_exit);
4448 
4449   BIND(CRC_by32_loop);
4450     ldp(tmp0, tmp1, Address(post(buf, 16)));
4451     subs(len, len, 32);
4452     crc32x(crc, crc, tmp0);
4453     ldr(tmp2, Address(post(buf, 8)));
4454     crc32x(crc, crc, tmp1);
4455     ldr(tmp3, Address(post(buf, 8)));
4456     crc32x(crc, crc, tmp2);
4457     crc32x(crc, crc, tmp3);
4458     br(Assembler::GE, CRC_by32_loop);
4459     cmn(len, (u1)32);
4460     br(Assembler::NE, CRC_less32);
4461     b(L_exit);
4462 
4463   BIND(CRC_by4_loop);
4464     ldrw(tmp0, Address(post(buf, 4)));
4465     subs(len, len, 4);
4466     crc32w(crc, crc, tmp0);
4467     br(Assembler::GE, CRC_by4_loop);
4468     adds(len, len, 4);
4469     br(Assembler::LE, L_exit);
4470   BIND(CRC_by1_loop);
4471     ldrb(tmp0, Address(post(buf, 1)));
4472     subs(len, len, 1);
4473     crc32b(crc, crc, tmp0);
4474     br(Assembler::GT, CRC_by1_loop);
4475     b(L_exit);
4476 
4477   BIND(CRC_by64_pre);
4478     sub(buf, buf, 8);
4479     ldp(tmp0, tmp1, Address(buf, 8));
4480     crc32x(crc, crc, tmp0);
4481     ldr(tmp2, Address(buf, 24));
4482     crc32x(crc, crc, tmp1);
4483     ldr(tmp3, Address(buf, 32));
4484     crc32x(crc, crc, tmp2);
4485     ldr(tmp0, Address(buf, 40));
4486     crc32x(crc, crc, tmp3);
4487     ldr(tmp1, Address(buf, 48));
4488     crc32x(crc, crc, tmp0);
4489     ldr(tmp2, Address(buf, 56));
4490     crc32x(crc, crc, tmp1);
4491     ldr(tmp3, Address(pre(buf, 64)));
4492 
4493     b(CRC_by64_loop);
4494 
4495     align(CodeEntryAlignment);
4496   BIND(CRC_by64_loop);
4497     subs(len, len, 64);
4498     crc32x(crc, crc, tmp2);
4499     ldr(tmp0, Address(buf, 8));
4500     crc32x(crc, crc, tmp3);
4501     ldr(tmp1, Address(buf, 16));
4502     crc32x(crc, crc, tmp0);
4503     ldr(tmp2, Address(buf, 24));
4504     crc32x(crc, crc, tmp1);
4505     ldr(tmp3, Address(buf, 32));
4506     crc32x(crc, crc, tmp2);
4507     ldr(tmp0, Address(buf, 40));
4508     crc32x(crc, crc, tmp3);
4509     ldr(tmp1, Address(buf, 48));
4510     crc32x(crc, crc, tmp0);
4511     ldr(tmp2, Address(buf, 56));
4512     crc32x(crc, crc, tmp1);
4513     ldr(tmp3, Address(pre(buf, 64)));
4514     br(Assembler::GE, CRC_by64_loop);
4515 
4516     // post-loop
4517     crc32x(crc, crc, tmp2);
4518     crc32x(crc, crc, tmp3);
4519 
4520     sub(len, len, 64);
4521     add(buf, buf, 8);
4522     cmn(len, (u1)128);
4523     br(Assembler::NE, CRC_less64);
4524   BIND(L_exit);
4525     mvnw(crc, crc);
4526 }
4527 
4528 /**
4529  * @param crc   register containing existing CRC (32-bit)
4530  * @param buf   register pointing to input byte buffer (byte*)
4531  * @param len   register containing number of bytes
4532  * @param table register that will contain address of CRC table
4533  * @param tmp   scratch register
4534  */
4535 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
4536         Register table0, Register table1, Register table2, Register table3,
4537         Register tmp, Register tmp2, Register tmp3) {
4538   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
4539 
4540   if (UseCryptoPmullForCRC32) {
4541       kernel_crc32_using_crypto_pmull(crc, buf, len, table0, table1, table2, table3);
4542       return;
4543   }
4544 
4545   if (UseCRC32) {
4546       kernel_crc32_using_crc32(crc, buf, len, table0, table1, table2, table3);
4547       return;
4548   }
4549 
4550     mvnw(crc, crc);
4551 
4552     {
4553       uint64_t offset;
4554       adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
4555       add(table0, table0, offset);
4556     }
4557     add(table1, table0, 1*256*sizeof(juint));
4558     add(table2, table0, 2*256*sizeof(juint));
4559     add(table3, table0, 3*256*sizeof(juint));
4560 
4561     { // Neon code start
4562       cmp(len, (u1)64);
4563       br(Assembler::LT, L_by16);
4564       eor(v16, T16B, v16, v16);
4565 
4566     Label L_fold;
4567 
4568       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
4569 
4570       ld1(v0, v1, T2D, post(buf, 32));
4571       ld1r(v4, T2D, post(tmp, 8));
4572       ld1r(v5, T2D, post(tmp, 8));
4573       ld1r(v6, T2D, post(tmp, 8));
4574       ld1r(v7, T2D, post(tmp, 8));
4575       mov(v16, S, 0, crc);
4576 
4577       eor(v0, T16B, v0, v16);
4578       sub(len, len, 64);
4579 
4580     BIND(L_fold);
4581       pmull(v22, T8H, v0, v5, T8B);
4582       pmull(v20, T8H, v0, v7, T8B);
4583       pmull(v23, T8H, v0, v4, T8B);
4584       pmull(v21, T8H, v0, v6, T8B);
4585 
4586       pmull2(v18, T8H, v0, v5, T16B);
4587       pmull2(v16, T8H, v0, v7, T16B);
4588       pmull2(v19, T8H, v0, v4, T16B);
4589       pmull2(v17, T8H, v0, v6, T16B);
4590 
4591       uzp1(v24, T8H, v20, v22);
4592       uzp2(v25, T8H, v20, v22);
4593       eor(v20, T16B, v24, v25);
4594 
4595       uzp1(v26, T8H, v16, v18);
4596       uzp2(v27, T8H, v16, v18);
4597       eor(v16, T16B, v26, v27);
4598 
4599       ushll2(v22, T4S, v20, T8H, 8);
4600       ushll(v20, T4S, v20, T4H, 8);
4601 
4602       ushll2(v18, T4S, v16, T8H, 8);
4603       ushll(v16, T4S, v16, T4H, 8);
4604 
4605       eor(v22, T16B, v23, v22);
4606       eor(v18, T16B, v19, v18);
4607       eor(v20, T16B, v21, v20);
4608       eor(v16, T16B, v17, v16);
4609 
4610       uzp1(v17, T2D, v16, v20);
4611       uzp2(v21, T2D, v16, v20);
4612       eor(v17, T16B, v17, v21);
4613 
4614       ushll2(v20, T2D, v17, T4S, 16);
4615       ushll(v16, T2D, v17, T2S, 16);
4616 
4617       eor(v20, T16B, v20, v22);
4618       eor(v16, T16B, v16, v18);
4619 
4620       uzp1(v17, T2D, v20, v16);
4621       uzp2(v21, T2D, v20, v16);
4622       eor(v28, T16B, v17, v21);
4623 
4624       pmull(v22, T8H, v1, v5, T8B);
4625       pmull(v20, T8H, v1, v7, T8B);
4626       pmull(v23, T8H, v1, v4, T8B);
4627       pmull(v21, T8H, v1, v6, T8B);
4628 
4629       pmull2(v18, T8H, v1, v5, T16B);
4630       pmull2(v16, T8H, v1, v7, T16B);
4631       pmull2(v19, T8H, v1, v4, T16B);
4632       pmull2(v17, T8H, v1, v6, T16B);
4633 
4634       ld1(v0, v1, T2D, post(buf, 32));
4635 
4636       uzp1(v24, T8H, v20, v22);
4637       uzp2(v25, T8H, v20, v22);
4638       eor(v20, T16B, v24, v25);
4639 
4640       uzp1(v26, T8H, v16, v18);
4641       uzp2(v27, T8H, v16, v18);
4642       eor(v16, T16B, v26, v27);
4643 
4644       ushll2(v22, T4S, v20, T8H, 8);
4645       ushll(v20, T4S, v20, T4H, 8);
4646 
4647       ushll2(v18, T4S, v16, T8H, 8);
4648       ushll(v16, T4S, v16, T4H, 8);
4649 
4650       eor(v22, T16B, v23, v22);
4651       eor(v18, T16B, v19, v18);
4652       eor(v20, T16B, v21, v20);
4653       eor(v16, T16B, v17, v16);
4654 
4655       uzp1(v17, T2D, v16, v20);
4656       uzp2(v21, T2D, v16, v20);
4657       eor(v16, T16B, v17, v21);
4658 
4659       ushll2(v20, T2D, v16, T4S, 16);
4660       ushll(v16, T2D, v16, T2S, 16);
4661 
4662       eor(v20, T16B, v22, v20);
4663       eor(v16, T16B, v16, v18);
4664 
4665       uzp1(v17, T2D, v20, v16);
4666       uzp2(v21, T2D, v20, v16);
4667       eor(v20, T16B, v17, v21);
4668 
4669       shl(v16, T2D, v28, 1);
4670       shl(v17, T2D, v20, 1);
4671 
4672       eor(v0, T16B, v0, v16);
4673       eor(v1, T16B, v1, v17);
4674 
4675       subs(len, len, 32);
4676       br(Assembler::GE, L_fold);
4677 
4678       mov(crc, 0);
4679       mov(tmp, v0, D, 0);
4680       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4681       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4682       mov(tmp, v0, D, 1);
4683       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4684       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4685       mov(tmp, v1, D, 0);
4686       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4687       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4688       mov(tmp, v1, D, 1);
4689       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4690       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4691 
4692       add(len, len, 32);
4693     } // Neon code end
4694 
4695   BIND(L_by16);
4696     subs(len, len, 16);
4697     br(Assembler::GE, L_by16_loop);
4698     adds(len, len, 16-4);
4699     br(Assembler::GE, L_by4_loop);
4700     adds(len, len, 4);
4701     br(Assembler::GT, L_by1_loop);
4702     b(L_exit);
4703 
4704   BIND(L_by4_loop);
4705     ldrw(tmp, Address(post(buf, 4)));
4706     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
4707     subs(len, len, 4);
4708     br(Assembler::GE, L_by4_loop);
4709     adds(len, len, 4);
4710     br(Assembler::LE, L_exit);
4711   BIND(L_by1_loop);
4712     subs(len, len, 1);
4713     ldrb(tmp, Address(post(buf, 1)));
4714     update_byte_crc32(crc, tmp, table0);
4715     br(Assembler::GT, L_by1_loop);
4716     b(L_exit);
4717 
4718     align(CodeEntryAlignment);
4719   BIND(L_by16_loop);
4720     subs(len, len, 16);
4721     ldp(tmp, tmp3, Address(post(buf, 16)));
4722     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4723     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4724     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
4725     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
4726     br(Assembler::GE, L_by16_loop);
4727     adds(len, len, 16-4);
4728     br(Assembler::GE, L_by4_loop);
4729     adds(len, len, 4);
4730     br(Assembler::GT, L_by1_loop);
4731   BIND(L_exit);
4732     mvnw(crc, crc);
4733 }
4734 
4735 void MacroAssembler::kernel_crc32c_using_crypto_pmull(Register crc, Register buf,
4736         Register len, Register tmp0, Register tmp1, Register tmp2, Register tmp3) {
4737     Label CRC_by4_loop, CRC_by1_loop, CRC_less128, CRC_by128_pre, CRC_by32_loop, CRC_less32, L_exit;
4738     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
4739 
4740     subs(tmp0, len, 384);
4741     br(Assembler::GE, CRC_by128_pre);
4742   BIND(CRC_less128);
4743     subs(len, len, 32);
4744     br(Assembler::GE, CRC_by32_loop);
4745   BIND(CRC_less32);
4746     adds(len, len, 32 - 4);
4747     br(Assembler::GE, CRC_by4_loop);
4748     adds(len, len, 4);
4749     br(Assembler::GT, CRC_by1_loop);
4750     b(L_exit);
4751 
4752   BIND(CRC_by32_loop);
4753     ldp(tmp0, tmp1, Address(buf));
4754     crc32cx(crc, crc, tmp0);
4755     ldr(tmp2, Address(buf, 16));
4756     crc32cx(crc, crc, tmp1);
4757     ldr(tmp3, Address(buf, 24));
4758     crc32cx(crc, crc, tmp2);
4759     add(buf, buf, 32);
4760     subs(len, len, 32);
4761     crc32cx(crc, crc, tmp3);
4762     br(Assembler::GE, CRC_by32_loop);
4763     cmn(len, (u1)32);
4764     br(Assembler::NE, CRC_less32);
4765     b(L_exit);
4766 
4767   BIND(CRC_by4_loop);
4768     ldrw(tmp0, Address(post(buf, 4)));
4769     subs(len, len, 4);
4770     crc32cw(crc, crc, tmp0);
4771     br(Assembler::GE, CRC_by4_loop);
4772     adds(len, len, 4);
4773     br(Assembler::LE, L_exit);
4774   BIND(CRC_by1_loop);
4775     ldrb(tmp0, Address(post(buf, 1)));
4776     subs(len, len, 1);
4777     crc32cb(crc, crc, tmp0);
4778     br(Assembler::GT, CRC_by1_loop);
4779     b(L_exit);
4780 
4781   BIND(CRC_by128_pre);
4782     kernel_crc32_common_fold_using_crypto_pmull(crc, buf, len, tmp0, tmp1, tmp2,
4783       4*256*sizeof(juint) + 8*sizeof(juint) + 0x50);
4784     mov(crc, 0);
4785     crc32cx(crc, crc, tmp0);
4786     crc32cx(crc, crc, tmp1);
4787 
4788     cbnz(len, CRC_less128);
4789 
4790   BIND(L_exit);
4791 }
4792 
4793 void MacroAssembler::kernel_crc32c_using_crc32c(Register crc, Register buf,
4794         Register len, Register tmp0, Register tmp1, Register tmp2,
4795         Register tmp3) {
4796     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
4797     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
4798 
4799     subs(len, len, 128);
4800     br(Assembler::GE, CRC_by64_pre);
4801   BIND(CRC_less64);
4802     adds(len, len, 128-32);
4803     br(Assembler::GE, CRC_by32_loop);
4804   BIND(CRC_less32);
4805     adds(len, len, 32-4);
4806     br(Assembler::GE, CRC_by4_loop);
4807     adds(len, len, 4);
4808     br(Assembler::GT, CRC_by1_loop);
4809     b(L_exit);
4810 
4811   BIND(CRC_by32_loop);
4812     ldp(tmp0, tmp1, Address(post(buf, 16)));
4813     subs(len, len, 32);
4814     crc32cx(crc, crc, tmp0);
4815     ldr(tmp2, Address(post(buf, 8)));
4816     crc32cx(crc, crc, tmp1);
4817     ldr(tmp3, Address(post(buf, 8)));
4818     crc32cx(crc, crc, tmp2);
4819     crc32cx(crc, crc, tmp3);
4820     br(Assembler::GE, CRC_by32_loop);
4821     cmn(len, (u1)32);
4822     br(Assembler::NE, CRC_less32);
4823     b(L_exit);
4824 
4825   BIND(CRC_by4_loop);
4826     ldrw(tmp0, Address(post(buf, 4)));
4827     subs(len, len, 4);
4828     crc32cw(crc, crc, tmp0);
4829     br(Assembler::GE, CRC_by4_loop);
4830     adds(len, len, 4);
4831     br(Assembler::LE, L_exit);
4832   BIND(CRC_by1_loop);
4833     ldrb(tmp0, Address(post(buf, 1)));
4834     subs(len, len, 1);
4835     crc32cb(crc, crc, tmp0);
4836     br(Assembler::GT, CRC_by1_loop);
4837     b(L_exit);
4838 
4839   BIND(CRC_by64_pre);
4840     sub(buf, buf, 8);
4841     ldp(tmp0, tmp1, Address(buf, 8));
4842     crc32cx(crc, crc, tmp0);
4843     ldr(tmp2, Address(buf, 24));
4844     crc32cx(crc, crc, tmp1);
4845     ldr(tmp3, Address(buf, 32));
4846     crc32cx(crc, crc, tmp2);
4847     ldr(tmp0, Address(buf, 40));
4848     crc32cx(crc, crc, tmp3);
4849     ldr(tmp1, Address(buf, 48));
4850     crc32cx(crc, crc, tmp0);
4851     ldr(tmp2, Address(buf, 56));
4852     crc32cx(crc, crc, tmp1);
4853     ldr(tmp3, Address(pre(buf, 64)));
4854 
4855     b(CRC_by64_loop);
4856 
4857     align(CodeEntryAlignment);
4858   BIND(CRC_by64_loop);
4859     subs(len, len, 64);
4860     crc32cx(crc, crc, tmp2);
4861     ldr(tmp0, Address(buf, 8));
4862     crc32cx(crc, crc, tmp3);
4863     ldr(tmp1, Address(buf, 16));
4864     crc32cx(crc, crc, tmp0);
4865     ldr(tmp2, Address(buf, 24));
4866     crc32cx(crc, crc, tmp1);
4867     ldr(tmp3, Address(buf, 32));
4868     crc32cx(crc, crc, tmp2);
4869     ldr(tmp0, Address(buf, 40));
4870     crc32cx(crc, crc, tmp3);
4871     ldr(tmp1, Address(buf, 48));
4872     crc32cx(crc, crc, tmp0);
4873     ldr(tmp2, Address(buf, 56));
4874     crc32cx(crc, crc, tmp1);
4875     ldr(tmp3, Address(pre(buf, 64)));
4876     br(Assembler::GE, CRC_by64_loop);
4877 
4878     // post-loop
4879     crc32cx(crc, crc, tmp2);
4880     crc32cx(crc, crc, tmp3);
4881 
4882     sub(len, len, 64);
4883     add(buf, buf, 8);
4884     cmn(len, (u1)128);
4885     br(Assembler::NE, CRC_less64);
4886   BIND(L_exit);
4887 }
4888 
4889 /**
4890  * @param crc   register containing existing CRC (32-bit)
4891  * @param buf   register pointing to input byte buffer (byte*)
4892  * @param len   register containing number of bytes
4893  * @param table register that will contain address of CRC table
4894  * @param tmp   scratch register
4895  */
4896 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
4897         Register table0, Register table1, Register table2, Register table3,
4898         Register tmp, Register tmp2, Register tmp3) {
4899   if (UseCryptoPmullForCRC32) {
4900     kernel_crc32c_using_crypto_pmull(crc, buf, len, table0, table1, table2, table3);
4901   } else {
4902     kernel_crc32c_using_crc32c(crc, buf, len, table0, table1, table2, table3);
4903   }
4904 }
4905 
4906 void MacroAssembler::kernel_crc32_common_fold_using_crypto_pmull(Register crc, Register buf,
4907         Register len, Register tmp0, Register tmp1, Register tmp2, size_t table_offset) {
4908     Label CRC_by128_loop;
4909     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
4910 
4911     sub(len, len, 256);
4912     Register table = tmp0;
4913     {
4914       uint64_t offset;
4915       adrp(table, ExternalAddress(StubRoutines::crc_table_addr()), offset);
4916       add(table, table, offset);
4917     }
4918     add(table, table, table_offset);
4919 
4920     // Registers v0..v7 are used as data registers.
4921     // Registers v16..v31 are used as tmp registers.
4922     sub(buf, buf, 0x10);
4923     ldrq(v0, Address(buf, 0x10));
4924     ldrq(v1, Address(buf, 0x20));
4925     ldrq(v2, Address(buf, 0x30));
4926     ldrq(v3, Address(buf, 0x40));
4927     ldrq(v4, Address(buf, 0x50));
4928     ldrq(v5, Address(buf, 0x60));
4929     ldrq(v6, Address(buf, 0x70));
4930     ldrq(v7, Address(pre(buf, 0x80)));
4931 
4932     movi(v31, T4S, 0);
4933     mov(v31, S, 0, crc);
4934     eor(v0, T16B, v0, v31);
4935 
4936     // Register v16 contains constants from the crc table.
4937     ldrq(v16, Address(table));
4938     b(CRC_by128_loop);
4939 
4940     align(OptoLoopAlignment);
4941   BIND(CRC_by128_loop);
4942     pmull (v17,  T1Q, v0, v16, T1D);
4943     pmull2(v18, T1Q, v0, v16, T2D);
4944     ldrq(v0, Address(buf, 0x10));
4945     eor3(v0, T16B, v17,  v18, v0);
4946 
4947     pmull (v19, T1Q, v1, v16, T1D);
4948     pmull2(v20, T1Q, v1, v16, T2D);
4949     ldrq(v1, Address(buf, 0x20));
4950     eor3(v1, T16B, v19, v20, v1);
4951 
4952     pmull (v21, T1Q, v2, v16, T1D);
4953     pmull2(v22, T1Q, v2, v16, T2D);
4954     ldrq(v2, Address(buf, 0x30));
4955     eor3(v2, T16B, v21, v22, v2);
4956 
4957     pmull (v23, T1Q, v3, v16, T1D);
4958     pmull2(v24, T1Q, v3, v16, T2D);
4959     ldrq(v3, Address(buf, 0x40));
4960     eor3(v3, T16B, v23, v24, v3);
4961 
4962     pmull (v25, T1Q, v4, v16, T1D);
4963     pmull2(v26, T1Q, v4, v16, T2D);
4964     ldrq(v4, Address(buf, 0x50));
4965     eor3(v4, T16B, v25, v26, v4);
4966 
4967     pmull (v27, T1Q, v5, v16, T1D);
4968     pmull2(v28, T1Q, v5, v16, T2D);
4969     ldrq(v5, Address(buf, 0x60));
4970     eor3(v5, T16B, v27, v28, v5);
4971 
4972     pmull (v29, T1Q, v6, v16, T1D);
4973     pmull2(v30, T1Q, v6, v16, T2D);
4974     ldrq(v6, Address(buf, 0x70));
4975     eor3(v6, T16B, v29, v30, v6);
4976 
4977     // Reuse registers v23, v24.
4978     // Using them won't block the first instruction of the next iteration.
4979     pmull (v23, T1Q, v7, v16, T1D);
4980     pmull2(v24, T1Q, v7, v16, T2D);
4981     ldrq(v7, Address(pre(buf, 0x80)));
4982     eor3(v7, T16B, v23, v24, v7);
4983 
4984     subs(len, len, 0x80);
4985     br(Assembler::GE, CRC_by128_loop);
4986 
4987     // fold into 512 bits
4988     // Use v31 for constants because v16 can be still in use.
4989     ldrq(v31, Address(table, 0x10));
4990 
4991     pmull (v17,  T1Q, v0, v31, T1D);
4992     pmull2(v18, T1Q, v0, v31, T2D);
4993     eor3(v0, T16B, v17, v18, v4);
4994 
4995     pmull (v19, T1Q, v1, v31, T1D);
4996     pmull2(v20, T1Q, v1, v31, T2D);
4997     eor3(v1, T16B, v19, v20, v5);
4998 
4999     pmull (v21, T1Q, v2, v31, T1D);
5000     pmull2(v22, T1Q, v2, v31, T2D);
5001     eor3(v2, T16B, v21, v22, v6);
5002 
5003     pmull (v23, T1Q, v3, v31, T1D);
5004     pmull2(v24, T1Q, v3, v31, T2D);
5005     eor3(v3, T16B, v23, v24, v7);
5006 
5007     // fold into 128 bits
5008     // Use v17 for constants because v31 can be still in use.
5009     ldrq(v17, Address(table, 0x20));
5010     pmull (v25, T1Q, v0, v17, T1D);
5011     pmull2(v26, T1Q, v0, v17, T2D);
5012     eor3(v3, T16B, v3, v25, v26);
5013 
5014     // Use v18 for constants because v17 can be still in use.
5015     ldrq(v18, Address(table, 0x30));
5016     pmull (v27, T1Q, v1, v18, T1D);
5017     pmull2(v28, T1Q, v1, v18, T2D);
5018     eor3(v3, T16B, v3, v27, v28);
5019 
5020     // Use v19 for constants because v18 can be still in use.
5021     ldrq(v19, Address(table, 0x40));
5022     pmull (v29, T1Q, v2, v19, T1D);
5023     pmull2(v30, T1Q, v2, v19, T2D);
5024     eor3(v0, T16B, v3, v29, v30);
5025 
5026     add(len, len, 0x80);
5027     add(buf, buf, 0x10);
5028 
5029     mov(tmp0, v0, D, 0);
5030     mov(tmp1, v0, D, 1);
5031 }
5032 
5033 void MacroAssembler::addptr(const Address &dst, int32_t src) {
5034   Address adr;
5035   switch(dst.getMode()) {
5036   case Address::base_plus_offset:
5037     // This is the expected mode, although we allow all the other
5038     // forms below.
5039     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
5040     break;
5041   default:
5042     lea(rscratch2, dst);
5043     adr = Address(rscratch2);
5044     break;
5045   }
5046   ldr(rscratch1, adr);
5047   add(rscratch1, rscratch1, src);
5048   str(rscratch1, adr);
5049 }
5050 
5051 void MacroAssembler::cmpptr(Register src1, Address src2) {
5052   uint64_t offset;
5053   adrp(rscratch1, src2, offset);
5054   ldr(rscratch1, Address(rscratch1, offset));
5055   cmp(src1, rscratch1);
5056 }
5057 
5058 void MacroAssembler::cmpoop(Register obj1, Register obj2) {
5059   cmp(obj1, obj2);
5060 }
5061 
5062 void MacroAssembler::load_method_holder_cld(Register rresult, Register rmethod) {
5063   load_method_holder(rresult, rmethod);
5064   ldr(rresult, Address(rresult, InstanceKlass::class_loader_data_offset()));
5065 }
5066 
5067 void MacroAssembler::load_method_holder(Register holder, Register method) {
5068   ldr(holder, Address(method, Method::const_offset()));                      // ConstMethod*
5069   ldr(holder, Address(holder, ConstMethod::constants_offset()));             // ConstantPool*
5070   ldr(holder, Address(holder, ConstantPool::pool_holder_offset()));          // InstanceKlass*
5071 }
5072 
5073 // Loads the obj's Klass* into dst.
5074 // Preserves all registers (incl src, rscratch1 and rscratch2).
5075 // Input:
5076 // src - the oop we want to load the klass from.
5077 // dst - output narrow klass.
5078 void MacroAssembler::load_narrow_klass_compact(Register dst, Register src) {
5079   assert(UseCompactObjectHeaders, "expects UseCompactObjectHeaders");
5080   ldr(dst, Address(src, oopDesc::mark_offset_in_bytes()));
5081   lsr(dst, dst, markWord::klass_shift);
5082 }
5083 
5084 void MacroAssembler::load_klass(Register dst, Register src) {
5085   if (UseCompactObjectHeaders) {
5086     load_narrow_klass_compact(dst, src);
5087   } else {
5088     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5089   }
5090   decode_klass_not_null(dst);
5091 }
5092 
5093 void MacroAssembler::restore_cpu_control_state_after_jni(Register tmp1, Register tmp2) {
5094   if (RestoreMXCSROnJNICalls) {
5095     Label OK;
5096     get_fpcr(tmp1);
5097     mov(tmp2, tmp1);
5098     // Set FPCR to the state we need. We do want Round to Nearest. We
5099     // don't want non-IEEE rounding modes or floating-point traps.
5100     bfi(tmp1, zr, 22, 4); // Clear DN, FZ, and Rmode
5101     bfi(tmp1, zr, 8, 5);  // Clear exception-control bits (8-12)
5102     bfi(tmp1, zr, 0, 2);  // Clear AH:FIZ
5103     eor(tmp2, tmp1, tmp2);
5104     cbz(tmp2, OK);        // Only reset FPCR if it's wrong
5105     set_fpcr(tmp1);
5106     bind(OK);
5107   }
5108 }
5109 
5110 // ((OopHandle)result).resolve();
5111 void MacroAssembler::resolve_oop_handle(Register result, Register tmp1, Register tmp2) {
5112   // OopHandle::resolve is an indirection.
5113   access_load_at(T_OBJECT, IN_NATIVE, result, Address(result, 0), tmp1, tmp2);
5114 }
5115 
5116 // ((WeakHandle)result).resolve();
5117 void MacroAssembler::resolve_weak_handle(Register result, Register tmp1, Register tmp2) {
5118   assert_different_registers(result, tmp1, tmp2);
5119   Label resolved;
5120 
5121   // A null weak handle resolves to null.
5122   cbz(result, resolved);
5123 
5124   // Only 64 bit platforms support GCs that require a tmp register
5125   // WeakHandle::resolve is an indirection like jweak.
5126   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
5127                  result, Address(result), tmp1, tmp2);
5128   bind(resolved);
5129 }
5130 
5131 void MacroAssembler::load_mirror(Register dst, Register method, Register tmp1, Register tmp2) {
5132   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
5133   ldr(dst, Address(rmethod, Method::const_offset()));
5134   ldr(dst, Address(dst, ConstMethod::constants_offset()));
5135   ldr(dst, Address(dst, ConstantPool::pool_holder_offset()));
5136   ldr(dst, Address(dst, mirror_offset));
5137   resolve_oop_handle(dst, tmp1, tmp2);
5138 }
5139 
5140 void MacroAssembler::cmp_klass(Register obj, Register klass, Register tmp) {
5141   assert_different_registers(obj, klass, tmp);
5142   if (UseCompactObjectHeaders) {
5143     load_narrow_klass_compact(tmp, obj);
5144   } else {
5145     ldrw(tmp, Address(obj, oopDesc::klass_offset_in_bytes()));
5146   }
5147   if (CompressedKlassPointers::base() == nullptr) {
5148     cmp(klass, tmp, LSL, CompressedKlassPointers::shift());
5149     return;
5150   } else if (!AOTCodeCache::is_on_for_dump() &&
5151              ((uint64_t)CompressedKlassPointers::base() & 0xffffffff) == 0
5152              && CompressedKlassPointers::shift() == 0) {
5153     // Only the bottom 32 bits matter
5154     cmpw(klass, tmp);
5155     return;
5156   }
5157   decode_klass_not_null(tmp);
5158   cmp(klass, tmp);
5159 }
5160 
5161 void MacroAssembler::cmp_klasses_from_objects(Register obj1, Register obj2, Register tmp1, Register tmp2) {
5162   if (UseCompactObjectHeaders) {
5163     load_narrow_klass_compact(tmp1, obj1);
5164     load_narrow_klass_compact(tmp2,  obj2);
5165   } else {
5166     ldrw(tmp1, Address(obj1, oopDesc::klass_offset_in_bytes()));
5167     ldrw(tmp2, Address(obj2, oopDesc::klass_offset_in_bytes()));
5168   }
5169   cmpw(tmp1, tmp2);
5170 }
5171 
5172 void MacroAssembler::store_klass(Register dst, Register src) {
5173   // FIXME: Should this be a store release?  concurrent gcs assumes
5174   // klass length is valid if klass field is not null.
5175   assert(!UseCompactObjectHeaders, "not with compact headers");
5176   encode_klass_not_null(src);
5177   strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
5178 }
5179 
5180 void MacroAssembler::store_klass_gap(Register dst, Register src) {
5181   assert(!UseCompactObjectHeaders, "not with compact headers");
5182   // Store to klass gap in destination
5183   strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
5184 }
5185 
5186 // Algorithm must match CompressedOops::encode.
5187 void MacroAssembler::encode_heap_oop(Register d, Register s) {
5188 #ifdef ASSERT
5189   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
5190 #endif
5191   verify_oop_msg(s, "broken oop in encode_heap_oop");
5192   if (CompressedOops::base() == nullptr) {
5193     if (CompressedOops::shift() != 0) {
5194       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5195       lsr(d, s, LogMinObjAlignmentInBytes);
5196     } else {
5197       mov(d, s);
5198     }
5199   } else {
5200     subs(d, s, rheapbase);
5201     csel(d, d, zr, Assembler::HS);
5202     lsr(d, d, LogMinObjAlignmentInBytes);
5203 
5204     /*  Old algorithm: is this any worse?
5205     Label nonnull;
5206     cbnz(r, nonnull);
5207     sub(r, r, rheapbase);
5208     bind(nonnull);
5209     lsr(r, r, LogMinObjAlignmentInBytes);
5210     */
5211   }
5212 }
5213 
5214 void MacroAssembler::encode_heap_oop_not_null(Register r) {
5215 #ifdef ASSERT
5216   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
5217   if (CheckCompressedOops) {
5218     Label ok;
5219     cbnz(r, ok);
5220     stop("null oop passed to encode_heap_oop_not_null");
5221     bind(ok);
5222   }
5223 #endif
5224   verify_oop_msg(r, "broken oop in encode_heap_oop_not_null");
5225   if (CompressedOops::base() != nullptr) {
5226     sub(r, r, rheapbase);
5227   }
5228   if (CompressedOops::shift() != 0) {
5229     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5230     lsr(r, r, LogMinObjAlignmentInBytes);
5231   }
5232 }
5233 
5234 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
5235 #ifdef ASSERT
5236   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
5237   if (CheckCompressedOops) {
5238     Label ok;
5239     cbnz(src, ok);
5240     stop("null oop passed to encode_heap_oop_not_null2");
5241     bind(ok);
5242   }
5243 #endif
5244   verify_oop_msg(src, "broken oop in encode_heap_oop_not_null2");
5245 
5246   Register data = src;
5247   if (CompressedOops::base() != nullptr) {
5248     sub(dst, src, rheapbase);
5249     data = dst;
5250   }
5251   if (CompressedOops::shift() != 0) {
5252     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5253     lsr(dst, data, LogMinObjAlignmentInBytes);
5254     data = dst;
5255   }
5256   if (data == src)
5257     mov(dst, src);
5258 }
5259 
5260 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
5261 #ifdef ASSERT
5262   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
5263 #endif
5264   if (CompressedOops::base() == nullptr) {
5265     if (CompressedOops::shift() != 0) {
5266       lsl(d, s, CompressedOops::shift());
5267     } else if (d != s) {
5268       mov(d, s);
5269     }
5270   } else {
5271     Label done;
5272     if (d != s)
5273       mov(d, s);
5274     cbz(s, done);
5275     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
5276     bind(done);
5277   }
5278   verify_oop_msg(d, "broken oop in decode_heap_oop");
5279 }
5280 
5281 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
5282   assert (UseCompressedOops, "should only be used for compressed headers");
5283   assert (Universe::heap() != nullptr, "java heap should be initialized");
5284   // Cannot assert, unverified entry point counts instructions (see .ad file)
5285   // vtableStubs also counts instructions in pd_code_size_limit.
5286   // Also do not verify_oop as this is called by verify_oop.
5287   if (CompressedOops::shift() != 0) {
5288     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5289     if (CompressedOops::base() != nullptr) {
5290       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
5291     } else {
5292       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
5293     }
5294   } else {
5295     assert (CompressedOops::base() == nullptr, "sanity");
5296   }
5297 }
5298 
5299 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
5300   assert (UseCompressedOops, "should only be used for compressed headers");
5301   assert (Universe::heap() != nullptr, "java heap should be initialized");
5302   // Cannot assert, unverified entry point counts instructions (see .ad file)
5303   // vtableStubs also counts instructions in pd_code_size_limit.
5304   // Also do not verify_oop as this is called by verify_oop.
5305   if (CompressedOops::shift() != 0) {
5306     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5307     if (CompressedOops::base() != nullptr) {
5308       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
5309     } else {
5310       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
5311     }
5312   } else {
5313     assert (CompressedOops::base() == nullptr, "sanity");
5314     if (dst != src) {
5315       mov(dst, src);
5316     }
5317   }
5318 }
5319 
5320 MacroAssembler::KlassDecodeMode MacroAssembler::_klass_decode_mode(KlassDecodeNone);
5321 
5322 MacroAssembler::KlassDecodeMode MacroAssembler::klass_decode_mode() {
5323   assert(Metaspace::initialized(), "metaspace not initialized yet");
5324   assert(_klass_decode_mode != KlassDecodeNone, "should be initialized");
5325   return _klass_decode_mode;
5326 }
5327 
5328 MacroAssembler::KlassDecodeMode  MacroAssembler::klass_decode_mode(address base, int shift, const size_t range) {
5329   // KlassDecodeMode shouldn't be set already.
5330   assert(_klass_decode_mode == KlassDecodeNone, "set once");
5331 
5332   if (base == nullptr) {
5333     return KlassDecodeZero;
5334   }
5335 
5336   if (operand_valid_for_logical_immediate(
5337         /*is32*/false, (uint64_t)base)) {
5338     const uint64_t range_mask = right_n_bits(log2i_ceil(range));
5339     if (((uint64_t)base & range_mask) == 0) {
5340       return KlassDecodeXor;
5341     }
5342   }
5343 
5344   const uint64_t shifted_base =
5345     (uint64_t)base >> shift;
5346   if ((shifted_base & 0xffff0000ffffffff) == 0) {
5347     return KlassDecodeMovk;
5348   }
5349 
5350   // No valid encoding.
5351   return KlassDecodeNone;
5352 }
5353 
5354 // Check if one of the above decoding modes will work for given base, shift and range.
5355 bool MacroAssembler::check_klass_decode_mode(address base, int shift, const size_t range) {
5356   return klass_decode_mode(base, shift, range) != KlassDecodeNone;
5357 }
5358 
5359 bool MacroAssembler::set_klass_decode_mode(address base, int shift, const size_t range) {
5360   _klass_decode_mode = klass_decode_mode(base, shift, range);
5361   return _klass_decode_mode != KlassDecodeNone;
5362 }
5363 
5364 static Register pick_different_tmp(Register dst, Register src) {
5365   auto tmps = RegSet::of(r0, r1, r2) - RegSet::of(src, dst);
5366   return *tmps.begin();
5367 }
5368 
5369 void MacroAssembler::encode_klass_not_null_for_aot(Register dst, Register src) {
5370   // we have to load the klass base from the AOT constants area but
5371   // not the shift because it is not allowed to change
5372   int shift = CompressedKlassPointers::shift();
5373   assert(shift >= 0 && shift <= CompressedKlassPointers::max_shift(), "unexpected compressed klass shift!");
5374   if (dst != src) {
5375     // we can load the base into dst, subtract it formthe src and shift down
5376     lea(dst, ExternalAddress(CompressedKlassPointers::base_addr()));
5377     ldr(dst, dst);
5378     sub(dst, src, dst);
5379     lsr(dst, dst, shift);
5380   } else {
5381     // we need an extra register in order to load the coop base
5382     Register tmp = pick_different_tmp(dst, src);
5383     RegSet regs = RegSet::of(tmp);
5384     push(regs, sp);
5385     lea(tmp, ExternalAddress(CompressedKlassPointers::base_addr()));
5386     ldr(tmp, tmp);
5387     sub(dst, src, tmp);
5388     lsr(dst, dst, shift);
5389     pop(regs, sp);
5390   }
5391 }
5392 
5393 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
5394   if (CompressedKlassPointers::base() != nullptr && AOTCodeCache::is_on_for_dump()) {
5395     encode_klass_not_null_for_aot(dst, src);
5396     return;
5397   }
5398 
5399   switch (klass_decode_mode()) {
5400   case KlassDecodeZero:
5401     if (CompressedKlassPointers::shift() != 0) {
5402       lsr(dst, src, CompressedKlassPointers::shift());
5403     } else {
5404       if (dst != src) mov(dst, src);
5405     }
5406     break;
5407 
5408   case KlassDecodeXor:
5409     if (CompressedKlassPointers::shift() != 0) {
5410       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5411       lsr(dst, dst, CompressedKlassPointers::shift());
5412     } else {
5413       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5414     }
5415     break;
5416 
5417   case KlassDecodeMovk:
5418     if (CompressedKlassPointers::shift() != 0) {
5419       ubfx(dst, src, CompressedKlassPointers::shift(), 32);
5420     } else {
5421       movw(dst, src);
5422     }
5423     break;
5424 
5425   case KlassDecodeNone:
5426     ShouldNotReachHere();
5427     break;
5428   }
5429 }
5430 
5431 void MacroAssembler::encode_klass_not_null(Register r) {
5432   encode_klass_not_null(r, r);
5433 }
5434 
5435 void MacroAssembler::decode_klass_not_null_for_aot(Register dst, Register src) {
5436   // we have to load the klass base from the AOT constants area but
5437   // not the shift because it is not allowed to change
5438   int shift = CompressedKlassPointers::shift();
5439   assert(shift >= 0 && shift <= CompressedKlassPointers::max_shift(), "unexpected compressed klass shift!");
5440   if (dst != src) {
5441     // we can load the base into dst then add the offset with a suitable shift
5442     lea(dst, ExternalAddress(CompressedKlassPointers::base_addr()));
5443     ldr(dst, dst);
5444     add(dst, dst, src, LSL,  shift);
5445   } else {
5446     // we need an extra register in order to load the coop base
5447     Register tmp = pick_different_tmp(dst, src);
5448     RegSet regs = RegSet::of(tmp);
5449     push(regs, sp);
5450     lea(tmp, ExternalAddress(CompressedKlassPointers::base_addr()));
5451     ldr(tmp, tmp);
5452     add(dst, tmp,  src, LSL,  shift);
5453     pop(regs, sp);
5454   }
5455 }
5456 
5457 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
5458   if (AOTCodeCache::is_on_for_dump()) {
5459     decode_klass_not_null_for_aot(dst, src);
5460     return;
5461   }
5462 
5463   switch (klass_decode_mode()) {
5464   case KlassDecodeZero:
5465     if (CompressedKlassPointers::shift() != 0) {
5466       lsl(dst, src, CompressedKlassPointers::shift());
5467     } else {
5468       if (dst != src) mov(dst, src);
5469     }
5470     break;
5471 
5472   case KlassDecodeXor:
5473     if (CompressedKlassPointers::shift() != 0) {
5474       lsl(dst, src, CompressedKlassPointers::shift());
5475       eor(dst, dst, (uint64_t)CompressedKlassPointers::base());
5476     } else {
5477       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5478     }
5479     break;
5480 
5481   case KlassDecodeMovk: {
5482     const uint64_t shifted_base =
5483       (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
5484 
5485     if (dst != src) movw(dst, src);
5486     movk(dst, shifted_base >> 32, 32);
5487 
5488     if (CompressedKlassPointers::shift() != 0) {
5489       lsl(dst, dst, CompressedKlassPointers::shift());
5490     }
5491 
5492     break;
5493   }
5494 
5495   case KlassDecodeNone:
5496     ShouldNotReachHere();
5497     break;
5498   }
5499 }
5500 
5501 void  MacroAssembler::decode_klass_not_null(Register r) {
5502   decode_klass_not_null(r, r);
5503 }
5504 
5505 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
5506 #ifdef ASSERT
5507   {
5508     ThreadInVMfromUnknown tiv;
5509     assert (UseCompressedOops, "should only be used for compressed oops");
5510     assert (Universe::heap() != nullptr, "java heap should be initialized");
5511     assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5512     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
5513   }
5514 #endif
5515   int oop_index = oop_recorder()->find_index(obj);
5516   InstructionMark im(this);
5517   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5518   code_section()->relocate(inst_mark(), rspec);
5519   movz(dst, 0xDEAD, 16);
5520   movk(dst, 0xBEEF);
5521 }
5522 
5523 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
5524   assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5525   int index = oop_recorder()->find_index(k);
5526 
5527   InstructionMark im(this);
5528   RelocationHolder rspec = metadata_Relocation::spec(index);
5529   code_section()->relocate(inst_mark(), rspec);
5530   narrowKlass nk = CompressedKlassPointers::encode(k);
5531   movz(dst, (nk >> 16), 16);
5532   movk(dst, nk & 0xffff);
5533 }
5534 
5535 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators,
5536                                     Register dst, Address src,
5537                                     Register tmp1, Register tmp2) {
5538   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5539   decorators = AccessInternal::decorator_fixup(decorators, type);
5540   bool as_raw = (decorators & AS_RAW) != 0;
5541   if (as_raw) {
5542     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, tmp2);
5543   } else {
5544     bs->load_at(this, decorators, type, dst, src, tmp1, tmp2);
5545   }
5546 }
5547 
5548 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators,
5549                                      Address dst, Register val,
5550                                      Register tmp1, Register tmp2, Register tmp3) {
5551   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5552   decorators = AccessInternal::decorator_fixup(decorators, type);
5553   bool as_raw = (decorators & AS_RAW) != 0;
5554   if (as_raw) {
5555     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
5556   } else {
5557     bs->store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
5558   }
5559 }
5560 
5561 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
5562                                    Register tmp2, DecoratorSet decorators) {
5563   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
5564 }
5565 
5566 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
5567                                             Register tmp2, DecoratorSet decorators) {
5568   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, tmp2);
5569 }
5570 
5571 void MacroAssembler::store_heap_oop(Address dst, Register val, Register tmp1,
5572                                     Register tmp2, Register tmp3, DecoratorSet decorators) {
5573   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, val, tmp1, tmp2, tmp3);
5574 }
5575 
5576 // Used for storing nulls.
5577 void MacroAssembler::store_heap_oop_null(Address dst) {
5578   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg, noreg);
5579 }
5580 
5581 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
5582   assert(oop_recorder() != nullptr, "this assembler needs a Recorder");
5583   int index = oop_recorder()->allocate_metadata_index(obj);
5584   RelocationHolder rspec = metadata_Relocation::spec(index);
5585   return Address((address)obj, rspec);
5586 }
5587 
5588 // Move an oop into a register.
5589 void MacroAssembler::movoop(Register dst, jobject obj) {
5590   int oop_index;
5591   if (obj == nullptr) {
5592     oop_index = oop_recorder()->allocate_oop_index(obj);
5593   } else {
5594 #ifdef ASSERT
5595     {
5596       ThreadInVMfromUnknown tiv;
5597       assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
5598     }
5599 #endif
5600     oop_index = oop_recorder()->find_index(obj);
5601   }
5602   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5603 
5604   if (BarrierSet::barrier_set()->barrier_set_assembler()->supports_instruction_patching()) {
5605     mov(dst, Address((address)obj, rspec));
5606   } else {
5607     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
5608     ldr(dst, Address(dummy, rspec));
5609   }
5610 }
5611 
5612 // Move a metadata address into a register.
5613 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
5614   int oop_index;
5615   if (obj == nullptr) {
5616     oop_index = oop_recorder()->allocate_metadata_index(obj);
5617   } else {
5618     oop_index = oop_recorder()->find_index(obj);
5619   }
5620   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
5621   mov(dst, Address((address)obj, rspec));
5622 }
5623 
5624 Address MacroAssembler::constant_oop_address(jobject obj) {
5625 #ifdef ASSERT
5626   {
5627     ThreadInVMfromUnknown tiv;
5628     assert(oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5629     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "not an oop");
5630   }
5631 #endif
5632   int oop_index = oop_recorder()->find_index(obj);
5633   return Address((address)obj, oop_Relocation::spec(oop_index));
5634 }
5635 
5636 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5637 void MacroAssembler::tlab_allocate(Register obj,
5638                                    Register var_size_in_bytes,
5639                                    int con_size_in_bytes,
5640                                    Register t1,
5641                                    Register t2,
5642                                    Label& slow_case) {
5643   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5644   bs->tlab_allocate(this, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
5645 }
5646 
5647 void MacroAssembler::verify_tlab() {
5648 #ifdef ASSERT
5649   if (UseTLAB && VerifyOops) {
5650     Label next, ok;
5651 
5652     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
5653 
5654     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
5655     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
5656     cmp(rscratch2, rscratch1);
5657     br(Assembler::HS, next);
5658     STOP("assert(top >= start)");
5659     should_not_reach_here();
5660 
5661     bind(next);
5662     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
5663     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
5664     cmp(rscratch2, rscratch1);
5665     br(Assembler::HS, ok);
5666     STOP("assert(top <= end)");
5667     should_not_reach_here();
5668 
5669     bind(ok);
5670     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
5671   }
5672 #endif
5673 }
5674 
5675 // Writes to stack successive pages until offset reached to check for
5676 // stack overflow + shadow pages.  This clobbers tmp.
5677 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
5678   assert_different_registers(tmp, size, rscratch1);
5679   mov(tmp, sp);
5680   // Bang stack for total size given plus shadow page size.
5681   // Bang one page at a time because large size can bang beyond yellow and
5682   // red zones.
5683   Label loop;
5684   mov(rscratch1, (int)os::vm_page_size());
5685   bind(loop);
5686   lea(tmp, Address(tmp, -(int)os::vm_page_size()));
5687   subsw(size, size, rscratch1);
5688   str(size, Address(tmp));
5689   br(Assembler::GT, loop);
5690 
5691   // Bang down shadow pages too.
5692   // At this point, (tmp-0) is the last address touched, so don't
5693   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
5694   // was post-decremented.)  Skip this address by starting at i=1, and
5695   // touch a few more pages below.  N.B.  It is important to touch all
5696   // the way down to and including i=StackShadowPages.
5697   for (int i = 0; i < (int)(StackOverflow::stack_shadow_zone_size() / (int)os::vm_page_size()) - 1; i++) {
5698     // this could be any sized move but this is can be a debugging crumb
5699     // so the bigger the better.
5700     lea(tmp, Address(tmp, -(int)os::vm_page_size()));
5701     str(size, Address(tmp));
5702   }
5703 }
5704 
5705 // Move the address of the polling page into dest.
5706 void MacroAssembler::get_polling_page(Register dest, relocInfo::relocType rtype) {
5707   ldr(dest, Address(rthread, JavaThread::polling_page_offset()));
5708 }
5709 
5710 // Read the polling page.  The address of the polling page must
5711 // already be in r.
5712 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
5713   address mark;
5714   {
5715     InstructionMark im(this);
5716     code_section()->relocate(inst_mark(), rtype);
5717     ldrw(zr, Address(r, 0));
5718     mark = inst_mark();
5719   }
5720   verify_cross_modify_fence_not_required();
5721   return mark;
5722 }
5723 
5724 void MacroAssembler::adrp(Register reg1, const Address &dest, uint64_t &byte_offset) {
5725   uint64_t low_page = (uint64_t)CodeCache::low_bound() >> 12;
5726   uint64_t high_page = (uint64_t)(CodeCache::high_bound()-1) >> 12;
5727   uint64_t dest_page = (uint64_t)dest.target() >> 12;
5728   int64_t offset_low = dest_page - low_page;
5729   int64_t offset_high = dest_page - high_page;
5730 
5731   assert(is_valid_AArch64_address(dest.target()), "bad address");
5732   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
5733 
5734   InstructionMark im(this);
5735   code_section()->relocate(inst_mark(), dest.rspec());
5736   // 8143067: Ensure that the adrp can reach the dest from anywhere within
5737   // the code cache so that if it is relocated we know it will still reach
5738   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
5739     _adrp(reg1, dest.target());
5740   } else {
5741     uint64_t target = (uint64_t)dest.target();
5742     uint64_t adrp_target
5743       = (target & 0xffffffffULL) | ((uint64_t)pc() & 0xffff00000000ULL);
5744 
5745     _adrp(reg1, (address)adrp_target);
5746     movk(reg1, target >> 32, 32);
5747   }
5748   byte_offset = (uint64_t)dest.target() & 0xfff;
5749 }
5750 
5751 void MacroAssembler::load_byte_map_base(Register reg) {
5752 #if INCLUDE_CDS
5753   if (AOTCodeCache::is_on_for_dump()) {
5754     address byte_map_base_adr = AOTRuntimeConstants::card_table_base_address();
5755     lea(reg, ExternalAddress(byte_map_base_adr));
5756     ldr(reg, Address(reg));
5757     return;
5758   }
5759 #endif
5760   CardTableBarrierSet* ctbs = CardTableBarrierSet::barrier_set();
5761 
5762   // Strictly speaking the card table base isn't an address at all, and it might
5763   // even be negative. It is thus materialised as a constant.
5764   mov(reg, (uint64_t)ctbs->card_table_base_const());
5765 }
5766 
5767 void MacroAssembler::load_aotrc_address(Register reg, address a) {
5768 #if INCLUDE_CDS
5769   assert(AOTRuntimeConstants::contains(a), "address out of range for data area");
5770   if (AOTCodeCache::is_on_for_dump()) {
5771     // all aotrc field addresses should be registered in the AOTCodeCache address table
5772     lea(reg, ExternalAddress(a));
5773   } else {
5774     mov(reg, (uint64_t)a);
5775   }
5776 #else
5777   ShouldNotReachHere();
5778 #endif
5779 }
5780 
5781 void MacroAssembler::build_frame(int framesize) {
5782   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
5783   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
5784   protect_return_address();
5785   if (framesize < ((1 << 9) + 2 * wordSize)) {
5786     sub(sp, sp, framesize);
5787     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
5788     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
5789   } else {
5790     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
5791     if (PreserveFramePointer) mov(rfp, sp);
5792     if (framesize < ((1 << 12) + 2 * wordSize))
5793       sub(sp, sp, framesize - 2 * wordSize);
5794     else {
5795       mov(rscratch1, framesize - 2 * wordSize);
5796       sub(sp, sp, rscratch1);
5797     }
5798   }
5799   verify_cross_modify_fence_not_required();
5800 }
5801 
5802 void MacroAssembler::remove_frame(int framesize) {
5803   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
5804   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
5805   if (framesize < ((1 << 9) + 2 * wordSize)) {
5806     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
5807     add(sp, sp, framesize);
5808   } else {
5809     if (framesize < ((1 << 12) + 2 * wordSize))
5810       add(sp, sp, framesize - 2 * wordSize);
5811     else {
5812       mov(rscratch1, framesize - 2 * wordSize);
5813       add(sp, sp, rscratch1);
5814     }
5815     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
5816   }
5817   authenticate_return_address();
5818 }
5819 
5820 
5821 // This method counts leading positive bytes (highest bit not set) in provided byte array
5822 address MacroAssembler::count_positives(Register ary1, Register len, Register result) {
5823     // Simple and most common case of aligned small array which is not at the
5824     // end of memory page is placed here. All other cases are in stub.
5825     Label LOOP, END, STUB, STUB_LONG, SET_RESULT, DONE;
5826     const uint64_t UPPER_BIT_MASK=0x8080808080808080;
5827     assert_different_registers(ary1, len, result);
5828 
5829     mov(result, len);
5830     cmpw(len, 0);
5831     br(LE, DONE);
5832     cmpw(len, 4 * wordSize);
5833     br(GE, STUB_LONG); // size > 32 then go to stub
5834 
5835     int shift = 64 - exact_log2(os::vm_page_size());
5836     lsl(rscratch1, ary1, shift);
5837     mov(rscratch2, (size_t)(4 * wordSize) << shift);
5838     adds(rscratch2, rscratch1, rscratch2);  // At end of page?
5839     br(CS, STUB); // at the end of page then go to stub
5840     subs(len, len, wordSize);
5841     br(LT, END);
5842 
5843   BIND(LOOP);
5844     ldr(rscratch1, Address(post(ary1, wordSize)));
5845     tst(rscratch1, UPPER_BIT_MASK);
5846     br(NE, SET_RESULT);
5847     subs(len, len, wordSize);
5848     br(GE, LOOP);
5849     cmpw(len, -wordSize);
5850     br(EQ, DONE);
5851 
5852   BIND(END);
5853     ldr(rscratch1, Address(ary1));
5854     sub(rscratch2, zr, len, LSL, 3); // LSL 3 is to get bits from bytes
5855     lslv(rscratch1, rscratch1, rscratch2);
5856     tst(rscratch1, UPPER_BIT_MASK);
5857     br(NE, SET_RESULT);
5858     b(DONE);
5859 
5860   BIND(STUB);
5861     RuntimeAddress count_pos = RuntimeAddress(StubRoutines::aarch64::count_positives());
5862     assert(count_pos.target() != nullptr, "count_positives stub has not been generated");
5863     address tpc1 = trampoline_call(count_pos);
5864     if (tpc1 == nullptr) {
5865       DEBUG_ONLY(reset_labels(STUB_LONG, SET_RESULT, DONE));
5866       postcond(pc() == badAddress);
5867       return nullptr;
5868     }
5869     b(DONE);
5870 
5871   BIND(STUB_LONG);
5872     RuntimeAddress count_pos_long = RuntimeAddress(StubRoutines::aarch64::count_positives_long());
5873     assert(count_pos_long.target() != nullptr, "count_positives_long stub has not been generated");
5874     address tpc2 = trampoline_call(count_pos_long);
5875     if (tpc2 == nullptr) {
5876       DEBUG_ONLY(reset_labels(SET_RESULT, DONE));
5877       postcond(pc() == badAddress);
5878       return nullptr;
5879     }
5880     b(DONE);
5881 
5882   BIND(SET_RESULT);
5883 
5884     add(len, len, wordSize);
5885     sub(result, result, len);
5886 
5887   BIND(DONE);
5888   postcond(pc() != badAddress);
5889   return pc();
5890 }
5891 
5892 // Clobbers: rscratch1, rscratch2, rflags
5893 // May also clobber v0-v7 when (!UseSimpleArrayEquals && UseSIMDForArrayEquals)
5894 address MacroAssembler::arrays_equals(Register a1, Register a2, Register tmp3,
5895                                       Register tmp4, Register tmp5, Register result,
5896                                       Register cnt1, int elem_size) {
5897   Label DONE, SAME;
5898   Register tmp1 = rscratch1;
5899   Register tmp2 = rscratch2;
5900   int elem_per_word = wordSize/elem_size;
5901   int log_elem_size = exact_log2(elem_size);
5902   int klass_offset  = arrayOopDesc::klass_offset_in_bytes();
5903   int length_offset = arrayOopDesc::length_offset_in_bytes();
5904   int base_offset
5905     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
5906   // When the length offset is not aligned to 8 bytes,
5907   // then we align it down. This is valid because the new
5908   // offset will always be the klass which is the same
5909   // for type arrays.
5910   int start_offset = align_down(length_offset, BytesPerWord);
5911   int extra_length = base_offset - start_offset;
5912   assert(start_offset == length_offset || start_offset == klass_offset,
5913          "start offset must be 8-byte-aligned or be the klass offset");
5914   assert(base_offset != start_offset, "must include the length field");
5915   extra_length = extra_length / elem_size; // We count in elements, not bytes.
5916   int stubBytesThreshold = 3 * 64 + (UseSIMDForArrayEquals ? 0 : 16);
5917 
5918   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
5919   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
5920 
5921 #ifndef PRODUCT
5922   {
5923     const char kind = (elem_size == 2) ? 'U' : 'L';
5924     char comment[64];
5925     os::snprintf_checked(comment, sizeof comment, "array_equals%c{", kind);
5926     BLOCK_COMMENT(comment);
5927   }
5928 #endif
5929 
5930   // if (a1 == a2)
5931   //     return true;
5932   cmpoop(a1, a2); // May have read barriers for a1 and a2.
5933   br(EQ, SAME);
5934 
5935   if (UseSimpleArrayEquals) {
5936     Label NEXT_WORD, SHORT, TAIL03, TAIL01, A_MIGHT_BE_NULL, A_IS_NOT_NULL;
5937     // if (a1 == nullptr || a2 == nullptr)
5938     //     return false;
5939     // a1 & a2 == 0 means (some-pointer is null) or
5940     // (very-rare-or-even-probably-impossible-pointer-values)
5941     // so, we can save one branch in most cases
5942     tst(a1, a2);
5943     mov(result, false);
5944     br(EQ, A_MIGHT_BE_NULL);
5945     // if (a1.length != a2.length)
5946     //      return false;
5947     bind(A_IS_NOT_NULL);
5948     ldrw(cnt1, Address(a1, length_offset));
5949     ldrw(tmp5, Address(a2, length_offset));
5950     cmp(cnt1, tmp5);
5951     br(NE, DONE); // If lengths differ, return false
5952     // Increase loop counter by diff between base- and actual start-offset.
5953     addw(cnt1, cnt1, extra_length);
5954     lea(a1, Address(a1, start_offset));
5955     lea(a2, Address(a2, start_offset));
5956     // Check for short strings, i.e. smaller than wordSize.
5957     subs(cnt1, cnt1, elem_per_word);
5958     br(Assembler::LT, SHORT);
5959     // Main 8 byte comparison loop.
5960     bind(NEXT_WORD); {
5961       ldr(tmp1, Address(post(a1, wordSize)));
5962       ldr(tmp2, Address(post(a2, wordSize)));
5963       subs(cnt1, cnt1, elem_per_word);
5964       eor(tmp5, tmp1, tmp2);
5965       cbnz(tmp5, DONE);
5966     } br(GT, NEXT_WORD);
5967     // Last longword.  In the case where length == 4 we compare the
5968     // same longword twice, but that's still faster than another
5969     // conditional branch.
5970     // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
5971     // length == 4.
5972     if (log_elem_size > 0)
5973       lsl(cnt1, cnt1, log_elem_size);
5974     ldr(tmp3, Address(a1, cnt1));
5975     ldr(tmp4, Address(a2, cnt1));
5976     eor(tmp5, tmp3, tmp4);
5977     cbnz(tmp5, DONE);
5978     b(SAME);
5979     bind(A_MIGHT_BE_NULL);
5980     // in case both a1 and a2 are not-null, proceed with loads
5981     cbz(a1, DONE);
5982     cbz(a2, DONE);
5983     b(A_IS_NOT_NULL);
5984     bind(SHORT);
5985 
5986     tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
5987     {
5988       ldrw(tmp1, Address(post(a1, 4)));
5989       ldrw(tmp2, Address(post(a2, 4)));
5990       eorw(tmp5, tmp1, tmp2);
5991       cbnzw(tmp5, DONE);
5992     }
5993     bind(TAIL03);
5994     tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
5995     {
5996       ldrh(tmp3, Address(post(a1, 2)));
5997       ldrh(tmp4, Address(post(a2, 2)));
5998       eorw(tmp5, tmp3, tmp4);
5999       cbnzw(tmp5, DONE);
6000     }
6001     bind(TAIL01);
6002     if (elem_size == 1) { // Only needed when comparing byte arrays.
6003       tbz(cnt1, 0, SAME); // 0-1 bytes left.
6004       {
6005         ldrb(tmp1, a1);
6006         ldrb(tmp2, a2);
6007         eorw(tmp5, tmp1, tmp2);
6008         cbnzw(tmp5, DONE);
6009       }
6010     }
6011   } else {
6012     Label NEXT_DWORD, SHORT, TAIL, TAIL2, STUB,
6013         CSET_EQ, LAST_CHECK;
6014     mov(result, false);
6015     cbz(a1, DONE);
6016     ldrw(cnt1, Address(a1, length_offset));
6017     cbz(a2, DONE);
6018     ldrw(tmp5, Address(a2, length_offset));
6019     cmp(cnt1, tmp5);
6020     br(NE, DONE); // If lengths differ, return false
6021     // Increase loop counter by diff between base- and actual start-offset.
6022     addw(cnt1, cnt1, extra_length);
6023 
6024     // on most CPUs a2 is still "locked"(surprisingly) in ldrw and it's
6025     // faster to perform another branch before comparing a1 and a2
6026     cmp(cnt1, (u1)elem_per_word);
6027     br(LE, SHORT); // short or same
6028     ldr(tmp3, Address(pre(a1, start_offset)));
6029     subs(zr, cnt1, stubBytesThreshold);
6030     br(GE, STUB);
6031     ldr(tmp4, Address(pre(a2, start_offset)));
6032     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
6033 
6034     // Main 16 byte comparison loop with 2 exits
6035     bind(NEXT_DWORD); {
6036       ldr(tmp1, Address(pre(a1, wordSize)));
6037       ldr(tmp2, Address(pre(a2, wordSize)));
6038       subs(cnt1, cnt1, 2 * elem_per_word);
6039       br(LE, TAIL);
6040       eor(tmp4, tmp3, tmp4);
6041       cbnz(tmp4, DONE);
6042       ldr(tmp3, Address(pre(a1, wordSize)));
6043       ldr(tmp4, Address(pre(a2, wordSize)));
6044       cmp(cnt1, (u1)elem_per_word);
6045       br(LE, TAIL2);
6046       cmp(tmp1, tmp2);
6047     } br(EQ, NEXT_DWORD);
6048     b(DONE);
6049 
6050     bind(TAIL);
6051     eor(tmp4, tmp3, tmp4);
6052     eor(tmp2, tmp1, tmp2);
6053     lslv(tmp2, tmp2, tmp5);
6054     orr(tmp5, tmp4, tmp2);
6055     cmp(tmp5, zr);
6056     b(CSET_EQ);
6057 
6058     bind(TAIL2);
6059     eor(tmp2, tmp1, tmp2);
6060     cbnz(tmp2, DONE);
6061     b(LAST_CHECK);
6062 
6063     bind(STUB);
6064     ldr(tmp4, Address(pre(a2, start_offset)));
6065     if (elem_size == 2) { // convert to byte counter
6066       lsl(cnt1, cnt1, 1);
6067     }
6068     eor(tmp5, tmp3, tmp4);
6069     cbnz(tmp5, DONE);
6070     RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_array_equals());
6071     assert(stub.target() != nullptr, "array_equals_long stub has not been generated");
6072     address tpc = trampoline_call(stub);
6073     if (tpc == nullptr) {
6074       DEBUG_ONLY(reset_labels(SHORT, LAST_CHECK, CSET_EQ, SAME, DONE));
6075       postcond(pc() == badAddress);
6076       return nullptr;
6077     }
6078     b(DONE);
6079 
6080     // (a1 != null && a2 == null) || (a1 != null && a2 != null && a1 == a2)
6081     // so, if a2 == null => return false(0), else return true, so we can return a2
6082     mov(result, a2);
6083     b(DONE);
6084     bind(SHORT);
6085     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
6086     ldr(tmp3, Address(a1, start_offset));
6087     ldr(tmp4, Address(a2, start_offset));
6088     bind(LAST_CHECK);
6089     eor(tmp4, tmp3, tmp4);
6090     lslv(tmp5, tmp4, tmp5);
6091     cmp(tmp5, zr);
6092     bind(CSET_EQ);
6093     cset(result, EQ);
6094     b(DONE);
6095   }
6096 
6097   bind(SAME);
6098   mov(result, true);
6099   // That's it.
6100   bind(DONE);
6101 
6102   BLOCK_COMMENT("} array_equals");
6103   postcond(pc() != badAddress);
6104   return pc();
6105 }
6106 
6107 // Compare Strings
6108 
6109 // For Strings we're passed the address of the first characters in a1
6110 // and a2 and the length in cnt1.
6111 // There are two implementations.  For arrays >= 8 bytes, all
6112 // comparisons (including the final one, which may overlap) are
6113 // performed 8 bytes at a time.  For strings < 8 bytes, we compare a
6114 // halfword, then a short, and then a byte.
6115 
6116 void MacroAssembler::string_equals(Register a1, Register a2,
6117                                    Register result, Register cnt1)
6118 {
6119   Label SAME, DONE, SHORT, NEXT_WORD;
6120   Register tmp1 = rscratch1;
6121   Register tmp2 = rscratch2;
6122 
6123   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
6124 
6125 #ifndef PRODUCT
6126   {
6127     char comment[64];
6128     os::snprintf_checked(comment, sizeof comment, "{string_equalsL");
6129     BLOCK_COMMENT(comment);
6130   }
6131 #endif
6132 
6133   mov(result, false);
6134 
6135   // Check for short strings, i.e. smaller than wordSize.
6136   subs(cnt1, cnt1, wordSize);
6137   br(Assembler::LT, SHORT);
6138   // Main 8 byte comparison loop.
6139   bind(NEXT_WORD); {
6140     ldr(tmp1, Address(post(a1, wordSize)));
6141     ldr(tmp2, Address(post(a2, wordSize)));
6142     subs(cnt1, cnt1, wordSize);
6143     eor(tmp1, tmp1, tmp2);
6144     cbnz(tmp1, DONE);
6145   } br(GT, NEXT_WORD);
6146   // Last longword.  In the case where length == 4 we compare the
6147   // same longword twice, but that's still faster than another
6148   // conditional branch.
6149   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
6150   // length == 4.
6151   ldr(tmp1, Address(a1, cnt1));
6152   ldr(tmp2, Address(a2, cnt1));
6153   eor(tmp2, tmp1, tmp2);
6154   cbnz(tmp2, DONE);
6155   b(SAME);
6156 
6157   bind(SHORT);
6158   Label TAIL03, TAIL01;
6159 
6160   tbz(cnt1, 2, TAIL03); // 0-7 bytes left.
6161   {
6162     ldrw(tmp1, Address(post(a1, 4)));
6163     ldrw(tmp2, Address(post(a2, 4)));
6164     eorw(tmp1, tmp1, tmp2);
6165     cbnzw(tmp1, DONE);
6166   }
6167   bind(TAIL03);
6168   tbz(cnt1, 1, TAIL01); // 0-3 bytes left.
6169   {
6170     ldrh(tmp1, Address(post(a1, 2)));
6171     ldrh(tmp2, Address(post(a2, 2)));
6172     eorw(tmp1, tmp1, tmp2);
6173     cbnzw(tmp1, DONE);
6174   }
6175   bind(TAIL01);
6176   tbz(cnt1, 0, SAME); // 0-1 bytes left.
6177     {
6178     ldrb(tmp1, a1);
6179     ldrb(tmp2, a2);
6180     eorw(tmp1, tmp1, tmp2);
6181     cbnzw(tmp1, DONE);
6182   }
6183   // Arrays are equal.
6184   bind(SAME);
6185   mov(result, true);
6186 
6187   // That's it.
6188   bind(DONE);
6189   BLOCK_COMMENT("} string_equals");
6190 }
6191 
6192 
6193 // The size of the blocks erased by the zero_blocks stub.  We must
6194 // handle anything smaller than this ourselves in zero_words().
6195 const int MacroAssembler::zero_words_block_size = 8;
6196 
6197 // zero_words() is used by C2 ClearArray patterns and by
6198 // C1_MacroAssembler.  It is as small as possible, handling small word
6199 // counts locally and delegating anything larger to the zero_blocks
6200 // stub.  It is expanded many times in compiled code, so it is
6201 // important to keep it short.
6202 
6203 // ptr:   Address of a buffer to be zeroed.
6204 // cnt:   Count in HeapWords.
6205 //
6206 // ptr, cnt, rscratch1, and rscratch2 are clobbered.
6207 address MacroAssembler::zero_words(Register ptr, Register cnt)
6208 {
6209   assert(is_power_of_2(zero_words_block_size), "adjust this");
6210 
6211   BLOCK_COMMENT("zero_words {");
6212   assert(ptr == r10 && cnt == r11, "mismatch in register usage");
6213   RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
6214   assert(zero_blocks.target() != nullptr, "zero_blocks stub has not been generated");
6215 
6216   subs(rscratch1, cnt, zero_words_block_size);
6217   Label around;
6218   br(LO, around);
6219   {
6220     RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
6221     assert(zero_blocks.target() != nullptr, "zero_blocks stub has not been generated");
6222     // Make sure this is a C2 compilation. C1 allocates space only for
6223     // trampoline stubs generated by Call LIR ops, and in any case it
6224     // makes sense for a C1 compilation task to proceed as quickly as
6225     // possible.
6226     CompileTask* task;
6227     if (StubRoutines::aarch64::complete()
6228         && Thread::current()->is_Compiler_thread()
6229         && (task = ciEnv::current()->task())
6230         && is_c2_compile(task->comp_level())) {
6231       address tpc = trampoline_call(zero_blocks);
6232       if (tpc == nullptr) {
6233         DEBUG_ONLY(reset_labels(around));
6234         return nullptr;
6235       }
6236     } else {
6237       far_call(zero_blocks);
6238     }
6239   }
6240   bind(around);
6241 
6242   // We have a few words left to do. zero_blocks has adjusted r10 and r11
6243   // for us.
6244   for (int i = zero_words_block_size >> 1; i > 1; i >>= 1) {
6245     Label l;
6246     tbz(cnt, exact_log2(i), l);
6247     for (int j = 0; j < i; j += 2) {
6248       stp(zr, zr, post(ptr, 2 * BytesPerWord));
6249     }
6250     bind(l);
6251   }
6252   {
6253     Label l;
6254     tbz(cnt, 0, l);
6255     str(zr, Address(ptr));
6256     bind(l);
6257   }
6258 
6259   BLOCK_COMMENT("} zero_words");
6260   return pc();
6261 }
6262 
6263 // base:         Address of a buffer to be zeroed, 8 bytes aligned.
6264 // cnt:          Immediate count in HeapWords.
6265 //
6266 // r10, r11, rscratch1, and rscratch2 are clobbered.
6267 address MacroAssembler::zero_words(Register base, uint64_t cnt)
6268 {
6269   assert(wordSize <= BlockZeroingLowLimit,
6270             "increase BlockZeroingLowLimit");
6271   address result = nullptr;
6272   if (cnt <= (uint64_t)BlockZeroingLowLimit / BytesPerWord) {
6273 #ifndef PRODUCT
6274     {
6275       char buf[64];
6276       os::snprintf_checked(buf, sizeof buf, "zero_words (count = %" PRIu64 ") {", cnt);
6277       BLOCK_COMMENT(buf);
6278     }
6279 #endif
6280     if (cnt >= 16) {
6281       uint64_t loops = cnt/16;
6282       if (loops > 1) {
6283         mov(rscratch2, loops - 1);
6284       }
6285       {
6286         Label loop;
6287         bind(loop);
6288         for (int i = 0; i < 16; i += 2) {
6289           stp(zr, zr, Address(base, i * BytesPerWord));
6290         }
6291         add(base, base, 16 * BytesPerWord);
6292         if (loops > 1) {
6293           subs(rscratch2, rscratch2, 1);
6294           br(GE, loop);
6295         }
6296       }
6297     }
6298     cnt %= 16;
6299     int i = cnt & 1;  // store any odd word to start
6300     if (i) str(zr, Address(base));
6301     for (; i < (int)cnt; i += 2) {
6302       stp(zr, zr, Address(base, i * wordSize));
6303     }
6304     BLOCK_COMMENT("} zero_words");
6305     result = pc();
6306   } else {
6307     mov(r10, base); mov(r11, cnt);
6308     result = zero_words(r10, r11);
6309   }
6310   return result;
6311 }
6312 
6313 // Zero blocks of memory by using DC ZVA.
6314 //
6315 // Aligns the base address first sufficiently for DC ZVA, then uses
6316 // DC ZVA repeatedly for every full block.  cnt is the size to be
6317 // zeroed in HeapWords.  Returns the count of words left to be zeroed
6318 // in cnt.
6319 //
6320 // NOTE: This is intended to be used in the zero_blocks() stub.  If
6321 // you want to use it elsewhere, note that cnt must be >= 2*zva_length.
6322 void MacroAssembler::zero_dcache_blocks(Register base, Register cnt) {
6323   Register tmp = rscratch1;
6324   Register tmp2 = rscratch2;
6325   int zva_length = VM_Version::zva_length();
6326   Label initial_table_end, loop_zva;
6327   Label fini;
6328 
6329   // Base must be 16 byte aligned. If not just return and let caller handle it
6330   tst(base, 0x0f);
6331   br(Assembler::NE, fini);
6332   // Align base with ZVA length.
6333   neg(tmp, base);
6334   andr(tmp, tmp, zva_length - 1);
6335 
6336   // tmp: the number of bytes to be filled to align the base with ZVA length.
6337   add(base, base, tmp);
6338   sub(cnt, cnt, tmp, Assembler::ASR, 3);
6339   adr(tmp2, initial_table_end);
6340   sub(tmp2, tmp2, tmp, Assembler::LSR, 2);
6341   br(tmp2);
6342 
6343   for (int i = -zva_length + 16; i < 0; i += 16)
6344     stp(zr, zr, Address(base, i));
6345   bind(initial_table_end);
6346 
6347   sub(cnt, cnt, zva_length >> 3);
6348   bind(loop_zva);
6349   dc(Assembler::ZVA, base);
6350   subs(cnt, cnt, zva_length >> 3);
6351   add(base, base, zva_length);
6352   br(Assembler::GE, loop_zva);
6353   add(cnt, cnt, zva_length >> 3); // count not zeroed by DC ZVA
6354   bind(fini);
6355 }
6356 
6357 // base:   Address of a buffer to be filled, 8 bytes aligned.
6358 // cnt:    Count in 8-byte unit.
6359 // value:  Value to be filled with.
6360 // base will point to the end of the buffer after filling.
6361 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
6362 {
6363 //  Algorithm:
6364 //
6365 //    if (cnt == 0) {
6366 //      return;
6367 //    }
6368 //    if ((p & 8) != 0) {
6369 //      *p++ = v;
6370 //    }
6371 //
6372 //    scratch1 = cnt & 14;
6373 //    cnt -= scratch1;
6374 //    p += scratch1;
6375 //    switch (scratch1 / 2) {
6376 //      do {
6377 //        cnt -= 16;
6378 //          p[-16] = v;
6379 //          p[-15] = v;
6380 //        case 7:
6381 //          p[-14] = v;
6382 //          p[-13] = v;
6383 //        case 6:
6384 //          p[-12] = v;
6385 //          p[-11] = v;
6386 //          // ...
6387 //        case 1:
6388 //          p[-2] = v;
6389 //          p[-1] = v;
6390 //        case 0:
6391 //          p += 16;
6392 //      } while (cnt);
6393 //    }
6394 //    if ((cnt & 1) == 1) {
6395 //      *p++ = v;
6396 //    }
6397 
6398   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
6399 
6400   Label fini, skip, entry, loop;
6401   const int unroll = 8; // Number of stp instructions we'll unroll
6402 
6403   cbz(cnt, fini);
6404   tbz(base, 3, skip);
6405   str(value, Address(post(base, 8)));
6406   sub(cnt, cnt, 1);
6407   bind(skip);
6408 
6409   andr(rscratch1, cnt, (unroll-1) * 2);
6410   sub(cnt, cnt, rscratch1);
6411   add(base, base, rscratch1, Assembler::LSL, 3);
6412   adr(rscratch2, entry);
6413   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
6414   br(rscratch2);
6415 
6416   bind(loop);
6417   add(base, base, unroll * 16);
6418   for (int i = -unroll; i < 0; i++)
6419     stp(value, value, Address(base, i * 16));
6420   bind(entry);
6421   subs(cnt, cnt, unroll * 2);
6422   br(Assembler::GE, loop);
6423 
6424   tbz(cnt, 0, fini);
6425   str(value, Address(post(base, 8)));
6426   bind(fini);
6427 }
6428 
6429 // Intrinsic for
6430 //
6431 // - sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6432 //   Encodes char[] to byte[] in ISO-8859-1
6433 //
6434 // - java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6435 //   Encodes byte[] (containing UTF-16) to byte[] in ISO-8859-1
6436 //
6437 // - java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6438 //   Encodes char[] to byte[] in ASCII
6439 //
6440 // This version always returns the number of characters copied, and does not
6441 // clobber the 'len' register. A successful copy will complete with the post-
6442 // condition: 'res' == 'len', while an unsuccessful copy will exit with the
6443 // post-condition: 0 <= 'res' < 'len'.
6444 //
6445 // NOTE: Attempts to use 'ld2' (and 'umaxv' in the ISO part) has proven to
6446 //       degrade performance (on Ampere Altra - Neoverse N1), to an extent
6447 //       beyond the acceptable, even though the footprint would be smaller.
6448 //       Using 'umaxv' in the ASCII-case comes with a small penalty but does
6449 //       avoid additional bloat.
6450 //
6451 // Clobbers: src, dst, res, rscratch1, rscratch2, rflags
6452 void MacroAssembler::encode_iso_array(Register src, Register dst,
6453                                       Register len, Register res, bool ascii,
6454                                       FloatRegister vtmp0, FloatRegister vtmp1,
6455                                       FloatRegister vtmp2, FloatRegister vtmp3,
6456                                       FloatRegister vtmp4, FloatRegister vtmp5)
6457 {
6458   Register cnt = res;
6459   Register max = rscratch1;
6460   Register chk = rscratch2;
6461 
6462   prfm(Address(src), PLDL1STRM);
6463   movw(cnt, len);
6464 
6465 #define ASCII(insn) do { if (ascii) { insn; } } while (0)
6466 
6467   Label LOOP_32, DONE_32, FAIL_32;
6468 
6469   BIND(LOOP_32);
6470   {
6471     cmpw(cnt, 32);
6472     br(LT, DONE_32);
6473     ld1(vtmp0, vtmp1, vtmp2, vtmp3, T8H, Address(post(src, 64)));
6474     // Extract lower bytes.
6475     FloatRegister vlo0 = vtmp4;
6476     FloatRegister vlo1 = vtmp5;
6477     uzp1(vlo0, T16B, vtmp0, vtmp1);
6478     uzp1(vlo1, T16B, vtmp2, vtmp3);
6479     // Merge bits...
6480     orr(vtmp0, T16B, vtmp0, vtmp1);
6481     orr(vtmp2, T16B, vtmp2, vtmp3);
6482     // Extract merged upper bytes.
6483     FloatRegister vhix = vtmp0;
6484     uzp2(vhix, T16B, vtmp0, vtmp2);
6485     // ISO-check on hi-parts (all zero).
6486     //                          ASCII-check on lo-parts (no sign).
6487     FloatRegister vlox = vtmp1; // Merge lower bytes.
6488                                 ASCII(orr(vlox, T16B, vlo0, vlo1));
6489     umov(chk, vhix, D, 1);      ASCII(cm(LT, vlox, T16B, vlox));
6490     fmovd(max, vhix);           ASCII(umaxv(vlox, T16B, vlox));
6491     orr(chk, chk, max);         ASCII(umov(max, vlox, B, 0));
6492                                 ASCII(orr(chk, chk, max));
6493     cbnz(chk, FAIL_32);
6494     subw(cnt, cnt, 32);
6495     st1(vlo0, vlo1, T16B, Address(post(dst, 32)));
6496     b(LOOP_32);
6497   }
6498   BIND(FAIL_32);
6499   sub(src, src, 64);
6500   BIND(DONE_32);
6501 
6502   Label LOOP_8, SKIP_8;
6503 
6504   BIND(LOOP_8);
6505   {
6506     cmpw(cnt, 8);
6507     br(LT, SKIP_8);
6508     FloatRegister vhi = vtmp0;
6509     FloatRegister vlo = vtmp1;
6510     ld1(vtmp3, T8H, src);
6511     uzp1(vlo, T16B, vtmp3, vtmp3);
6512     uzp2(vhi, T16B, vtmp3, vtmp3);
6513     // ISO-check on hi-parts (all zero).
6514     //                          ASCII-check on lo-parts (no sign).
6515                                 ASCII(cm(LT, vtmp2, T16B, vlo));
6516     fmovd(chk, vhi);            ASCII(umaxv(vtmp2, T16B, vtmp2));
6517                                 ASCII(umov(max, vtmp2, B, 0));
6518                                 ASCII(orr(chk, chk, max));
6519     cbnz(chk, SKIP_8);
6520 
6521     strd(vlo, Address(post(dst, 8)));
6522     subw(cnt, cnt, 8);
6523     add(src, src, 16);
6524     b(LOOP_8);
6525   }
6526   BIND(SKIP_8);
6527 
6528 #undef ASCII
6529 
6530   Label LOOP, DONE;
6531 
6532   cbz(cnt, DONE);
6533   BIND(LOOP);
6534   {
6535     Register chr = rscratch1;
6536     ldrh(chr, Address(post(src, 2)));
6537     tst(chr, ascii ? 0xff80 : 0xff00);
6538     br(NE, DONE);
6539     strb(chr, Address(post(dst, 1)));
6540     subs(cnt, cnt, 1);
6541     br(GT, LOOP);
6542   }
6543   BIND(DONE);
6544   // Return index where we stopped.
6545   subw(res, len, cnt);
6546 }
6547 
6548 // Inflate byte[] array to char[].
6549 // Clobbers: src, dst, len, rflags, rscratch1, v0-v6
6550 address MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
6551                                            FloatRegister vtmp1, FloatRegister vtmp2,
6552                                            FloatRegister vtmp3, Register tmp4) {
6553   Label big, done, after_init, to_stub;
6554 
6555   assert_different_registers(src, dst, len, tmp4, rscratch1);
6556 
6557   fmovd(vtmp1, 0.0);
6558   lsrw(tmp4, len, 3);
6559   bind(after_init);
6560   cbnzw(tmp4, big);
6561   // Short string: less than 8 bytes.
6562   {
6563     Label loop, tiny;
6564 
6565     cmpw(len, 4);
6566     br(LT, tiny);
6567     // Use SIMD to do 4 bytes.
6568     ldrs(vtmp2, post(src, 4));
6569     zip1(vtmp3, T8B, vtmp2, vtmp1);
6570     subw(len, len, 4);
6571     strd(vtmp3, post(dst, 8));
6572 
6573     cbzw(len, done);
6574 
6575     // Do the remaining bytes by steam.
6576     bind(loop);
6577     ldrb(tmp4, post(src, 1));
6578     strh(tmp4, post(dst, 2));
6579     subw(len, len, 1);
6580 
6581     bind(tiny);
6582     cbnz(len, loop);
6583 
6584     b(done);
6585   }
6586 
6587   if (SoftwarePrefetchHintDistance >= 0) {
6588     bind(to_stub);
6589       RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_byte_array_inflate());
6590       assert(stub.target() != nullptr, "large_byte_array_inflate stub has not been generated");
6591       address tpc = trampoline_call(stub);
6592       if (tpc == nullptr) {
6593         DEBUG_ONLY(reset_labels(big, done));
6594         postcond(pc() == badAddress);
6595         return nullptr;
6596       }
6597       b(after_init);
6598   }
6599 
6600   // Unpack the bytes 8 at a time.
6601   bind(big);
6602   {
6603     Label loop, around, loop_last, loop_start;
6604 
6605     if (SoftwarePrefetchHintDistance >= 0) {
6606       const int large_loop_threshold = (64 + 16)/8;
6607       ldrd(vtmp2, post(src, 8));
6608       andw(len, len, 7);
6609       cmp(tmp4, (u1)large_loop_threshold);
6610       br(GE, to_stub);
6611       b(loop_start);
6612 
6613       bind(loop);
6614       ldrd(vtmp2, post(src, 8));
6615       bind(loop_start);
6616       subs(tmp4, tmp4, 1);
6617       br(EQ, loop_last);
6618       zip1(vtmp2, T16B, vtmp2, vtmp1);
6619       ldrd(vtmp3, post(src, 8));
6620       st1(vtmp2, T8H, post(dst, 16));
6621       subs(tmp4, tmp4, 1);
6622       zip1(vtmp3, T16B, vtmp3, vtmp1);
6623       st1(vtmp3, T8H, post(dst, 16));
6624       br(NE, loop);
6625       b(around);
6626       bind(loop_last);
6627       zip1(vtmp2, T16B, vtmp2, vtmp1);
6628       st1(vtmp2, T8H, post(dst, 16));
6629       bind(around);
6630       cbz(len, done);
6631     } else {
6632       andw(len, len, 7);
6633       bind(loop);
6634       ldrd(vtmp2, post(src, 8));
6635       sub(tmp4, tmp4, 1);
6636       zip1(vtmp3, T16B, vtmp2, vtmp1);
6637       st1(vtmp3, T8H, post(dst, 16));
6638       cbnz(tmp4, loop);
6639     }
6640   }
6641 
6642   // Do the tail of up to 8 bytes.
6643   add(src, src, len);
6644   ldrd(vtmp3, Address(src, -8));
6645   add(dst, dst, len, ext::uxtw, 1);
6646   zip1(vtmp3, T16B, vtmp3, vtmp1);
6647   strq(vtmp3, Address(dst, -16));
6648 
6649   bind(done);
6650   postcond(pc() != badAddress);
6651   return pc();
6652 }
6653 
6654 // Compress char[] array to byte[].
6655 // Intrinsic for java.lang.StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
6656 // Return the array length if every element in array can be encoded,
6657 // otherwise, the index of first non-latin1 (> 0xff) character.
6658 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
6659                                          Register res,
6660                                          FloatRegister tmp0, FloatRegister tmp1,
6661                                          FloatRegister tmp2, FloatRegister tmp3,
6662                                          FloatRegister tmp4, FloatRegister tmp5) {
6663   encode_iso_array(src, dst, len, res, false, tmp0, tmp1, tmp2, tmp3, tmp4, tmp5);
6664 }
6665 
6666 // java.math.round(double a)
6667 // Returns the closest long to the argument, with ties rounding to
6668 // positive infinity.  This requires some fiddling for corner
6669 // cases. We take care to avoid double rounding in e.g. (jlong)(a + 0.5).
6670 void MacroAssembler::java_round_double(Register dst, FloatRegister src,
6671                                        FloatRegister ftmp) {
6672   Label DONE;
6673   BLOCK_COMMENT("java_round_double: { ");
6674   fmovd(rscratch1, src);
6675   // Use RoundToNearestTiesAway unless src small and -ve.
6676   fcvtasd(dst, src);
6677   // Test if src >= 0 || abs(src) >= 0x1.0p52
6678   eor(rscratch1, rscratch1, UCONST64(1) << 63); // flip sign bit
6679   mov(rscratch2, julong_cast(0x1.0p52));
6680   cmp(rscratch1, rscratch2);
6681   br(HS, DONE); {
6682     // src < 0 && abs(src) < 0x1.0p52
6683     // src may have a fractional part, so add 0.5
6684     fmovd(ftmp, 0.5);
6685     faddd(ftmp, src, ftmp);
6686     // Convert double to jlong, use RoundTowardsNegative
6687     fcvtmsd(dst, ftmp);
6688   }
6689   bind(DONE);
6690   BLOCK_COMMENT("} java_round_double");
6691 }
6692 
6693 void MacroAssembler::java_round_float(Register dst, FloatRegister src,
6694                                       FloatRegister ftmp) {
6695   Label DONE;
6696   BLOCK_COMMENT("java_round_float: { ");
6697   fmovs(rscratch1, src);
6698   // Use RoundToNearestTiesAway unless src small and -ve.
6699   fcvtassw(dst, src);
6700   // Test if src >= 0 || abs(src) >= 0x1.0p23
6701   eor(rscratch1, rscratch1, 0x80000000); // flip sign bit
6702   mov(rscratch2, jint_cast(0x1.0p23f));
6703   cmp(rscratch1, rscratch2);
6704   br(HS, DONE); {
6705     // src < 0 && |src| < 0x1.0p23
6706     // src may have a fractional part, so add 0.5
6707     fmovs(ftmp, 0.5f);
6708     fadds(ftmp, src, ftmp);
6709     // Convert float to jint, use RoundTowardsNegative
6710     fcvtmssw(dst, ftmp);
6711   }
6712   bind(DONE);
6713   BLOCK_COMMENT("} java_round_float");
6714 }
6715 
6716 // get_thread() can be called anywhere inside generated code so we
6717 // need to save whatever non-callee save context might get clobbered
6718 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
6719 // the call setup code.
6720 //
6721 // On Linux and Windows, aarch64_get_thread_helper() is implemented in
6722 // assembly and clobbers only r0, r1, and flags.
6723 // On other systems, the helper is a usual C function.
6724 //
6725 void MacroAssembler::get_thread(Register dst) {
6726   RegSet saved_regs =
6727     BSD_ONLY(RegSet::range(r0, r17) + lr - dst)
6728     NOT_BSD (RegSet::range(r0, r1)  + lr - dst);
6729 
6730   protect_return_address();
6731   push(saved_regs, sp);
6732 
6733   mov(lr, ExternalAddress(CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper)));
6734   blr(lr);
6735   if (dst != c_rarg0) {
6736     mov(dst, c_rarg0);
6737   }
6738 
6739   pop(saved_regs, sp);
6740   authenticate_return_address();
6741 }
6742 
6743 void MacroAssembler::cache_wb(Address line) {
6744   assert(line.getMode() == Address::base_plus_offset, "mode should be base_plus_offset");
6745   assert(line.index() == noreg, "index should be noreg");
6746   assert(line.offset() == 0, "offset should be 0");
6747   // would like to assert this
6748   // assert(line._ext.shift == 0, "shift should be zero");
6749   if (VM_Version::supports_dcpop()) {
6750     // writeback using clear virtual address to point of persistence
6751     dc(Assembler::CVAP, line.base());
6752   } else {
6753     // no need to generate anything as Unsafe.writebackMemory should
6754     // never invoke this stub
6755   }
6756 }
6757 
6758 void MacroAssembler::cache_wbsync(bool is_pre) {
6759   // we only need a barrier post sync
6760   if (!is_pre) {
6761     membar(Assembler::AnyAny);
6762   }
6763 }
6764 
6765 void MacroAssembler::verify_sve_vector_length(Register tmp) {
6766   if (!UseSVE || VM_Version::get_max_supported_sve_vector_length() == FloatRegister::sve_vl_min) {
6767     return;
6768   }
6769   // Make sure that native code does not change SVE vector length.
6770   Label verify_ok;
6771   movw(tmp, zr);
6772   sve_inc(tmp, B);
6773   subsw(zr, tmp, VM_Version::get_initial_sve_vector_length());
6774   br(EQ, verify_ok);
6775   stop("Error: SVE vector length has changed since jvm startup");
6776   bind(verify_ok);
6777 }
6778 
6779 void MacroAssembler::verify_ptrue() {
6780   Label verify_ok;
6781   if (!UseSVE) {
6782     return;
6783   }
6784   sve_cntp(rscratch1, B, ptrue, ptrue); // get true elements count.
6785   sve_dec(rscratch1, B);
6786   cbz(rscratch1, verify_ok);
6787   stop("Error: the preserved predicate register (p7) elements are not all true");
6788   bind(verify_ok);
6789 }
6790 
6791 void MacroAssembler::safepoint_isb() {
6792   isb();
6793 #ifndef PRODUCT
6794   if (VerifyCrossModifyFence) {
6795     // Clear the thread state.
6796     strb(zr, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
6797   }
6798 #endif
6799 }
6800 
6801 #ifndef PRODUCT
6802 void MacroAssembler::verify_cross_modify_fence_not_required() {
6803   if (VerifyCrossModifyFence) {
6804     // Check if thread needs a cross modify fence.
6805     ldrb(rscratch1, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
6806     Label fence_not_required;
6807     cbz(rscratch1, fence_not_required);
6808     // If it does then fail.
6809     lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::verify_cross_modify_fence_failure)));
6810     mov(c_rarg0, rthread);
6811     blr(rscratch1);
6812     bind(fence_not_required);
6813   }
6814 }
6815 #endif
6816 
6817 void MacroAssembler::spin_wait() {
6818   block_comment("spin_wait {");
6819   for (int i = 0; i < VM_Version::spin_wait_desc().inst_count(); ++i) {
6820     switch (VM_Version::spin_wait_desc().inst()) {
6821       case SpinWait::NOP:
6822         nop();
6823         break;
6824       case SpinWait::ISB:
6825         isb();
6826         break;
6827       case SpinWait::YIELD:
6828         yield();
6829         break;
6830       case SpinWait::SB:
6831         assert(VM_Version::supports_sb(), "current CPU does not support SB instruction");
6832         sb();
6833         break;
6834       case SpinWait::WFET:
6835         spin_wait_wfet(VM_Version::spin_wait_desc().delay());
6836         break;
6837       default:
6838         ShouldNotReachHere();
6839     }
6840   }
6841   block_comment("}");
6842 }
6843 
6844 void MacroAssembler::spin_wait_wfet(int delay_ns) {
6845   // The sequence assumes CNTFRQ_EL0 is fixed to 1GHz. The assumption is valid
6846   // starting from Armv8.6, according to the "D12.1.2 The system counter" of the
6847   // Arm Architecture Reference Manual for A-profile architecture version M.a.a.
6848   // This is sufficient because FEAT_WFXT is introduced from Armv8.6.
6849   Register target = rscratch1;
6850   Register current = rscratch2;
6851   get_cntvctss_el0(current);
6852   add(target, current, delay_ns);
6853 
6854   Label L_wait_loop;
6855   bind(L_wait_loop);
6856 
6857   wfet(target);
6858   get_cntvctss_el0(current);
6859 
6860   cmp(current, target);
6861   br(LT, L_wait_loop);
6862 
6863   sb();
6864 }
6865 
6866 // Stack frame creation/removal
6867 
6868 void MacroAssembler::enter(bool strip_ret_addr) {
6869   if (strip_ret_addr) {
6870     // Addresses can only be signed once. If there are multiple nested frames being created
6871     // in the same function, then the return address needs stripping first.
6872     strip_return_address();
6873   }
6874   protect_return_address();
6875   stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
6876   mov(rfp, sp);
6877 }
6878 
6879 void MacroAssembler::leave() {
6880   mov(sp, rfp);
6881   ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
6882   authenticate_return_address();
6883 }
6884 
6885 // ROP Protection
6886 // Use the AArch64 PAC feature to add ROP protection for generated code. Use whenever creating/
6887 // destroying stack frames or whenever directly loading/storing the LR to memory.
6888 // If ROP protection is not set then these functions are no-ops.
6889 // For more details on PAC see pauth_aarch64.hpp.
6890 
6891 // Sign the LR. Use during construction of a stack frame, before storing the LR to memory.
6892 // Uses value zero as the modifier.
6893 //
6894 void MacroAssembler::protect_return_address() {
6895   if (VM_Version::use_rop_protection()) {
6896     check_return_address();
6897     paciaz();
6898   }
6899 }
6900 
6901 // Sign the return value in the given register. Use before updating the LR in the existing stack
6902 // frame for the current function.
6903 // Uses value zero as the modifier.
6904 //
6905 void MacroAssembler::protect_return_address(Register return_reg) {
6906   if (VM_Version::use_rop_protection()) {
6907     check_return_address(return_reg);
6908     paciza(return_reg);
6909   }
6910 }
6911 
6912 // Authenticate the LR. Use before function return, after restoring FP and loading LR from memory.
6913 // Uses value zero as the modifier.
6914 //
6915 void MacroAssembler::authenticate_return_address() {
6916   if (VM_Version::use_rop_protection()) {
6917     autiaz();
6918     check_return_address();
6919   }
6920 }
6921 
6922 // Authenticate the return value in the given register. Use before updating the LR in the existing
6923 // stack frame for the current function.
6924 // Uses value zero as the modifier.
6925 //
6926 void MacroAssembler::authenticate_return_address(Register return_reg) {
6927   if (VM_Version::use_rop_protection()) {
6928     autiza(return_reg);
6929     check_return_address(return_reg);
6930   }
6931 }
6932 
6933 // Strip any PAC data from LR without performing any authentication. Use with caution - only if
6934 // there is no guaranteed way of authenticating the LR.
6935 //
6936 void MacroAssembler::strip_return_address() {
6937   if (VM_Version::use_rop_protection()) {
6938     xpaclri();
6939   }
6940 }
6941 
6942 #ifndef PRODUCT
6943 // PAC failures can be difficult to debug. After an authentication failure, a segfault will only
6944 // occur when the pointer is used - ie when the program returns to the invalid LR. At this point
6945 // it is difficult to debug back to the callee function.
6946 // This function simply loads from the address in the given register.
6947 // Use directly after authentication to catch authentication failures.
6948 // Also use before signing to check that the pointer is valid and hasn't already been signed.
6949 //
6950 void MacroAssembler::check_return_address(Register return_reg) {
6951   if (VM_Version::use_rop_protection()) {
6952     ldr(zr, Address(return_reg));
6953   }
6954 }
6955 #endif
6956 
6957 // The java_calling_convention describes stack locations as ideal slots on
6958 // a frame with no abi restrictions. Since we must observe abi restrictions
6959 // (like the placement of the register window) the slots must be biased by
6960 // the following value.
6961 static int reg2offset_in(VMReg r) {
6962   // Account for saved rfp and lr
6963   // This should really be in_preserve_stack_slots
6964   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
6965 }
6966 
6967 static int reg2offset_out(VMReg r) {
6968   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
6969 }
6970 
6971 // On 64bit we will store integer like items to the stack as
6972 // 64bits items (AArch64 ABI) even though java would only store
6973 // 32bits for a parameter. On 32bit it will simply be 32bits
6974 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
6975 void MacroAssembler::move32_64(VMRegPair src, VMRegPair dst, Register tmp) {
6976   if (src.first()->is_stack()) {
6977     if (dst.first()->is_stack()) {
6978       // stack to stack
6979       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
6980       str(tmp, Address(sp, reg2offset_out(dst.first())));
6981     } else {
6982       // stack to reg
6983       ldrsw(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
6984     }
6985   } else if (dst.first()->is_stack()) {
6986     // reg to stack
6987     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
6988   } else {
6989     if (dst.first() != src.first()) {
6990       sxtw(dst.first()->as_Register(), src.first()->as_Register());
6991     }
6992   }
6993 }
6994 
6995 // An oop arg. Must pass a handle not the oop itself
6996 void MacroAssembler::object_move(
6997                         OopMap* map,
6998                         int oop_handle_offset,
6999                         int framesize_in_slots,
7000                         VMRegPair src,
7001                         VMRegPair dst,
7002                         bool is_receiver,
7003                         int* receiver_offset) {
7004 
7005   // must pass a handle. First figure out the location we use as a handle
7006 
7007   Register rHandle = dst.first()->is_stack() ? rscratch2 : dst.first()->as_Register();
7008 
7009   // See if oop is null if it is we need no handle
7010 
7011   if (src.first()->is_stack()) {
7012 
7013     // Oop is already on the stack as an argument
7014     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
7015     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
7016     if (is_receiver) {
7017       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
7018     }
7019 
7020     ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
7021     lea(rHandle, Address(rfp, reg2offset_in(src.first())));
7022     // conditionally move a null
7023     cmp(rscratch1, zr);
7024     csel(rHandle, zr, rHandle, Assembler::EQ);
7025   } else {
7026 
7027     // Oop is in an a register we must store it to the space we reserve
7028     // on the stack for oop_handles and pass a handle if oop is non-null
7029 
7030     const Register rOop = src.first()->as_Register();
7031     int oop_slot;
7032     if (rOop == j_rarg0)
7033       oop_slot = 0;
7034     else if (rOop == j_rarg1)
7035       oop_slot = 1;
7036     else if (rOop == j_rarg2)
7037       oop_slot = 2;
7038     else if (rOop == j_rarg3)
7039       oop_slot = 3;
7040     else if (rOop == j_rarg4)
7041       oop_slot = 4;
7042     else if (rOop == j_rarg5)
7043       oop_slot = 5;
7044     else if (rOop == j_rarg6)
7045       oop_slot = 6;
7046     else {
7047       assert(rOop == j_rarg7, "wrong register");
7048       oop_slot = 7;
7049     }
7050 
7051     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
7052     int offset = oop_slot*VMRegImpl::stack_slot_size;
7053 
7054     map->set_oop(VMRegImpl::stack2reg(oop_slot));
7055     // Store oop in handle area, may be null
7056     str(rOop, Address(sp, offset));
7057     if (is_receiver) {
7058       *receiver_offset = offset;
7059     }
7060 
7061     cmp(rOop, zr);
7062     lea(rHandle, Address(sp, offset));
7063     // conditionally move a null
7064     csel(rHandle, zr, rHandle, Assembler::EQ);
7065   }
7066 
7067   // If arg is on the stack then place it otherwise it is already in correct reg.
7068   if (dst.first()->is_stack()) {
7069     str(rHandle, Address(sp, reg2offset_out(dst.first())));
7070   }
7071 }
7072 
7073 // A float arg may have to do float reg int reg conversion
7074 void MacroAssembler::float_move(VMRegPair src, VMRegPair dst, Register tmp) {
7075  if (src.first()->is_stack()) {
7076     if (dst.first()->is_stack()) {
7077       ldrw(tmp, Address(rfp, reg2offset_in(src.first())));
7078       strw(tmp, Address(sp, reg2offset_out(dst.first())));
7079     } else {
7080       ldrs(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
7081     }
7082   } else if (src.first() != dst.first()) {
7083     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
7084       fmovs(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
7085     else
7086       strs(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
7087   }
7088 }
7089 
7090 // A long move
7091 void MacroAssembler::long_move(VMRegPair src, VMRegPair dst, Register tmp) {
7092   if (src.first()->is_stack()) {
7093     if (dst.first()->is_stack()) {
7094       // stack to stack
7095       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7096       str(tmp, Address(sp, reg2offset_out(dst.first())));
7097     } else {
7098       // stack to reg
7099       ldr(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
7100     }
7101   } else if (dst.first()->is_stack()) {
7102     // reg to stack
7103     // Do we really have to sign extend???
7104     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
7105     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
7106   } else {
7107     if (dst.first() != src.first()) {
7108       mov(dst.first()->as_Register(), src.first()->as_Register());
7109     }
7110   }
7111 }
7112 
7113 
7114 // A double move
7115 void MacroAssembler::double_move(VMRegPair src, VMRegPair dst, Register tmp) {
7116  if (src.first()->is_stack()) {
7117     if (dst.first()->is_stack()) {
7118       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7119       str(tmp, Address(sp, reg2offset_out(dst.first())));
7120     } else {
7121       ldrd(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
7122     }
7123   } else if (src.first() != dst.first()) {
7124     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
7125       fmovd(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
7126     else
7127       strd(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
7128   }
7129 }
7130 
7131 // Implements fast-locking.
7132 //
7133 //  - obj: the object to be locked
7134 //  - t1, t2, t3: temporary registers, will be destroyed
7135 //  - slow: branched to if locking fails, absolute offset may larger than 32KB (imm14 encoding).
7136 void MacroAssembler::fast_lock(Register basic_lock, Register obj, Register t1, Register t2, Register t3, Label& slow) {
7137   assert_different_registers(basic_lock, obj, t1, t2, t3, rscratch1);
7138 
7139   Label push;
7140   const Register top = t1;
7141   const Register mark = t2;
7142   const Register t = t3;
7143 
7144   // Preload the markWord. It is important that this is the first
7145   // instruction emitted as it is part of C1's null check semantics.
7146   ldr(mark, Address(obj, oopDesc::mark_offset_in_bytes()));
7147 
7148   if (UseObjectMonitorTable) {
7149     // Clear cache in case fast locking succeeds or we need to take the slow-path.
7150     str(zr, Address(basic_lock, BasicObjectLock::lock_offset() + in_ByteSize((BasicLock::object_monitor_cache_offset_in_bytes()))));
7151   }
7152 
7153   if (DiagnoseSyncOnValueBasedClasses != 0) {
7154     load_klass(t1, obj);
7155     ldrb(t1, Address(t1, Klass::misc_flags_offset()));
7156     tst(t1, KlassFlags::_misc_is_value_based_class);
7157     br(Assembler::NE, slow);
7158   }
7159 
7160   // Check if the lock-stack is full.
7161   ldrw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7162   cmpw(top, (unsigned)LockStack::end_offset());
7163   br(Assembler::GE, slow);
7164 
7165   // Check for recursion.
7166   subw(t, top, oopSize);
7167   ldr(t, Address(rthread, t));
7168   cmp(obj, t);
7169   br(Assembler::EQ, push);
7170 
7171   // Check header for monitor (0b10).
7172   tst(mark, markWord::monitor_value);
7173   br(Assembler::NE, slow);
7174 
7175   // Try to lock. Transition lock bits 0b01 => 0b00
7176   assert(oopDesc::mark_offset_in_bytes() == 0, "required to avoid lea");
7177   orr(mark, mark, markWord::unlocked_value);
7178   eor(t, mark, markWord::unlocked_value);
7179   cmpxchg(/*addr*/ obj, /*expected*/ mark, /*new*/ t, Assembler::xword,
7180           /*acquire*/ true, /*release*/ false, /*weak*/ false, noreg);
7181   br(Assembler::NE, slow);
7182 
7183   bind(push);
7184   // After successful lock, push object on lock-stack.
7185   str(obj, Address(rthread, top));
7186   addw(top, top, oopSize);
7187   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7188 }
7189 
7190 // Implements fast-unlocking.
7191 //
7192 // - obj: the object to be unlocked
7193 // - t1, t2, t3: temporary registers
7194 // - slow: branched to if unlocking fails, absolute offset may larger than 32KB (imm14 encoding).
7195 void MacroAssembler::fast_unlock(Register obj, Register t1, Register t2, Register t3, Label& slow) {
7196   // cmpxchg clobbers rscratch1.
7197   assert_different_registers(obj, t1, t2, t3, rscratch1);
7198 
7199 #ifdef ASSERT
7200   {
7201     // Check for lock-stack underflow.
7202     Label stack_ok;
7203     ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
7204     cmpw(t1, (unsigned)LockStack::start_offset());
7205     br(Assembler::GE, stack_ok);
7206     STOP("Lock-stack underflow");
7207     bind(stack_ok);
7208   }
7209 #endif
7210 
7211   Label unlocked, push_and_slow;
7212   const Register top = t1;
7213   const Register mark = t2;
7214   const Register t = t3;
7215 
7216   // Check if obj is top of lock-stack.
7217   ldrw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7218   subw(top, top, oopSize);
7219   ldr(t, Address(rthread, top));
7220   cmp(obj, t);
7221   br(Assembler::NE, slow);
7222 
7223   // Pop lock-stack.
7224   DEBUG_ONLY(str(zr, Address(rthread, top));)
7225   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7226 
7227   // Check if recursive.
7228   subw(t, top, oopSize);
7229   ldr(t, Address(rthread, t));
7230   cmp(obj, t);
7231   br(Assembler::EQ, unlocked);
7232 
7233   // Not recursive. Check header for monitor (0b10).
7234   ldr(mark, Address(obj, oopDesc::mark_offset_in_bytes()));
7235   tbnz(mark, log2i_exact(markWord::monitor_value), push_and_slow);
7236 
7237 #ifdef ASSERT
7238   // Check header not unlocked (0b01).
7239   Label not_unlocked;
7240   tbz(mark, log2i_exact(markWord::unlocked_value), not_unlocked);
7241   stop("fast_unlock already unlocked");
7242   bind(not_unlocked);
7243 #endif
7244 
7245   // Try to unlock. Transition lock bits 0b00 => 0b01
7246   assert(oopDesc::mark_offset_in_bytes() == 0, "required to avoid lea");
7247   orr(t, mark, markWord::unlocked_value);
7248   cmpxchg(obj, mark, t, Assembler::xword,
7249           /*acquire*/ false, /*release*/ true, /*weak*/ false, noreg);
7250   br(Assembler::EQ, unlocked);
7251 
7252   bind(push_and_slow);
7253   // Restore lock-stack and handle the unlock in runtime.
7254   DEBUG_ONLY(str(obj, Address(rthread, top));)
7255   addw(top, top, oopSize);
7256   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7257   b(slow);
7258 
7259   bind(unlocked);
7260 }
7261 
7262 // Rotate using USHR and SLI instructions (or copy, if rotate count is zero)
7263 void MacroAssembler::neon_vector_rotate(FloatRegister dst, SIMD_Arrangement T,
7264                                         FloatRegister src, int shift_amount) {
7265   assert(src != dst, "did not expect src and dst to be the same register");
7266 
7267   int esize = BitsPerByte << (T / 2);
7268   int lshift = shift_amount & (esize - 1);
7269 
7270   if (lshift == 0) {
7271     // T & 1 == 0 => 64-bit arrangements, else 128-bit arrangements
7272     orr(dst, (T & 1) == 0 ? T8B : T16B, src, src);
7273   } else {
7274     ushr(dst, T, src, esize - lshift);
7275     sli(dst, T, src, lshift);
7276   }
7277 }
7278 
7279 void MacroAssembler::try_to_replace_prev_vector_copy_with_movprfx(FloatRegister dst) {
7280   if (code_section()->is_empty()) {
7281     return;
7282   }
7283 
7284   address prev = pc() - NativeInstruction::instruction_size;
7285   uint32_t insn = nativeInstruction_at(prev)->encoding();
7286   if (!NativeInstruction::is_neon_vector_mov_alias(insn) &&
7287       !NativeInstruction::is_sve_vector_mov_alias(insn)) {
7288     return;
7289   }
7290 
7291   // The destructive instruction must reuse the mov alias destination.
7292   uint32_t rd = Instruction_aarch64::extract(insn, 4, 0);
7293   if (rd != (uint32_t)dst->encoding()) {
7294     return;
7295   }
7296 
7297   uint32_t rn = Instruction_aarch64::extract(insn, 9, 5);
7298   Instruction_aarch64::patch(prev, 31, 0,
7299                              NativeInstruction::encode_sve_movprfx(rd, rn));
7300 }