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