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