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