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