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