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