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