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 // Handle the receiver type profile update given the "recv" klass.
2122 //
2123 // Normally updates the ReceiverData (RD) that starts at "mdp" + "mdp_offset".
2124 // If there are no matching or claimable receiver entries in RD, updates
2125 // the polymorphic counter.
2126 //
2127 // This code expected to run by either the interpreter or JIT-ed code, without
2128 // extra synchronization. For safety, receiver cells are claimed atomically, which
2129 // avoids grossly misrepresenting the profiles under concurrent updates. For speed,
2130 // counter updates are not atomic.
2131 //
2132 void MacroAssembler::profile_receiver_type(Register recv, Register mdp, int mdp_offset) {
2133   assert_different_registers(recv, mdp, rscratch1, rscratch2);
2134 
2135   int base_receiver_offset   = in_bytes(ReceiverTypeData::receiver_offset(0));
2136   int end_receiver_offset    = in_bytes(ReceiverTypeData::receiver_offset(ReceiverTypeData::row_limit()));
2137   int poly_count_offset      = in_bytes(CounterData::count_offset());
2138   int receiver_step          = in_bytes(ReceiverTypeData::receiver_offset(1)) - base_receiver_offset;
2139   int receiver_to_count_step = in_bytes(ReceiverTypeData::receiver_count_offset(0)) - base_receiver_offset;
2140 
2141   // Adjust for MDP offsets.
2142   base_receiver_offset += mdp_offset;
2143   end_receiver_offset  += mdp_offset;
2144   poly_count_offset    += mdp_offset;
2145 
2146 #ifdef ASSERT
2147   // We are about to walk the MDO slots without asking for offsets.
2148   // Check that our math hits all the right spots.
2149   for (uint c = 0; c < ReceiverTypeData::row_limit(); c++) {
2150     int real_recv_offset  = mdp_offset + in_bytes(ReceiverTypeData::receiver_offset(c));
2151     int real_count_offset = mdp_offset + in_bytes(ReceiverTypeData::receiver_count_offset(c));
2152     int offset = base_receiver_offset + receiver_step*c;
2153     int count_offset = offset + receiver_to_count_step;
2154     assert(offset == real_recv_offset, "receiver slot math");
2155     assert(count_offset == real_count_offset, "receiver count math");
2156   }
2157   int real_poly_count_offset = mdp_offset + in_bytes(CounterData::count_offset());
2158   assert(poly_count_offset == real_poly_count_offset, "poly counter math");
2159 #endif
2160 
2161   // Corner case: no profile table. Increment poly counter and exit.
2162   if (ReceiverTypeData::row_limit() == 0) {
2163     increment(Address(mdp, poly_count_offset), DataLayout::counter_increment);
2164     return;
2165   }
2166 
2167   Register offset = rscratch2;
2168 
2169   Label L_loop_search_receiver, L_loop_search_empty;
2170   Label L_restart, L_found_recv, L_found_empty, L_polymorphic, L_count_update;
2171 
2172   // The code here recognizes three major cases:
2173   //   A. Fastest: receiver found in the table
2174   //   B. Fast: no receiver in the table, and the table is full
2175   //   C. Slow: no receiver in the table, free slots in the table
2176   //
2177   // The case A performance is most important, as perfectly-behaved code would end up
2178   // there, especially with larger TypeProfileWidth. The case B performance is
2179   // important as well, this is where bulk of code would land for normally megamorphic
2180   // cases. The case C performance is not essential, its job is to deal with installation
2181   // races, we optimize for code density instead. Case C needs to make sure that receiver
2182   // rows are only claimed once. This makes sure we never overwrite a row for another
2183   // receiver and never duplicate the receivers in the list, making profile type-accurate.
2184   //
2185   // It is very tempting to handle these cases in a single loop, and claim the first slot
2186   // without checking the rest of the table. But, profiling code should tolerate free slots
2187   // in the table, as class unloading can clear them. After such cleanup, the receiver
2188   // we need might be _after_ the free slot. Therefore, we need to let at least full scan
2189   // to complete, before trying to install new slots. Splitting the code in several tight
2190   // loops also helpfully optimizes for cases A and B.
2191   //
2192   // This code is effectively:
2193   //
2194   // restart:
2195   //   // Fastest: receiver is already installed
2196   //   for (i = 0; i < receiver_count(); i++) {
2197   //     if (receiver(i) == recv) goto found_recv(i);
2198   //   }
2199   //
2200   //   // Fast: no receiver, but profile is full
2201   //   for (i = 0; i < receiver_count(); i++) {
2202   //     if (receiver(i) == null) goto found_null(i);
2203   //   }
2204   //   goto polymorphic
2205   //
2206   //   // Slow: try to install receiver
2207   // found_null(i):
2208   //   CAS(&receiver(i), null, recv);
2209   //   goto restart
2210   //
2211   // polymorphic:
2212   //   count++;
2213   //   return
2214   //
2215   // found_recv(i):
2216   //   *receiver_count(i)++
2217   //
2218 
2219   bind(L_restart);
2220 
2221   // Fastest: receiver is already installed
2222   mov(offset, base_receiver_offset);
2223   bind(L_loop_search_receiver);
2224     ldr(rscratch1, Address(mdp, offset));
2225     cmp(rscratch1, recv);
2226     br(Assembler::EQ, L_found_recv);
2227   add(offset, offset, receiver_step);
2228   sub(rscratch1, offset, end_receiver_offset);
2229   cbnz(rscratch1, L_loop_search_receiver);
2230 
2231   // Fast: no receiver, but profile is full
2232   mov(offset, base_receiver_offset);
2233   bind(L_loop_search_empty);
2234     ldr(rscratch1, Address(mdp, offset));
2235     cbz(rscratch1, L_found_empty);
2236   add(offset, offset, receiver_step);
2237   sub(rscratch1, offset, end_receiver_offset);
2238   cbnz(rscratch1, L_loop_search_empty);
2239   b(L_polymorphic);
2240 
2241   // Slow: try to install receiver
2242   bind(L_found_empty);
2243 
2244   // Atomically swing receiver slot: null -> recv.
2245   //
2246   // The update uses CAS, which clobbers rscratch1. Therefore, rscratch2
2247   // is used to hold the destination address. This is safe because the
2248   // offset is no longer needed after the address is computed.
2249 
2250   lea(rscratch2, Address(mdp, offset));
2251   cmpxchg(/*addr*/ rscratch2, /*expected*/ zr, /*new*/ recv, Assembler::xword,
2252           /*acquire*/ false, /*release*/ false, /*weak*/ true, noreg);
2253 
2254   // CAS success means the slot now has the receiver we want. CAS failure means
2255   // something had claimed the slot concurrently: it can be the same receiver we want,
2256   // or something else. Since this is a slow path, we can optimize for code density,
2257   // and just restart the search from the beginning.
2258   b(L_restart);
2259 
2260   // Counter updates:
2261 
2262   // Increment polymorphic counter instead of receiver slot.
2263   bind(L_polymorphic);
2264   mov(offset, poly_count_offset);
2265   b(L_count_update);
2266 
2267   // Found a receiver, convert its slot offset to corresponding count offset.
2268   bind(L_found_recv);
2269   add(offset, offset, receiver_to_count_step);
2270 
2271   bind(L_count_update);
2272   increment(Address(mdp, offset), DataLayout::counter_increment);
2273 }
2274 
2275 
2276 void MacroAssembler::call_VM_leaf_base(address entry_point,
2277                                        int number_of_arguments,
2278                                        Label *retaddr) {
2279   Label E, L;
2280 
2281   stp(rscratch1, rmethod, Address(pre(sp, -2 * wordSize)));
2282 
2283   mov(rscratch1, RuntimeAddress(entry_point));
2284   blr(rscratch1);
2285   if (retaddr)
2286     bind(*retaddr);
2287 
2288   ldp(rscratch1, rmethod, Address(post(sp, 2 * wordSize)));
2289 }
2290 
2291 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2292   call_VM_leaf_base(entry_point, number_of_arguments);
2293 }
2294 
2295 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2296   pass_arg0(this, arg_0);
2297   call_VM_leaf_base(entry_point, 1);
2298 }
2299 
2300 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2301   assert_different_registers(arg_1, c_rarg0);
2302   pass_arg0(this, arg_0);
2303   pass_arg1(this, arg_1);
2304   call_VM_leaf_base(entry_point, 2);
2305 }
2306 
2307 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0,
2308                                   Register arg_1, Register arg_2) {
2309   assert_different_registers(arg_1, c_rarg0);
2310   assert_different_registers(arg_2, c_rarg0, c_rarg1);
2311   pass_arg0(this, arg_0);
2312   pass_arg1(this, arg_1);
2313   pass_arg2(this, arg_2);
2314   call_VM_leaf_base(entry_point, 3);
2315 }
2316 
2317 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2318   pass_arg0(this, arg_0);
2319   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2320 }
2321 
2322 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2323 
2324   assert_different_registers(arg_0, c_rarg1);
2325   pass_arg1(this, arg_1);
2326   pass_arg0(this, arg_0);
2327   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2328 }
2329 
2330 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2331   assert_different_registers(arg_0, c_rarg1, c_rarg2);
2332   assert_different_registers(arg_1, c_rarg2);
2333   pass_arg2(this, arg_2);
2334   pass_arg1(this, arg_1);
2335   pass_arg0(this, arg_0);
2336   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2337 }
2338 
2339 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2340   assert_different_registers(arg_0, c_rarg1, c_rarg2, c_rarg3);
2341   assert_different_registers(arg_1, c_rarg2, c_rarg3);
2342   assert_different_registers(arg_2, c_rarg3);
2343   pass_arg3(this, arg_3);
2344   pass_arg2(this, arg_2);
2345   pass_arg1(this, arg_1);
2346   pass_arg0(this, arg_0);
2347   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2348 }
2349 
2350 void MacroAssembler::null_check(Register reg, int offset) {
2351   if (needs_explicit_null_check(offset)) {
2352     // provoke OS null exception if reg is null by
2353     // accessing M[reg] w/o changing any registers
2354     // NOTE: this is plenty to provoke a segv
2355     ldr(zr, Address(reg));
2356   } else {
2357     // nothing to do, (later) access of M[reg + offset]
2358     // will provoke OS null exception if reg is null
2359   }
2360 }
2361 
2362 // MacroAssembler protected routines needed to implement
2363 // public methods
2364 
2365 void MacroAssembler::mov(Register r, Address dest) {
2366   code_section()->relocate(pc(), dest.rspec());
2367   uint64_t imm64 = (uint64_t)dest.target();
2368   movptr(r, imm64);
2369 }
2370 
2371 // Move a constant pointer into r.  In AArch64 mode the virtual
2372 // address space is 48 bits in size, so we only need three
2373 // instructions to create a patchable instruction sequence that can
2374 // reach anywhere.
2375 void MacroAssembler::movptr(Register r, uintptr_t imm64) {
2376 #ifndef PRODUCT
2377   {
2378     char buffer[64];
2379     os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX64, (uint64_t)imm64);
2380     block_comment(buffer);
2381   }
2382 #endif
2383   assert(imm64 < (1ull << 48), "48-bit overflow in address constant");
2384   movz(r, imm64 & 0xffff);
2385   imm64 >>= 16;
2386   movk(r, imm64 & 0xffff, 16);
2387   imm64 >>= 16;
2388   movk(r, imm64 & 0xffff, 32);
2389 }
2390 
2391 // Macro to mov replicated immediate to vector register.
2392 // imm64: only the lower 8/16/32 bits are considered for B/H/S type. That is,
2393 //        the upper 56/48/32 bits must be zeros for B/H/S type.
2394 // Vd will get the following values for different arrangements in T
2395 //   imm64 == hex 000000gh  T8B:  Vd = ghghghghghghghgh
2396 //   imm64 == hex 000000gh  T16B: Vd = ghghghghghghghghghghghghghghghgh
2397 //   imm64 == hex 0000efgh  T4H:  Vd = efghefghefghefgh
2398 //   imm64 == hex 0000efgh  T8H:  Vd = efghefghefghefghefghefghefghefgh
2399 //   imm64 == hex abcdefgh  T2S:  Vd = abcdefghabcdefgh
2400 //   imm64 == hex abcdefgh  T4S:  Vd = abcdefghabcdefghabcdefghabcdefgh
2401 //   imm64 == hex abcdefgh  T1D:  Vd = 00000000abcdefgh
2402 //   imm64 == hex abcdefgh  T2D:  Vd = 00000000abcdefgh00000000abcdefgh
2403 // Clobbers rscratch1
2404 void MacroAssembler::mov(FloatRegister Vd, SIMD_Arrangement T, uint64_t imm64) {
2405   assert(T != T1Q, "unsupported");
2406   if (T == T1D || T == T2D) {
2407     int imm = operand_valid_for_movi_immediate(imm64, T);
2408     if (-1 != imm) {
2409       movi(Vd, T, imm);
2410     } else {
2411       mov(rscratch1, imm64);
2412       dup(Vd, T, rscratch1);
2413     }
2414     return;
2415   }
2416 
2417 #ifdef ASSERT
2418   if (T == T8B || T == T16B) assert((imm64 & ~0xff) == 0, "extraneous bits (T8B/T16B)");
2419   if (T == T4H || T == T8H) assert((imm64  & ~0xffff) == 0, "extraneous bits (T4H/T8H)");
2420   if (T == T2S || T == T4S) assert((imm64  & ~0xffffffff) == 0, "extraneous bits (T2S/T4S)");
2421 #endif
2422   int shift = operand_valid_for_movi_immediate(imm64, T);
2423   uint32_t imm32 = imm64 & 0xffffffffULL;
2424   if (shift >= 0) {
2425     movi(Vd, T, (imm32 >> shift) & 0xff, shift);
2426   } else {
2427     movw(rscratch1, imm32);
2428     dup(Vd, T, rscratch1);
2429   }
2430 }
2431 
2432 void MacroAssembler::mov_immediate64(Register dst, uint64_t imm64)
2433 {
2434 #ifndef PRODUCT
2435   {
2436     char buffer[64];
2437     os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX64, imm64);
2438     block_comment(buffer);
2439   }
2440 #endif
2441   if (operand_valid_for_logical_immediate(false, imm64)) {
2442     orr(dst, zr, imm64);
2443   } else {
2444     // we can use a combination of MOVZ or MOVN with
2445     // MOVK to build up the constant
2446     uint64_t imm_h[4];
2447     int zero_count = 0;
2448     int neg_count = 0;
2449     int i;
2450     for (i = 0; i < 4; i++) {
2451       imm_h[i] = ((imm64 >> (i * 16)) & 0xffffL);
2452       if (imm_h[i] == 0) {
2453         zero_count++;
2454       } else if (imm_h[i] == 0xffffL) {
2455         neg_count++;
2456       }
2457     }
2458     if (zero_count == 4) {
2459       // one MOVZ will do
2460       movz(dst, 0);
2461     } else if (neg_count == 4) {
2462       // one MOVN will do
2463       movn(dst, 0);
2464     } else if (zero_count == 3) {
2465       for (i = 0; i < 4; i++) {
2466         if (imm_h[i] != 0L) {
2467           movz(dst, (uint32_t)imm_h[i], (i << 4));
2468           break;
2469         }
2470       }
2471     } else if (neg_count == 3) {
2472       // one MOVN will do
2473       for (int i = 0; i < 4; i++) {
2474         if (imm_h[i] != 0xffffL) {
2475           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2476           break;
2477         }
2478       }
2479     } else if (zero_count == 2) {
2480       // one MOVZ and one MOVK will do
2481       for (i = 0; i < 3; i++) {
2482         if (imm_h[i] != 0L) {
2483           movz(dst, (uint32_t)imm_h[i], (i << 4));
2484           i++;
2485           break;
2486         }
2487       }
2488       for (;i < 4; i++) {
2489         if (imm_h[i] != 0L) {
2490           movk(dst, (uint32_t)imm_h[i], (i << 4));
2491         }
2492       }
2493     } else if (neg_count == 2) {
2494       // one MOVN and one MOVK will do
2495       for (i = 0; i < 4; i++) {
2496         if (imm_h[i] != 0xffffL) {
2497           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2498           i++;
2499           break;
2500         }
2501       }
2502       for (;i < 4; i++) {
2503         if (imm_h[i] != 0xffffL) {
2504           movk(dst, (uint32_t)imm_h[i], (i << 4));
2505         }
2506       }
2507     } else if (zero_count == 1) {
2508       // one MOVZ and two MOVKs will do
2509       for (i = 0; i < 4; i++) {
2510         if (imm_h[i] != 0L) {
2511           movz(dst, (uint32_t)imm_h[i], (i << 4));
2512           i++;
2513           break;
2514         }
2515       }
2516       for (;i < 4; i++) {
2517         if (imm_h[i] != 0x0L) {
2518           movk(dst, (uint32_t)imm_h[i], (i << 4));
2519         }
2520       }
2521     } else if (neg_count == 1) {
2522       // one MOVN and two MOVKs will do
2523       for (i = 0; i < 4; i++) {
2524         if (imm_h[i] != 0xffffL) {
2525           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
2526           i++;
2527           break;
2528         }
2529       }
2530       for (;i < 4; i++) {
2531         if (imm_h[i] != 0xffffL) {
2532           movk(dst, (uint32_t)imm_h[i], (i << 4));
2533         }
2534       }
2535     } else {
2536       // use a MOVZ and 3 MOVKs (makes it easier to debug)
2537       movz(dst, (uint32_t)imm_h[0], 0);
2538       for (i = 1; i < 4; i++) {
2539         movk(dst, (uint32_t)imm_h[i], (i << 4));
2540       }
2541     }
2542   }
2543 }
2544 
2545 void MacroAssembler::mov_immediate32(Register dst, uint32_t imm32)
2546 {
2547 #ifndef PRODUCT
2548     {
2549       char buffer[64];
2550       os::snprintf_checked(buffer, sizeof(buffer), "0x%" PRIX32, imm32);
2551       block_comment(buffer);
2552     }
2553 #endif
2554   if (operand_valid_for_logical_immediate(true, imm32)) {
2555     orrw(dst, zr, imm32);
2556   } else {
2557     // we can use MOVZ, MOVN or two calls to MOVK to build up the
2558     // constant
2559     uint32_t imm_h[2];
2560     imm_h[0] = imm32 & 0xffff;
2561     imm_h[1] = ((imm32 >> 16) & 0xffff);
2562     if (imm_h[0] == 0) {
2563       movzw(dst, imm_h[1], 16);
2564     } else if (imm_h[0] == 0xffff) {
2565       movnw(dst, imm_h[1] ^ 0xffff, 16);
2566     } else if (imm_h[1] == 0) {
2567       movzw(dst, imm_h[0], 0);
2568     } else if (imm_h[1] == 0xffff) {
2569       movnw(dst, imm_h[0] ^ 0xffff, 0);
2570     } else {
2571       // use a MOVZ and MOVK (makes it easier to debug)
2572       movzw(dst, imm_h[0], 0);
2573       movkw(dst, imm_h[1], 16);
2574     }
2575   }
2576 }
2577 
2578 // Form an address from base + offset in Rd.  Rd may or may
2579 // not actually be used: you must use the Address that is returned.
2580 // It is up to you to ensure that the shift provided matches the size
2581 // of your data.
2582 Address MacroAssembler::form_address(Register Rd, Register base, int64_t byte_offset, int shift) {
2583   if (Address::offset_ok_for_immed(byte_offset, shift))
2584     // It fits; no need for any heroics
2585     return Address(base, byte_offset);
2586 
2587   // Don't do anything clever with negative or misaligned offsets
2588   unsigned mask = (1 << shift) - 1;
2589   if (byte_offset < 0 || byte_offset & mask) {
2590     mov(Rd, byte_offset);
2591     add(Rd, base, Rd);
2592     return Address(Rd);
2593   }
2594 
2595   // See if we can do this with two 12-bit offsets
2596   {
2597     uint64_t word_offset = byte_offset >> shift;
2598     uint64_t masked_offset = word_offset & 0xfff000;
2599     if (Address::offset_ok_for_immed(word_offset - masked_offset, 0)
2600         && Assembler::operand_valid_for_add_sub_immediate(masked_offset << shift)) {
2601       add(Rd, base, masked_offset << shift);
2602       word_offset -= masked_offset;
2603       return Address(Rd, word_offset << shift);
2604     }
2605   }
2606 
2607   // Do it the hard way
2608   mov(Rd, byte_offset);
2609   add(Rd, base, Rd);
2610   return Address(Rd);
2611 }
2612 
2613 int MacroAssembler::corrected_idivl(Register result, Register ra, Register rb,
2614                                     bool want_remainder, Register scratch)
2615 {
2616   // Full implementation of Java idiv and irem.  The function
2617   // returns the (pc) offset of the div instruction - may be needed
2618   // for implicit exceptions.
2619   //
2620   // constraint : ra/rb =/= scratch
2621   //         normal case
2622   //
2623   // input : ra: dividend
2624   //         rb: divisor
2625   //
2626   // result: either
2627   //         quotient  (= ra idiv rb)
2628   //         remainder (= ra irem rb)
2629 
2630   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
2631 
2632   int idivl_offset = offset();
2633   if (! want_remainder) {
2634     sdivw(result, ra, rb);
2635   } else {
2636     sdivw(scratch, ra, rb);
2637     Assembler::msubw(result, scratch, rb, ra);
2638   }
2639 
2640   return idivl_offset;
2641 }
2642 
2643 int MacroAssembler::corrected_idivq(Register result, Register ra, Register rb,
2644                                     bool want_remainder, Register scratch)
2645 {
2646   // Full implementation of Java ldiv and lrem.  The function
2647   // returns the (pc) offset of the div instruction - may be needed
2648   // for implicit exceptions.
2649   //
2650   // constraint : ra/rb =/= scratch
2651   //         normal case
2652   //
2653   // input : ra: dividend
2654   //         rb: divisor
2655   //
2656   // result: either
2657   //         quotient  (= ra idiv rb)
2658   //         remainder (= ra irem rb)
2659 
2660   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
2661 
2662   int idivq_offset = offset();
2663   if (! want_remainder) {
2664     sdiv(result, ra, rb);
2665   } else {
2666     sdiv(scratch, ra, rb);
2667     Assembler::msub(result, scratch, rb, ra);
2668   }
2669 
2670   return idivq_offset;
2671 }
2672 
2673 void MacroAssembler::membar(Membar_mask_bits order_constraint) {
2674   address prev = pc() - NativeMembar::instruction_size;
2675   address last = code()->last_insn();
2676   if (last != nullptr && nativeInstruction_at(last)->is_Membar() && prev == last) {
2677     NativeMembar *bar = NativeMembar_at(prev);
2678     if (AlwaysMergeDMB) {
2679       bar->set_kind(bar->get_kind() | order_constraint);
2680       BLOCK_COMMENT("merged membar(always)");
2681       return;
2682     }
2683     // Don't promote DMB ST|DMB LD to DMB (a full barrier) because
2684     // doing so would introduce a StoreLoad which the caller did not
2685     // intend
2686     if (bar->get_kind() == order_constraint
2687         || bar->get_kind() == AnyAny
2688         || order_constraint == AnyAny) {
2689       // We are merging two memory barrier instructions.  On AArch64 we
2690       // can do this simply by ORing them together.
2691       bar->set_kind(bar->get_kind() | order_constraint);
2692       BLOCK_COMMENT("merged membar");
2693       return;
2694     } else {
2695       // A special case like "DMB ST;DMB LD;DMB ST", the last DMB can be skipped
2696       // We need check the last 2 instructions
2697       address prev2 = prev - NativeMembar::instruction_size;
2698       if (last != code()->last_label() && nativeInstruction_at(prev2)->is_Membar()) {
2699         NativeMembar *bar2 = NativeMembar_at(prev2);
2700         assert(bar2->get_kind() == order_constraint, "it should be merged before");
2701         BLOCK_COMMENT("merged membar(elided)");
2702         return;
2703       }
2704     }
2705   }
2706   code()->set_last_insn(pc());
2707   dmb(Assembler::barrier(order_constraint));
2708 }
2709 
2710 bool MacroAssembler::try_merge_ldst(Register rt, const Address &adr, size_t size_in_bytes, bool is_store) {
2711   if (ldst_can_merge(rt, adr, size_in_bytes, is_store)) {
2712     merge_ldst(rt, adr, size_in_bytes, is_store);
2713     code()->clear_last_insn();
2714     return true;
2715   } else {
2716     assert(size_in_bytes == 8 || size_in_bytes == 4, "only 8 bytes or 4 bytes load/store is supported.");
2717     const uint64_t mask = size_in_bytes - 1;
2718     if (adr.getMode() == Address::base_plus_offset &&
2719         (adr.offset() & mask) == 0) { // only supports base_plus_offset.
2720       code()->set_last_insn(pc());
2721     }
2722     return false;
2723   }
2724 }
2725 
2726 void MacroAssembler::ldr(Register Rx, const Address &adr) {
2727   // We always try to merge two adjacent loads into one ldp.
2728   if (!try_merge_ldst(Rx, adr, 8, false)) {
2729     Assembler::ldr(Rx, adr);
2730   }
2731 }
2732 
2733 void MacroAssembler::ldrw(Register Rw, const Address &adr) {
2734   // We always try to merge two adjacent loads into one ldp.
2735   if (!try_merge_ldst(Rw, adr, 4, false)) {
2736     Assembler::ldrw(Rw, adr);
2737   }
2738 }
2739 
2740 void MacroAssembler::str(Register Rx, const Address &adr) {
2741   // We always try to merge two adjacent stores into one stp.
2742   if (!try_merge_ldst(Rx, adr, 8, true)) {
2743     Assembler::str(Rx, adr);
2744   }
2745 }
2746 
2747 void MacroAssembler::strw(Register Rw, const Address &adr) {
2748   // We always try to merge two adjacent stores into one stp.
2749   if (!try_merge_ldst(Rw, adr, 4, true)) {
2750     Assembler::strw(Rw, adr);
2751   }
2752 }
2753 
2754 // MacroAssembler routines found actually to be needed
2755 
2756 void MacroAssembler::push(Register src)
2757 {
2758   str(src, Address(pre(esp, -1 * wordSize)));
2759 }
2760 
2761 void MacroAssembler::pop(Register dst)
2762 {
2763   ldr(dst, Address(post(esp, 1 * wordSize)));
2764 }
2765 
2766 // Note: load_unsigned_short used to be called load_unsigned_word.
2767 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
2768   int off = offset();
2769   ldrh(dst, src);
2770   return off;
2771 }
2772 
2773 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
2774   int off = offset();
2775   ldrb(dst, src);
2776   return off;
2777 }
2778 
2779 int MacroAssembler::load_signed_short(Register dst, Address src) {
2780   int off = offset();
2781   ldrsh(dst, src);
2782   return off;
2783 }
2784 
2785 int MacroAssembler::load_signed_byte(Register dst, Address src) {
2786   int off = offset();
2787   ldrsb(dst, src);
2788   return off;
2789 }
2790 
2791 int MacroAssembler::load_signed_short32(Register dst, Address src) {
2792   int off = offset();
2793   ldrshw(dst, src);
2794   return off;
2795 }
2796 
2797 int MacroAssembler::load_signed_byte32(Register dst, Address src) {
2798   int off = offset();
2799   ldrsbw(dst, src);
2800   return off;
2801 }
2802 
2803 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed) {
2804   switch (size_in_bytes) {
2805   case  8:  ldr(dst, src); break;
2806   case  4:  ldrw(dst, src); break;
2807   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
2808   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
2809   default:  ShouldNotReachHere();
2810   }
2811 }
2812 
2813 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes) {
2814   switch (size_in_bytes) {
2815   case  8:  str(src, dst); break;
2816   case  4:  strw(src, dst); break;
2817   case  2:  strh(src, dst); break;
2818   case  1:  strb(src, dst); break;
2819   default:  ShouldNotReachHere();
2820   }
2821 }
2822 
2823 void MacroAssembler::decrementw(Register reg, int value)
2824 {
2825   if (value < 0)  { incrementw(reg, -value);      return; }
2826   if (value == 0) {                               return; }
2827   if (value < (1 << 12)) { subw(reg, reg, value); return; }
2828   /* else */ {
2829     guarantee(reg != rscratch2, "invalid dst for register decrement");
2830     movw(rscratch2, (unsigned)value);
2831     subw(reg, reg, rscratch2);
2832   }
2833 }
2834 
2835 void MacroAssembler::decrement(Register reg, int value)
2836 {
2837   if (value < 0)  { increment(reg, -value);      return; }
2838   if (value == 0) {                              return; }
2839   if (value < (1 << 12)) { sub(reg, reg, value); return; }
2840   /* else */ {
2841     assert(reg != rscratch2, "invalid dst for register decrement");
2842     mov(rscratch2, (uint64_t)value);
2843     sub(reg, reg, rscratch2);
2844   }
2845 }
2846 
2847 void MacroAssembler::decrementw(Address dst, int value)
2848 {
2849   assert(!dst.uses(rscratch1), "invalid dst for address decrement");
2850   if (dst.getMode() == Address::literal) {
2851     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2852     lea(rscratch2, dst);
2853     dst = Address(rscratch2);
2854   }
2855   ldrw(rscratch1, dst);
2856   decrementw(rscratch1, value);
2857   strw(rscratch1, dst);
2858 }
2859 
2860 void MacroAssembler::decrement(Address dst, int value)
2861 {
2862   assert(!dst.uses(rscratch1), "invalid address for decrement");
2863   if (dst.getMode() == Address::literal) {
2864     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2865     lea(rscratch2, dst);
2866     dst = Address(rscratch2);
2867   }
2868   ldr(rscratch1, dst);
2869   decrement(rscratch1, value);
2870   str(rscratch1, dst);
2871 }
2872 
2873 void MacroAssembler::incrementw(Register reg, int value)
2874 {
2875   if (value < 0)  { decrementw(reg, -value);      return; }
2876   if (value == 0) {                               return; }
2877   if (value < (1 << 12)) { addw(reg, reg, value); return; }
2878   /* else */ {
2879     assert(reg != rscratch2, "invalid dst for register increment");
2880     movw(rscratch2, (unsigned)value);
2881     addw(reg, reg, rscratch2);
2882   }
2883 }
2884 
2885 void MacroAssembler::increment(Register reg, int value)
2886 {
2887   if (value < 0)  { decrement(reg, -value);      return; }
2888   if (value == 0) {                              return; }
2889   if (value < (1 << 12)) { add(reg, reg, value); return; }
2890   /* else */ {
2891     assert(reg != rscratch2, "invalid dst for register increment");
2892     movw(rscratch2, (unsigned)value);
2893     add(reg, reg, rscratch2);
2894   }
2895 }
2896 
2897 void MacroAssembler::incrementw(Address dst, int value)
2898 {
2899   assert(!dst.uses(rscratch1), "invalid dst for address increment");
2900   if (dst.getMode() == Address::literal) {
2901     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2902     lea(rscratch2, dst);
2903     dst = Address(rscratch2);
2904   }
2905   ldrw(rscratch1, dst);
2906   incrementw(rscratch1, value);
2907   strw(rscratch1, dst);
2908 }
2909 
2910 void MacroAssembler::increment(Address dst, int value)
2911 {
2912   assert(!dst.uses(rscratch1), "invalid dst for address increment");
2913   if (dst.getMode() == Address::literal) {
2914     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2915     lea(rscratch2, dst);
2916     dst = Address(rscratch2);
2917   }
2918   ldr(rscratch1, dst);
2919   increment(rscratch1, value);
2920   str(rscratch1, dst);
2921 }
2922 
2923 // Push lots of registers in the bit set supplied.  Don't push sp.
2924 // Return the number of words pushed
2925 int MacroAssembler::push(unsigned int bitset, Register stack) {
2926   int words_pushed = 0;
2927 
2928   // Scan bitset to accumulate register pairs
2929   unsigned char regs[32];
2930   int count = 0;
2931   for (int reg = 0; reg <= 30; reg++) {
2932     if (1 & bitset)
2933       regs[count++] = reg;
2934     bitset >>= 1;
2935   }
2936   regs[count++] = zr->raw_encoding();
2937   count &= ~1;  // Only push an even number of regs
2938 
2939   if (count) {
2940     stp(as_Register(regs[0]), as_Register(regs[1]),
2941        Address(pre(stack, -count * wordSize)));
2942     words_pushed += 2;
2943   }
2944   for (int i = 2; i < count; i += 2) {
2945     stp(as_Register(regs[i]), as_Register(regs[i+1]),
2946        Address(stack, i * wordSize));
2947     words_pushed += 2;
2948   }
2949 
2950   assert(words_pushed == count, "oops, pushed != count");
2951 
2952   return count;
2953 }
2954 
2955 int MacroAssembler::pop(unsigned int bitset, Register stack) {
2956   int words_pushed = 0;
2957 
2958   // Scan bitset to accumulate register pairs
2959   unsigned char regs[32];
2960   int count = 0;
2961   for (int reg = 0; reg <= 30; reg++) {
2962     if (1 & bitset)
2963       regs[count++] = reg;
2964     bitset >>= 1;
2965   }
2966   regs[count++] = zr->raw_encoding();
2967   count &= ~1;
2968 
2969   for (int i = 2; i < count; i += 2) {
2970     ldp(as_Register(regs[i]), as_Register(regs[i+1]),
2971        Address(stack, i * wordSize));
2972     words_pushed += 2;
2973   }
2974   if (count) {
2975     ldp(as_Register(regs[0]), as_Register(regs[1]),
2976        Address(post(stack, count * wordSize)));
2977     words_pushed += 2;
2978   }
2979 
2980   assert(words_pushed == count, "oops, pushed != count");
2981 
2982   return count;
2983 }
2984 
2985 // Push lots of registers in the bit set supplied.  Don't push sp.
2986 // Return the number of dwords pushed
2987 int MacroAssembler::push_fp(unsigned int bitset, Register stack, FpPushPopMode mode) {
2988   int words_pushed = 0;
2989   bool use_sve = false;
2990   int sve_vector_size_in_bytes = 0;
2991 
2992 #ifdef COMPILER2
2993   use_sve = Matcher::supports_scalable_vector();
2994   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
2995 #endif
2996 
2997   // Scan bitset to accumulate register pairs
2998   unsigned char regs[32];
2999   int count = 0;
3000   for (int reg = 0; reg <= 31; reg++) {
3001     if (1 & bitset)
3002       regs[count++] = reg;
3003     bitset >>= 1;
3004   }
3005 
3006   if (count == 0) {
3007     return 0;
3008   }
3009 
3010   if (mode == PushPopFull) {
3011     if (use_sve && sve_vector_size_in_bytes > 16) {
3012       mode = PushPopSVE;
3013     } else {
3014       mode = PushPopNeon;
3015     }
3016   }
3017 
3018 #ifndef PRODUCT
3019   {
3020     char buffer[48];
3021     if (mode == PushPopSVE) {
3022       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d SVE registers", count);
3023     } else if (mode == PushPopNeon) {
3024       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d Neon registers", count);
3025     } else {
3026       os::snprintf_checked(buffer, sizeof(buffer), "push_fp: %d fp registers", count);
3027     }
3028     block_comment(buffer);
3029   }
3030 #endif
3031 
3032   if (mode == PushPopSVE) {
3033     sub(stack, stack, sve_vector_size_in_bytes * count);
3034     for (int i = 0; i < count; i++) {
3035       sve_str(as_FloatRegister(regs[i]), Address(stack, i));
3036     }
3037     return count * sve_vector_size_in_bytes / 8;
3038   }
3039 
3040   if (mode == PushPopNeon) {
3041     if (count == 1) {
3042       strq(as_FloatRegister(regs[0]), Address(pre(stack, -wordSize * 2)));
3043       return 2;
3044     }
3045 
3046     bool odd = (count & 1) == 1;
3047     int push_slots = count + (odd ? 1 : 0);
3048 
3049     // Always pushing full 128 bit registers.
3050     stpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize * 2)));
3051     words_pushed += 2;
3052 
3053     for (int i = 2; i + 1 < count; i += 2) {
3054       stpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
3055       words_pushed += 2;
3056     }
3057 
3058     if (odd) {
3059       strq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
3060       words_pushed++;
3061     }
3062 
3063     assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
3064     return count * 2;
3065   }
3066 
3067   if (mode == PushPopFp) {
3068     bool odd = (count & 1) == 1;
3069     int push_slots = count + (odd ? 1 : 0);
3070 
3071     if (count == 1) {
3072       // Stack pointer must be 16 bytes aligned
3073       strd(as_FloatRegister(regs[0]), Address(pre(stack, -push_slots * wordSize)));
3074       return 1;
3075     }
3076 
3077     stpd(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize)));
3078     words_pushed += 2;
3079 
3080     for (int i = 2; i + 1 < count; i += 2) {
3081       stpd(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize));
3082       words_pushed += 2;
3083     }
3084 
3085     if (odd) {
3086       // Stack pointer must be 16 bytes aligned
3087       strd(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize));
3088       words_pushed++;
3089     }
3090 
3091     assert(words_pushed == count, "oops, pushed != count");
3092 
3093     return count;
3094   }
3095 
3096   return 0;
3097 }
3098 
3099 // Return the number of dwords popped
3100 int MacroAssembler::pop_fp(unsigned int bitset, Register stack, FpPushPopMode mode) {
3101   int words_pushed = 0;
3102   bool use_sve = false;
3103   int sve_vector_size_in_bytes = 0;
3104 
3105 #ifdef COMPILER2
3106   use_sve = Matcher::supports_scalable_vector();
3107   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
3108 #endif
3109   // Scan bitset to accumulate register pairs
3110   unsigned char regs[32];
3111   int count = 0;
3112   for (int reg = 0; reg <= 31; reg++) {
3113     if (1 & bitset)
3114       regs[count++] = reg;
3115     bitset >>= 1;
3116   }
3117 
3118   if (count == 0) {
3119     return 0;
3120   }
3121 
3122   if (mode == PushPopFull) {
3123     if (use_sve && sve_vector_size_in_bytes > 16) {
3124       mode = PushPopSVE;
3125     } else {
3126       mode = PushPopNeon;
3127     }
3128   }
3129 
3130 #ifndef PRODUCT
3131   {
3132     char buffer[48];
3133     if (mode == PushPopSVE) {
3134       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d SVE registers", count);
3135     } else if (mode == PushPopNeon) {
3136       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d Neon registers", count);
3137     } else {
3138       os::snprintf_checked(buffer, sizeof(buffer), "pop_fp: %d fp registers", count);
3139     }
3140     block_comment(buffer);
3141   }
3142 #endif
3143 
3144   if (mode == PushPopSVE) {
3145     for (int i = count - 1; i >= 0; i--) {
3146       sve_ldr(as_FloatRegister(regs[i]), Address(stack, i));
3147     }
3148     add(stack, stack, sve_vector_size_in_bytes * count);
3149     return count * sve_vector_size_in_bytes / 8;
3150   }
3151 
3152   if (mode == PushPopNeon) {
3153     if (count == 1) {
3154       ldrq(as_FloatRegister(regs[0]), Address(post(stack, wordSize * 2)));
3155       return 2;
3156     }
3157 
3158     bool odd = (count & 1) == 1;
3159     int push_slots = count + (odd ? 1 : 0);
3160 
3161     if (odd) {
3162       ldrq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
3163       words_pushed++;
3164     }
3165 
3166     for (int i = 2; i + 1 < count; i += 2) {
3167       ldpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
3168       words_pushed += 2;
3169     }
3170 
3171     ldpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize * 2)));
3172     words_pushed += 2;
3173 
3174     assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
3175 
3176     return count * 2;
3177   }
3178 
3179   if (mode == PushPopFp) {
3180     bool odd = (count & 1) == 1;
3181     int push_slots = count + (odd ? 1 : 0);
3182 
3183     if (count == 1) {
3184       ldrd(as_FloatRegister(regs[0]), Address(post(stack, push_slots * wordSize)));
3185       return 1;
3186     }
3187 
3188     if (odd) {
3189       ldrd(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize));
3190       words_pushed++;
3191     }
3192 
3193     for (int i = 2; i + 1 < count; i += 2) {
3194       ldpd(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize));
3195       words_pushed += 2;
3196     }
3197 
3198     ldpd(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize)));
3199     words_pushed += 2;
3200 
3201     assert(words_pushed == count, "oops, pushed != count");
3202 
3203     return count;
3204   }
3205 
3206   return 0;
3207 }
3208 
3209 // Return the number of dwords pushed
3210 int MacroAssembler::push_p(unsigned int bitset, Register stack) {
3211   bool use_sve = false;
3212   int sve_predicate_size_in_slots = 0;
3213 
3214 #ifdef COMPILER2
3215   use_sve = Matcher::supports_scalable_vector();
3216   if (use_sve) {
3217     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
3218   }
3219 #endif
3220 
3221   if (!use_sve) {
3222     return 0;
3223   }
3224 
3225   unsigned char regs[PRegister::number_of_registers];
3226   int count = 0;
3227   for (int reg = 0; reg < PRegister::number_of_registers; reg++) {
3228     if (1 & bitset)
3229       regs[count++] = reg;
3230     bitset >>= 1;
3231   }
3232 
3233   if (count == 0) {
3234     return 0;
3235   }
3236 
3237   int total_push_bytes = align_up(sve_predicate_size_in_slots *
3238                                   VMRegImpl::stack_slot_size * count, 16);
3239   sub(stack, stack, total_push_bytes);
3240   for (int i = 0; i < count; i++) {
3241     sve_str(as_PRegister(regs[i]), Address(stack, i));
3242   }
3243   return total_push_bytes / 8;
3244 }
3245 
3246 // Return the number of dwords popped
3247 int MacroAssembler::pop_p(unsigned int bitset, Register stack) {
3248   bool use_sve = false;
3249   int sve_predicate_size_in_slots = 0;
3250 
3251 #ifdef COMPILER2
3252   use_sve = Matcher::supports_scalable_vector();
3253   if (use_sve) {
3254     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
3255   }
3256 #endif
3257 
3258   if (!use_sve) {
3259     return 0;
3260   }
3261 
3262   unsigned char regs[PRegister::number_of_registers];
3263   int count = 0;
3264   for (int reg = 0; reg < PRegister::number_of_registers; reg++) {
3265     if (1 & bitset)
3266       regs[count++] = reg;
3267     bitset >>= 1;
3268   }
3269 
3270   if (count == 0) {
3271     return 0;
3272   }
3273 
3274   int total_pop_bytes = align_up(sve_predicate_size_in_slots *
3275                                  VMRegImpl::stack_slot_size * count, 16);
3276   for (int i = count - 1; i >= 0; i--) {
3277     sve_ldr(as_PRegister(regs[i]), Address(stack, i));
3278   }
3279   add(stack, stack, total_pop_bytes);
3280   return total_pop_bytes / 8;
3281 }
3282 
3283 #ifdef ASSERT
3284 void MacroAssembler::verify_heapbase(const char* msg) {
3285 #if 0
3286   assert (UseCompressedOops || UseCompressedClassPointers, "should be compressed");
3287   assert (Universe::heap() != nullptr, "java heap should be initialized");
3288   if (!UseCompressedOops || Universe::ptr_base() == nullptr) {
3289     // rheapbase is allocated as general register
3290     return;
3291   }
3292   if (CheckCompressedOops) {
3293     Label ok;
3294     push(1 << rscratch1->encoding(), sp); // cmpptr trashes rscratch1
3295     cmpptr(rheapbase, ExternalAddress(CompressedOops::base_addr()));
3296     br(Assembler::EQ, ok);
3297     stop(msg);
3298     bind(ok);
3299     pop(1 << rscratch1->encoding(), sp);
3300   }
3301 #endif
3302 }
3303 #endif
3304 
3305 void MacroAssembler::resolve_jobject(Register value, Register tmp1, Register tmp2) {
3306   assert_different_registers(value, tmp1, tmp2);
3307   Label done, tagged, weak_tagged;
3308 
3309   cbz(value, done);           // Use null as-is.
3310   tst(value, JNIHandles::tag_mask); // Test for tag.
3311   br(Assembler::NE, tagged);
3312 
3313   // Resolve local handle
3314   access_load_at(T_OBJECT, IN_NATIVE | AS_RAW, value, Address(value, 0), tmp1, tmp2);
3315   verify_oop(value);
3316   b(done);
3317 
3318   bind(tagged);
3319   STATIC_ASSERT(JNIHandles::TypeTag::weak_global == 0b1);
3320   tbnz(value, 0, weak_tagged);    // Test for weak tag.
3321 
3322   // Resolve global handle
3323   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, -JNIHandles::TypeTag::global), tmp1, tmp2);
3324   verify_oop(value);
3325   b(done);
3326 
3327   bind(weak_tagged);
3328   // Resolve jweak.
3329   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
3330                  value, Address(value, -JNIHandles::TypeTag::weak_global), tmp1, tmp2);
3331   verify_oop(value);
3332 
3333   bind(done);
3334 }
3335 
3336 void MacroAssembler::resolve_global_jobject(Register value, Register tmp1, Register tmp2) {
3337   assert_different_registers(value, tmp1, tmp2);
3338   Label done;
3339 
3340   cbz(value, done);           // Use null as-is.
3341 
3342 #ifdef ASSERT
3343   {
3344     STATIC_ASSERT(JNIHandles::TypeTag::global == 0b10);
3345     Label valid_global_tag;
3346     tbnz(value, 1, valid_global_tag); // Test for global tag
3347     stop("non global jobject using resolve_global_jobject");
3348     bind(valid_global_tag);
3349   }
3350 #endif
3351 
3352   // Resolve global handle
3353   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, -JNIHandles::TypeTag::global), tmp1, tmp2);
3354   verify_oop(value);
3355 
3356   bind(done);
3357 }
3358 
3359 void MacroAssembler::stop(const char* msg) {
3360   // Skip AOT caching C strings in scratch buffer.
3361   const char* str = (code_section()->scratch_emit()) ? msg : AOTCodeCache::add_C_string(msg);
3362   BLOCK_COMMENT(str);
3363   // load msg into r0 so we can access it from the signal handler
3364   // ExternalAddress enables saving and restoring via the code cache
3365   lea(c_rarg0, ExternalAddress((address) str));
3366   dcps1(0xdeae);
3367 }
3368 
3369 void MacroAssembler::unimplemented(const char* what) {
3370   const char* buf = nullptr;
3371   {
3372     ResourceMark rm;
3373     stringStream ss;
3374     ss.print("unimplemented: %s", what);
3375     buf = code_string(ss.as_string());
3376   }
3377   stop(buf);
3378 }
3379 
3380 void MacroAssembler::_assert_asm(Assembler::Condition cc, const char* msg) {
3381 #ifdef ASSERT
3382   Label OK;
3383   br(cc, OK);
3384   stop(msg);
3385   bind(OK);
3386 #endif
3387 }
3388 
3389 // If a constant does not fit in an immediate field, generate some
3390 // number of MOV instructions and then perform the operation.
3391 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, uint64_t imm,
3392                                            add_sub_imm_insn insn1,
3393                                            add_sub_reg_insn insn2,
3394                                            bool is32) {
3395   assert(Rd != zr, "Rd = zr and not setting flags?");
3396   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
3397   if (fits) {
3398     (this->*insn1)(Rd, Rn, imm);
3399   } else {
3400     if (g_uabs(imm) < (1 << 24)) {
3401        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
3402        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
3403     } else {
3404        assert_different_registers(Rd, Rn);
3405        mov(Rd, imm);
3406        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
3407     }
3408   }
3409 }
3410 
3411 // Separate vsn which sets the flags. Optimisations are more restricted
3412 // because we must set the flags correctly.
3413 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, uint64_t imm,
3414                                              add_sub_imm_insn insn1,
3415                                              add_sub_reg_insn insn2,
3416                                              bool is32) {
3417   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
3418   if (fits) {
3419     (this->*insn1)(Rd, Rn, imm);
3420   } else {
3421     assert_different_registers(Rd, Rn);
3422     assert(Rd != zr, "overflow in immediate operand");
3423     mov(Rd, imm);
3424     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
3425   }
3426 }
3427 
3428 
3429 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
3430   if (increment.is_register()) {
3431     add(Rd, Rn, increment.as_register());
3432   } else {
3433     add(Rd, Rn, increment.as_constant());
3434   }
3435 }
3436 
3437 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
3438   if (increment.is_register()) {
3439     addw(Rd, Rn, increment.as_register());
3440   } else {
3441     addw(Rd, Rn, increment.as_constant());
3442   }
3443 }
3444 
3445 void MacroAssembler::sub(Register Rd, Register Rn, RegisterOrConstant decrement) {
3446   if (decrement.is_register()) {
3447     sub(Rd, Rn, decrement.as_register());
3448   } else {
3449     sub(Rd, Rn, decrement.as_constant());
3450   }
3451 }
3452 
3453 void MacroAssembler::subw(Register Rd, Register Rn, RegisterOrConstant decrement) {
3454   if (decrement.is_register()) {
3455     subw(Rd, Rn, decrement.as_register());
3456   } else {
3457     subw(Rd, Rn, decrement.as_constant());
3458   }
3459 }
3460 
3461 void MacroAssembler::reinit_heapbase()
3462 {
3463   if (UseCompressedOops) {
3464     if (Universe::is_fully_initialized()) {
3465       mov(rheapbase, CompressedOops::base());
3466     } else {
3467       lea(rheapbase, ExternalAddress(CompressedOops::base_addr()));
3468       ldr(rheapbase, Address(rheapbase));
3469     }
3470   }
3471 }
3472 
3473 // A generic CAS; success or failure is in the EQ flag.  A weak CAS
3474 // doesn't retry and may fail spuriously.  If the oldval is wanted,
3475 // Pass a register for the result, otherwise pass noreg.
3476 
3477 // Clobbers rscratch1
3478 void MacroAssembler::cmpxchg(Register addr, Register expected,
3479                              Register new_val,
3480                              enum operand_size size,
3481                              bool acquire, bool release,
3482                              bool weak,
3483                              Register result) {
3484   if (result == noreg)  result = rscratch1;
3485   BLOCK_COMMENT("cmpxchg {");
3486   if (UseLSE) {
3487     mov(result, expected);
3488     lse_cas(result, new_val, addr, size, acquire, release, /*not_pair*/ true);
3489     compare_eq(result, expected, size);
3490 #ifdef ASSERT
3491     // Poison rscratch1 which is written on !UseLSE branch
3492     mov(rscratch1, 0x1f1f1f1f1f1f1f1f);
3493 #endif
3494   } else {
3495     Label retry_load, done;
3496     prfm(Address(addr), PSTL1STRM);
3497     bind(retry_load);
3498     load_exclusive(result, addr, size, acquire);
3499     compare_eq(result, expected, size);
3500     br(Assembler::NE, done);
3501     store_exclusive(rscratch1, new_val, addr, size, release);
3502     if (weak) {
3503       cmpw(rscratch1, 0u);  // If the store fails, return NE to our caller.
3504     } else {
3505       cbnzw(rscratch1, retry_load);
3506     }
3507     bind(done);
3508   }
3509   BLOCK_COMMENT("} cmpxchg");
3510 }
3511 
3512 // A generic comparison. Only compares for equality, clobbers rscratch1.
3513 void MacroAssembler::compare_eq(Register rm, Register rn, enum operand_size size) {
3514   if (size == xword) {
3515     cmp(rm, rn);
3516   } else if (size == word) {
3517     cmpw(rm, rn);
3518   } else if (size == halfword) {
3519     eorw(rscratch1, rm, rn);
3520     ands(zr, rscratch1, 0xffff);
3521   } else if (size == byte) {
3522     eorw(rscratch1, rm, rn);
3523     ands(zr, rscratch1, 0xff);
3524   } else {
3525     ShouldNotReachHere();
3526   }
3527 }
3528 
3529 
3530 static bool different(Register a, RegisterOrConstant b, Register c) {
3531   if (b.is_constant())
3532     return a != c;
3533   else
3534     return a != b.as_register() && a != c && b.as_register() != c;
3535 }
3536 
3537 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
3538 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
3539   if (UseLSE) {                                                         \
3540     prev = prev->is_valid() ? prev : zr;                                \
3541     if (incr.is_register()) {                                           \
3542       AOP(sz, incr.as_register(), prev, addr);                          \
3543     } else {                                                            \
3544       mov(rscratch2, incr.as_constant());                               \
3545       AOP(sz, rscratch2, prev, addr);                                   \
3546     }                                                                   \
3547     return;                                                             \
3548   }                                                                     \
3549   Register result = rscratch2;                                          \
3550   if (prev->is_valid())                                                 \
3551     result = different(prev, incr, addr) ? prev : rscratch2;            \
3552                                                                         \
3553   Label retry_load;                                                     \
3554   prfm(Address(addr), PSTL1STRM);                                       \
3555   bind(retry_load);                                                     \
3556   LDXR(result, addr);                                                   \
3557   OP(rscratch1, result, incr);                                          \
3558   STXR(rscratch2, rscratch1, addr);                                     \
3559   cbnzw(rscratch2, retry_load);                                         \
3560   if (prev->is_valid() && prev != result) {                             \
3561     IOP(prev, rscratch1, incr);                                         \
3562   }                                                                     \
3563 }
3564 
3565 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
3566 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
3567 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
3568 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
3569 
3570 #undef ATOMIC_OP
3571 
3572 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
3573 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
3574   if (UseLSE) {                                                         \
3575     prev = prev->is_valid() ? prev : zr;                                \
3576     AOP(sz, newv, prev, addr);                                          \
3577     return;                                                             \
3578   }                                                                     \
3579   Register result = rscratch2;                                          \
3580   if (prev->is_valid())                                                 \
3581     result = different(prev, newv, addr) ? prev : rscratch2;            \
3582                                                                         \
3583   Label retry_load;                                                     \
3584   prfm(Address(addr), PSTL1STRM);                                       \
3585   bind(retry_load);                                                     \
3586   LDXR(result, addr);                                                   \
3587   STXR(rscratch1, newv, addr);                                          \
3588   cbnzw(rscratch1, retry_load);                                         \
3589   if (prev->is_valid() && prev != result)                               \
3590     mov(prev, result);                                                  \
3591 }
3592 
3593 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
3594 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
3595 ATOMIC_XCHG(xchgl, swpl, ldxr, stlxr, Assembler::xword)
3596 ATOMIC_XCHG(xchglw, swpl, ldxrw, stlxrw, Assembler::word)
3597 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
3598 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
3599 
3600 #undef ATOMIC_XCHG
3601 
3602 #ifndef PRODUCT
3603 extern "C" void findpc(intptr_t x);
3604 #endif
3605 
3606 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
3607 {
3608   // In order to get locks to work, we need to fake a in_VM state
3609   if (ShowMessageBoxOnError ) {
3610     JavaThread* thread = JavaThread::current();
3611     JavaThreadState saved_state = thread->thread_state();
3612     thread->set_thread_state(_thread_in_vm);
3613 #ifndef PRODUCT
3614     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
3615       ttyLocker ttyl;
3616       BytecodeCounter::print();
3617     }
3618 #endif
3619     if (os::message_box(msg, "Execution stopped, print registers?")) {
3620       ttyLocker ttyl;
3621       tty->print_cr(" pc = 0x%016" PRIx64, pc);
3622 #ifndef PRODUCT
3623       tty->cr();
3624       findpc(pc);
3625       tty->cr();
3626 #endif
3627       tty->print_cr(" r0 = 0x%016" PRIx64, regs[0]);
3628       tty->print_cr(" r1 = 0x%016" PRIx64, regs[1]);
3629       tty->print_cr(" r2 = 0x%016" PRIx64, regs[2]);
3630       tty->print_cr(" r3 = 0x%016" PRIx64, regs[3]);
3631       tty->print_cr(" r4 = 0x%016" PRIx64, regs[4]);
3632       tty->print_cr(" r5 = 0x%016" PRIx64, regs[5]);
3633       tty->print_cr(" r6 = 0x%016" PRIx64, regs[6]);
3634       tty->print_cr(" r7 = 0x%016" PRIx64, regs[7]);
3635       tty->print_cr(" r8 = 0x%016" PRIx64, regs[8]);
3636       tty->print_cr(" r9 = 0x%016" PRIx64, regs[9]);
3637       tty->print_cr("r10 = 0x%016" PRIx64, regs[10]);
3638       tty->print_cr("r11 = 0x%016" PRIx64, regs[11]);
3639       tty->print_cr("r12 = 0x%016" PRIx64, regs[12]);
3640       tty->print_cr("r13 = 0x%016" PRIx64, regs[13]);
3641       tty->print_cr("r14 = 0x%016" PRIx64, regs[14]);
3642       tty->print_cr("r15 = 0x%016" PRIx64, regs[15]);
3643       tty->print_cr("r16 = 0x%016" PRIx64, regs[16]);
3644       tty->print_cr("r17 = 0x%016" PRIx64, regs[17]);
3645       tty->print_cr("r18 = 0x%016" PRIx64, regs[18]);
3646       tty->print_cr("r19 = 0x%016" PRIx64, regs[19]);
3647       tty->print_cr("r20 = 0x%016" PRIx64, regs[20]);
3648       tty->print_cr("r21 = 0x%016" PRIx64, regs[21]);
3649       tty->print_cr("r22 = 0x%016" PRIx64, regs[22]);
3650       tty->print_cr("r23 = 0x%016" PRIx64, regs[23]);
3651       tty->print_cr("r24 = 0x%016" PRIx64, regs[24]);
3652       tty->print_cr("r25 = 0x%016" PRIx64, regs[25]);
3653       tty->print_cr("r26 = 0x%016" PRIx64, regs[26]);
3654       tty->print_cr("r27 = 0x%016" PRIx64, regs[27]);
3655       tty->print_cr("r28 = 0x%016" PRIx64, regs[28]);
3656       tty->print_cr("r30 = 0x%016" PRIx64, regs[30]);
3657       tty->print_cr("r31 = 0x%016" PRIx64, regs[31]);
3658       BREAKPOINT;
3659     }
3660   }
3661   fatal("DEBUG MESSAGE: %s", msg);
3662 }
3663 
3664 RegSet MacroAssembler::call_clobbered_gp_registers() {
3665   RegSet regs = RegSet::range(r0, r17) - RegSet::of(rscratch1, rscratch2);
3666 #ifndef R18_RESERVED
3667   regs += r18_tls;
3668 #endif
3669   return regs;
3670 }
3671 
3672 void MacroAssembler::push_call_clobbered_registers_except(RegSet exclude) {
3673   int step = 4 * wordSize;
3674   push(call_clobbered_gp_registers() - exclude, sp);
3675   sub(sp, sp, step);
3676   mov(rscratch1, -step);
3677   // Push v0-v7, v16-v31.
3678   for (int i = 31; i>= 4; i -= 4) {
3679     if (i <= v7->encoding() || i >= v16->encoding())
3680       st1(as_FloatRegister(i-3), as_FloatRegister(i-2), as_FloatRegister(i-1),
3681           as_FloatRegister(i), T1D, Address(post(sp, rscratch1)));
3682   }
3683   st1(as_FloatRegister(0), as_FloatRegister(1), as_FloatRegister(2),
3684       as_FloatRegister(3), T1D, Address(sp));
3685 }
3686 
3687 void MacroAssembler::pop_call_clobbered_registers_except(RegSet exclude) {
3688   for (int i = 0; i < 32; i += 4) {
3689     if (i <= v7->encoding() || i >= v16->encoding())
3690       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3691           as_FloatRegister(i+3), T1D, Address(post(sp, 4 * wordSize)));
3692   }
3693 
3694   reinitialize_ptrue();
3695 
3696   pop(call_clobbered_gp_registers() - exclude, sp);
3697 }
3698 
3699 void MacroAssembler::push_CPU_state(bool save_vectors, bool use_sve,
3700                                     int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
3701   push(RegSet::range(r0, r29), sp); // integer registers except lr & sp
3702   if (save_vectors && use_sve && sve_vector_size_in_bytes > 16) {
3703     sub(sp, sp, sve_vector_size_in_bytes * FloatRegister::number_of_registers);
3704     for (int i = 0; i < FloatRegister::number_of_registers; i++) {
3705       sve_str(as_FloatRegister(i), Address(sp, i));
3706     }
3707   } else {
3708     int step = (save_vectors ? 8 : 4) * wordSize;
3709     mov(rscratch1, -step);
3710     sub(sp, sp, step);
3711     for (int i = 28; i >= 4; i -= 4) {
3712       st1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3713           as_FloatRegister(i+3), save_vectors ? T2D : T1D, Address(post(sp, rscratch1)));
3714     }
3715     st1(v0, v1, v2, v3, save_vectors ? T2D : T1D, sp);
3716   }
3717   if (save_vectors && use_sve && total_predicate_in_bytes > 0) {
3718     sub(sp, sp, total_predicate_in_bytes);
3719     for (int i = 0; i < PRegister::number_of_registers; i++) {
3720       sve_str(as_PRegister(i), Address(sp, i));
3721     }
3722   }
3723 }
3724 
3725 void MacroAssembler::pop_CPU_state(bool restore_vectors, bool use_sve,
3726                                    int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
3727   if (restore_vectors && use_sve && total_predicate_in_bytes > 0) {
3728     for (int i = PRegister::number_of_registers - 1; i >= 0; i--) {
3729       sve_ldr(as_PRegister(i), Address(sp, i));
3730     }
3731     add(sp, sp, total_predicate_in_bytes);
3732   }
3733   if (restore_vectors && use_sve && sve_vector_size_in_bytes > 16) {
3734     for (int i = FloatRegister::number_of_registers - 1; i >= 0; i--) {
3735       sve_ldr(as_FloatRegister(i), Address(sp, i));
3736     }
3737     add(sp, sp, sve_vector_size_in_bytes * FloatRegister::number_of_registers);
3738   } else {
3739     int step = (restore_vectors ? 8 : 4) * wordSize;
3740     for (int i = 0; i <= 28; i += 4)
3741       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3742           as_FloatRegister(i+3), restore_vectors ? T2D : T1D, Address(post(sp, step)));
3743   }
3744 
3745   // We may use predicate registers and rely on ptrue with SVE,
3746   // regardless of wide vector (> 8 bytes) used or not.
3747   if (use_sve) {
3748     reinitialize_ptrue();
3749   }
3750 
3751   // integer registers except lr & sp
3752   pop(RegSet::range(r0, r17), sp);
3753 #ifdef R18_RESERVED
3754   ldp(zr, r19, Address(post(sp, 2 * wordSize)));
3755   pop(RegSet::range(r20, r29), sp);
3756 #else
3757   pop(RegSet::range(r18_tls, r29), sp);
3758 #endif
3759 }
3760 
3761 /**
3762  * Helpers for multiply_to_len().
3763  */
3764 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
3765                                      Register src1, Register src2) {
3766   adds(dest_lo, dest_lo, src1);
3767   adc(dest_hi, dest_hi, zr);
3768   adds(dest_lo, dest_lo, src2);
3769   adc(final_dest_hi, dest_hi, zr);
3770 }
3771 
3772 // Generate an address from (r + r1 extend offset).  "size" is the
3773 // size of the operand.  The result may be in rscratch2.
3774 Address MacroAssembler::offsetted_address(Register r, Register r1,
3775                                           Address::extend ext, int offset, int size) {
3776   if (offset || (ext.shift() % size != 0)) {
3777     lea(rscratch2, Address(r, r1, ext));
3778     return Address(rscratch2, offset);
3779   } else {
3780     return Address(r, r1, ext);
3781   }
3782 }
3783 
3784 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
3785 {
3786   assert(offset >= 0, "spill to negative address?");
3787   // Offset reachable ?
3788   //   Not aligned - 9 bits signed offset
3789   //   Aligned - 12 bits unsigned offset shifted
3790   Register base = sp;
3791   if ((offset & (size-1)) && offset >= (1<<8)) {
3792     add(tmp, base, offset & ((1<<12)-1));
3793     base = tmp;
3794     offset &= -1u<<12;
3795   }
3796 
3797   if (offset >= (1<<12) * size) {
3798     add(tmp, base, offset & (((1<<12)-1)<<12));
3799     base = tmp;
3800     offset &= ~(((1<<12)-1)<<12);
3801   }
3802 
3803   return Address(base, offset);
3804 }
3805 
3806 Address MacroAssembler::sve_spill_address(int sve_reg_size_in_bytes, int offset, Register tmp) {
3807   assert(offset >= 0, "spill to negative address?");
3808 
3809   Register base = sp;
3810 
3811   // An immediate offset in the range 0 to 255 which is multiplied
3812   // by the current vector or predicate register size in bytes.
3813   if (offset % sve_reg_size_in_bytes == 0 && offset < ((1<<8)*sve_reg_size_in_bytes)) {
3814     return Address(base, offset / sve_reg_size_in_bytes);
3815   }
3816 
3817   add(tmp, base, offset);
3818   return Address(tmp);
3819 }
3820 
3821 // Checks whether offset is aligned.
3822 // Returns true if it is, else false.
3823 bool MacroAssembler::merge_alignment_check(Register base,
3824                                            size_t size,
3825                                            int64_t cur_offset,
3826                                            int64_t prev_offset) const {
3827   if (AvoidUnalignedAccesses) {
3828     if (base == sp) {
3829       // Checks whether low offset if aligned to pair of registers.
3830       int64_t pair_mask = size * 2 - 1;
3831       int64_t offset = prev_offset > cur_offset ? cur_offset : prev_offset;
3832       return (offset & pair_mask) == 0;
3833     } else { // If base is not sp, we can't guarantee the access is aligned.
3834       return false;
3835     }
3836   } else {
3837     int64_t mask = size - 1;
3838     // Load/store pair instruction only supports element size aligned offset.
3839     return (cur_offset & mask) == 0 && (prev_offset & mask) == 0;
3840   }
3841 }
3842 
3843 // Checks whether current and previous loads/stores can be merged.
3844 // Returns true if it can be merged, else false.
3845 bool MacroAssembler::ldst_can_merge(Register rt,
3846                                     const Address &adr,
3847                                     size_t cur_size_in_bytes,
3848                                     bool is_store) const {
3849   address prev = pc() - NativeInstruction::instruction_size;
3850   address last = code()->last_insn();
3851 
3852   if (last == nullptr || !nativeInstruction_at(last)->is_Imm_LdSt()) {
3853     return false;
3854   }
3855 
3856   if (adr.getMode() != Address::base_plus_offset || prev != last) {
3857     return false;
3858   }
3859 
3860   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
3861   size_t prev_size_in_bytes = prev_ldst->size_in_bytes();
3862 
3863   assert(prev_size_in_bytes == 4 || prev_size_in_bytes == 8, "only supports 64/32bit merging.");
3864   assert(cur_size_in_bytes == 4 || cur_size_in_bytes == 8, "only supports 64/32bit merging.");
3865 
3866   if (cur_size_in_bytes != prev_size_in_bytes || is_store != prev_ldst->is_store()) {
3867     return false;
3868   }
3869 
3870   int64_t max_offset = 63 * prev_size_in_bytes;
3871   int64_t min_offset = -64 * prev_size_in_bytes;
3872 
3873   assert(prev_ldst->is_not_pre_post_index(), "pre-index or post-index is not supported to be merged.");
3874 
3875   // Only same base can be merged.
3876   if (adr.base() != prev_ldst->base()) {
3877     return false;
3878   }
3879 
3880   int64_t cur_offset = adr.offset();
3881   int64_t prev_offset = prev_ldst->offset();
3882   size_t diff = abs(cur_offset - prev_offset);
3883   if (diff != prev_size_in_bytes) {
3884     return false;
3885   }
3886 
3887   // Following cases can not be merged:
3888   // ldr x2, [x2, #8]
3889   // ldr x3, [x2, #16]
3890   // or:
3891   // ldr x2, [x3, #8]
3892   // ldr x2, [x3, #16]
3893   // If t1 and t2 is the same in "ldp t1, t2, [xn, #imm]", we'll get SIGILL.
3894   if (!is_store && (adr.base() == prev_ldst->target() || rt == prev_ldst->target())) {
3895     return false;
3896   }
3897 
3898   int64_t low_offset = prev_offset > cur_offset ? cur_offset : prev_offset;
3899   // Offset range must be in ldp/stp instruction's range.
3900   if (low_offset > max_offset || low_offset < min_offset) {
3901     return false;
3902   }
3903 
3904   if (merge_alignment_check(adr.base(), prev_size_in_bytes, cur_offset, prev_offset)) {
3905     return true;
3906   }
3907 
3908   return false;
3909 }
3910 
3911 // Merge current load/store with previous load/store into ldp/stp.
3912 void MacroAssembler::merge_ldst(Register rt,
3913                                 const Address &adr,
3914                                 size_t cur_size_in_bytes,
3915                                 bool is_store) {
3916 
3917   assert(ldst_can_merge(rt, adr, cur_size_in_bytes, is_store) == true, "cur and prev must be able to be merged.");
3918 
3919   Register rt_low, rt_high;
3920   address prev = pc() - NativeInstruction::instruction_size;
3921   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
3922 
3923   int64_t offset;
3924 
3925   if (adr.offset() < prev_ldst->offset()) {
3926     offset = adr.offset();
3927     rt_low = rt;
3928     rt_high = prev_ldst->target();
3929   } else {
3930     offset = prev_ldst->offset();
3931     rt_low = prev_ldst->target();
3932     rt_high = rt;
3933   }
3934 
3935   Address adr_p = Address(prev_ldst->base(), offset);
3936   // Overwrite previous generated binary.
3937   code_section()->set_end(prev);
3938 
3939   const size_t sz = prev_ldst->size_in_bytes();
3940   assert(sz == 8 || sz == 4, "only supports 64/32bit merging.");
3941   if (!is_store) {
3942     BLOCK_COMMENT("merged ldr pair");
3943     if (sz == 8) {
3944       ldp(rt_low, rt_high, adr_p);
3945     } else {
3946       ldpw(rt_low, rt_high, adr_p);
3947     }
3948   } else {
3949     BLOCK_COMMENT("merged str pair");
3950     if (sz == 8) {
3951       stp(rt_low, rt_high, adr_p);
3952     } else {
3953       stpw(rt_low, rt_high, adr_p);
3954     }
3955   }
3956 }
3957 
3958 /**
3959  * Multiply 64 bit by 64 bit first loop.
3960  */
3961 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
3962                                            Register y, Register y_idx, Register z,
3963                                            Register carry, Register product,
3964                                            Register idx, Register kdx) {
3965   //
3966   //  jlong carry, x[], y[], z[];
3967   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
3968   //    huge_128 product = y[idx] * x[xstart] + carry;
3969   //    z[kdx] = (jlong)product;
3970   //    carry  = (jlong)(product >>> 64);
3971   //  }
3972   //  z[xstart] = carry;
3973   //
3974 
3975   Label L_first_loop, L_first_loop_exit;
3976   Label L_one_x, L_one_y, L_multiply;
3977 
3978   subsw(xstart, xstart, 1);
3979   br(Assembler::MI, L_one_x);
3980 
3981   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
3982   ldr(x_xstart, Address(rscratch1));
3983   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
3984 
3985   bind(L_first_loop);
3986   subsw(idx, idx, 1);
3987   br(Assembler::MI, L_first_loop_exit);
3988   subsw(idx, idx, 1);
3989   br(Assembler::MI, L_one_y);
3990   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
3991   ldr(y_idx, Address(rscratch1));
3992   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
3993   bind(L_multiply);
3994 
3995   // AArch64 has a multiply-accumulate instruction that we can't use
3996   // here because it has no way to process carries, so we have to use
3997   // separate add and adc instructions.  Bah.
3998   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
3999   mul(product, x_xstart, y_idx);
4000   adds(product, product, carry);
4001   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
4002 
4003   subw(kdx, kdx, 2);
4004   ror(product, product, 32); // back to big-endian
4005   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
4006 
4007   b(L_first_loop);
4008 
4009   bind(L_one_y);
4010   ldrw(y_idx, Address(y,  0));
4011   b(L_multiply);
4012 
4013   bind(L_one_x);
4014   ldrw(x_xstart, Address(x,  0));
4015   b(L_first_loop);
4016 
4017   bind(L_first_loop_exit);
4018 }
4019 
4020 /**
4021  * Multiply 128 bit by 128. Unrolled inner loop.
4022  *
4023  */
4024 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
4025                                              Register carry, Register carry2,
4026                                              Register idx, Register jdx,
4027                                              Register yz_idx1, Register yz_idx2,
4028                                              Register tmp, Register tmp3, Register tmp4,
4029                                              Register tmp6, Register product_hi) {
4030 
4031   //   jlong carry, x[], y[], z[];
4032   //   int kdx = ystart+1;
4033   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
4034   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
4035   //     jlong carry2  = (jlong)(tmp3 >>> 64);
4036   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
4037   //     carry  = (jlong)(tmp4 >>> 64);
4038   //     z[kdx+idx+1] = (jlong)tmp3;
4039   //     z[kdx+idx] = (jlong)tmp4;
4040   //   }
4041   //   idx += 2;
4042   //   if (idx > 0) {
4043   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
4044   //     z[kdx+idx] = (jlong)yz_idx1;
4045   //     carry  = (jlong)(yz_idx1 >>> 64);
4046   //   }
4047   //
4048 
4049   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
4050 
4051   lsrw(jdx, idx, 2);
4052 
4053   bind(L_third_loop);
4054 
4055   subsw(jdx, jdx, 1);
4056   br(Assembler::MI, L_third_loop_exit);
4057   subw(idx, idx, 4);
4058 
4059   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4060 
4061   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
4062 
4063   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4064 
4065   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
4066   ror(yz_idx2, yz_idx2, 32);
4067 
4068   ldp(rscratch2, rscratch1, Address(tmp6, 0));
4069 
4070   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
4071   umulh(tmp4, product_hi, yz_idx1);
4072 
4073   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
4074   ror(rscratch2, rscratch2, 32);
4075 
4076   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
4077   umulh(carry2, product_hi, yz_idx2);
4078 
4079   // propagate sum of both multiplications into carry:tmp4:tmp3
4080   adds(tmp3, tmp3, carry);
4081   adc(tmp4, tmp4, zr);
4082   adds(tmp3, tmp3, rscratch1);
4083   adcs(tmp4, tmp4, tmp);
4084   adc(carry, carry2, zr);
4085   adds(tmp4, tmp4, rscratch2);
4086   adc(carry, carry, zr);
4087 
4088   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
4089   ror(tmp4, tmp4, 32);
4090   stp(tmp4, tmp3, Address(tmp6, 0));
4091 
4092   b(L_third_loop);
4093   bind (L_third_loop_exit);
4094 
4095   andw (idx, idx, 0x3);
4096   cbz(idx, L_post_third_loop_done);
4097 
4098   Label L_check_1;
4099   subsw(idx, idx, 2);
4100   br(Assembler::MI, L_check_1);
4101 
4102   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4103   ldr(yz_idx1, Address(rscratch1, 0));
4104   ror(yz_idx1, yz_idx1, 32);
4105   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
4106   umulh(tmp4, product_hi, yz_idx1);
4107   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4108   ldr(yz_idx2, Address(rscratch1, 0));
4109   ror(yz_idx2, yz_idx2, 32);
4110 
4111   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
4112 
4113   ror(tmp3, tmp3, 32);
4114   str(tmp3, Address(rscratch1, 0));
4115 
4116   bind (L_check_1);
4117 
4118   andw (idx, idx, 0x1);
4119   subsw(idx, idx, 1);
4120   br(Assembler::MI, L_post_third_loop_done);
4121   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
4122   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
4123   umulh(carry2, tmp4, product_hi);
4124   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4125 
4126   add2_with_carry(carry2, tmp3, tmp4, carry);
4127 
4128   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
4129   extr(carry, carry2, tmp3, 32);
4130 
4131   bind(L_post_third_loop_done);
4132 }
4133 
4134 /**
4135  * Code for BigInteger::multiplyToLen() intrinsic.
4136  *
4137  * r0: x
4138  * r1: xlen
4139  * r2: y
4140  * r3: ylen
4141  * r4:  z
4142  * r5: tmp0
4143  * r10: tmp1
4144  * r11: tmp2
4145  * r12: tmp3
4146  * r13: tmp4
4147  * r14: tmp5
4148  * r15: tmp6
4149  * r16: tmp7
4150  *
4151  */
4152 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
4153                                      Register z, Register tmp0,
4154                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
4155                                      Register tmp5, Register tmp6, Register product_hi) {
4156 
4157   assert_different_registers(x, xlen, y, ylen, z, tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, product_hi);
4158 
4159   const Register idx = tmp1;
4160   const Register kdx = tmp2;
4161   const Register xstart = tmp3;
4162 
4163   const Register y_idx = tmp4;
4164   const Register carry = tmp5;
4165   const Register product  = xlen;
4166   const Register x_xstart = tmp0;
4167 
4168   // First Loop.
4169   //
4170   //  final static long LONG_MASK = 0xffffffffL;
4171   //  int xstart = xlen - 1;
4172   //  int ystart = ylen - 1;
4173   //  long carry = 0;
4174   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
4175   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
4176   //    z[kdx] = (int)product;
4177   //    carry = product >>> 32;
4178   //  }
4179   //  z[xstart] = (int)carry;
4180   //
4181 
4182   movw(idx, ylen);       // idx = ylen;
4183   addw(kdx, xlen, ylen); // kdx = xlen+ylen;
4184   mov(carry, zr);        // carry = 0;
4185 
4186   Label L_done;
4187 
4188   movw(xstart, xlen);
4189   subsw(xstart, xstart, 1);
4190   br(Assembler::MI, L_done);
4191 
4192   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
4193 
4194   Label L_second_loop;
4195   cbzw(kdx, L_second_loop);
4196 
4197   Label L_carry;
4198   subw(kdx, kdx, 1);
4199   cbzw(kdx, L_carry);
4200 
4201   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
4202   lsr(carry, carry, 32);
4203   subw(kdx, kdx, 1);
4204 
4205   bind(L_carry);
4206   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
4207 
4208   // Second and third (nested) loops.
4209   //
4210   // for (int i = xstart-1; i >= 0; i--) { // Second loop
4211   //   carry = 0;
4212   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
4213   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
4214   //                    (z[k] & LONG_MASK) + carry;
4215   //     z[k] = (int)product;
4216   //     carry = product >>> 32;
4217   //   }
4218   //   z[i] = (int)carry;
4219   // }
4220   //
4221   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
4222 
4223   const Register jdx = tmp1;
4224 
4225   bind(L_second_loop);
4226   mov(carry, zr);                // carry = 0;
4227   movw(jdx, ylen);               // j = ystart+1
4228 
4229   subsw(xstart, xstart, 1);      // i = xstart-1;
4230   br(Assembler::MI, L_done);
4231 
4232   str(z, Address(pre(sp, -4 * wordSize)));
4233 
4234   Label L_last_x;
4235   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
4236   subsw(xstart, xstart, 1);       // i = xstart-1;
4237   br(Assembler::MI, L_last_x);
4238 
4239   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
4240   ldr(product_hi, Address(rscratch1));
4241   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
4242 
4243   Label L_third_loop_prologue;
4244   bind(L_third_loop_prologue);
4245 
4246   str(ylen, Address(sp, wordSize));
4247   stp(x, xstart, Address(sp, 2 * wordSize));
4248   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
4249                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
4250   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
4251   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
4252 
4253   addw(tmp3, xlen, 1);
4254   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
4255   subsw(tmp3, tmp3, 1);
4256   br(Assembler::MI, L_done);
4257 
4258   lsr(carry, carry, 32);
4259   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
4260   b(L_second_loop);
4261 
4262   // Next infrequent code is moved outside loops.
4263   bind(L_last_x);
4264   ldrw(product_hi, Address(x,  0));
4265   b(L_third_loop_prologue);
4266 
4267   bind(L_done);
4268 }
4269 
4270 // Code for BigInteger::mulAdd intrinsic
4271 // out     = r0
4272 // in      = r1
4273 // offset  = r2  (already out.length-offset)
4274 // len     = r3
4275 // k       = r4
4276 //
4277 // pseudo code from java implementation:
4278 // carry = 0;
4279 // offset = out.length-offset - 1;
4280 // for (int j=len-1; j >= 0; j--) {
4281 //     product = (in[j] & LONG_MASK) * kLong + (out[offset] & LONG_MASK) + carry;
4282 //     out[offset--] = (int)product;
4283 //     carry = product >>> 32;
4284 // }
4285 // return (int)carry;
4286 void MacroAssembler::mul_add(Register out, Register in, Register offset,
4287       Register len, Register k) {
4288     Label LOOP, END;
4289     // pre-loop
4290     cmp(len, zr); // cmp, not cbz/cbnz: to use condition twice => less branches
4291     csel(out, zr, out, Assembler::EQ);
4292     br(Assembler::EQ, END);
4293     add(in, in, len, LSL, 2); // in[j+1] address
4294     add(offset, out, offset, LSL, 2); // out[offset + 1] address
4295     mov(out, zr); // used to keep carry now
4296     BIND(LOOP);
4297     ldrw(rscratch1, Address(pre(in, -4)));
4298     madd(rscratch1, rscratch1, k, out);
4299     ldrw(rscratch2, Address(pre(offset, -4)));
4300     add(rscratch1, rscratch1, rscratch2);
4301     strw(rscratch1, Address(offset));
4302     lsr(out, rscratch1, 32);
4303     subs(len, len, 1);
4304     br(Assembler::NE, LOOP);
4305     BIND(END);
4306 }
4307 
4308 /**
4309  * Emits code to update CRC-32 with a byte value according to constants in table
4310  *
4311  * @param [in,out]crc   Register containing the crc.
4312  * @param [in]val       Register containing the byte to fold into the CRC.
4313  * @param [in]table     Register containing the table of crc constants.
4314  *
4315  * uint32_t crc;
4316  * val = crc_table[(val ^ crc) & 0xFF];
4317  * crc = val ^ (crc >> 8);
4318  *
4319  */
4320 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
4321   eor(val, val, crc);
4322   andr(val, val, 0xff);
4323   ldrw(val, Address(table, val, Address::lsl(2)));
4324   eor(crc, val, crc, Assembler::LSR, 8);
4325 }
4326 
4327 /**
4328  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
4329  *
4330  * @param [in,out]crc   Register containing the crc.
4331  * @param [in]v         Register containing the 32-bit to fold into the CRC.
4332  * @param [in]table0    Register containing table 0 of crc constants.
4333  * @param [in]table1    Register containing table 1 of crc constants.
4334  * @param [in]table2    Register containing table 2 of crc constants.
4335  * @param [in]table3    Register containing table 3 of crc constants.
4336  *
4337  * uint32_t crc;
4338  *   v = crc ^ v
4339  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
4340  *
4341  */
4342 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
4343         Register table0, Register table1, Register table2, Register table3,
4344         bool upper) {
4345   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
4346   uxtb(tmp, v);
4347   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
4348   ubfx(tmp, v, 8, 8);
4349   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
4350   eor(crc, crc, tmp);
4351   ubfx(tmp, v, 16, 8);
4352   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
4353   eor(crc, crc, tmp);
4354   ubfx(tmp, v, 24, 8);
4355   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
4356   eor(crc, crc, tmp);
4357 }
4358 
4359 void MacroAssembler::kernel_crc32_using_crypto_pmull(Register crc, Register buf,
4360         Register len, Register tmp0, Register tmp1, Register tmp2, Register tmp3) {
4361     Label CRC_by4_loop, CRC_by1_loop, CRC_less128, CRC_by128_pre, CRC_by32_loop, CRC_less32, L_exit;
4362     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
4363 
4364     subs(tmp0, len, 384);
4365     mvnw(crc, crc);
4366     br(Assembler::GE, CRC_by128_pre);
4367   BIND(CRC_less128);
4368     subs(len, len, 32);
4369     br(Assembler::GE, CRC_by32_loop);
4370   BIND(CRC_less32);
4371     adds(len, len, 32 - 4);
4372     br(Assembler::GE, CRC_by4_loop);
4373     adds(len, len, 4);
4374     br(Assembler::GT, CRC_by1_loop);
4375     b(L_exit);
4376 
4377   BIND(CRC_by32_loop);
4378     ldp(tmp0, tmp1, Address(buf));
4379     crc32x(crc, crc, tmp0);
4380     ldp(tmp2, tmp3, Address(buf, 16));
4381     crc32x(crc, crc, tmp1);
4382     add(buf, buf, 32);
4383     crc32x(crc, crc, tmp2);
4384     subs(len, len, 32);
4385     crc32x(crc, crc, tmp3);
4386     br(Assembler::GE, CRC_by32_loop);
4387     cmn(len, (u1)32);
4388     br(Assembler::NE, CRC_less32);
4389     b(L_exit);
4390 
4391   BIND(CRC_by4_loop);
4392     ldrw(tmp0, Address(post(buf, 4)));
4393     subs(len, len, 4);
4394     crc32w(crc, crc, tmp0);
4395     br(Assembler::GE, CRC_by4_loop);
4396     adds(len, len, 4);
4397     br(Assembler::LE, L_exit);
4398   BIND(CRC_by1_loop);
4399     ldrb(tmp0, Address(post(buf, 1)));
4400     subs(len, len, 1);
4401     crc32b(crc, crc, tmp0);
4402     br(Assembler::GT, CRC_by1_loop);
4403     b(L_exit);
4404 
4405   BIND(CRC_by128_pre);
4406     kernel_crc32_common_fold_using_crypto_pmull(crc, buf, len, tmp0, tmp1, tmp2,
4407       4*256*sizeof(juint) + 8*sizeof(juint));
4408     mov(crc, 0);
4409     crc32x(crc, crc, tmp0);
4410     crc32x(crc, crc, tmp1);
4411 
4412     cbnz(len, CRC_less128);
4413 
4414   BIND(L_exit);
4415     mvnw(crc, crc);
4416 }
4417 
4418 void MacroAssembler::kernel_crc32_using_crc32(Register crc, Register buf,
4419         Register len, Register tmp0, Register tmp1, Register tmp2,
4420         Register tmp3) {
4421     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
4422     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
4423 
4424     mvnw(crc, crc);
4425 
4426     subs(len, len, 128);
4427     br(Assembler::GE, CRC_by64_pre);
4428   BIND(CRC_less64);
4429     adds(len, len, 128-32);
4430     br(Assembler::GE, CRC_by32_loop);
4431   BIND(CRC_less32);
4432     adds(len, len, 32-4);
4433     br(Assembler::GE, CRC_by4_loop);
4434     adds(len, len, 4);
4435     br(Assembler::GT, CRC_by1_loop);
4436     b(L_exit);
4437 
4438   BIND(CRC_by32_loop);
4439     ldp(tmp0, tmp1, Address(post(buf, 16)));
4440     subs(len, len, 32);
4441     crc32x(crc, crc, tmp0);
4442     ldr(tmp2, Address(post(buf, 8)));
4443     crc32x(crc, crc, tmp1);
4444     ldr(tmp3, Address(post(buf, 8)));
4445     crc32x(crc, crc, tmp2);
4446     crc32x(crc, crc, tmp3);
4447     br(Assembler::GE, CRC_by32_loop);
4448     cmn(len, (u1)32);
4449     br(Assembler::NE, CRC_less32);
4450     b(L_exit);
4451 
4452   BIND(CRC_by4_loop);
4453     ldrw(tmp0, Address(post(buf, 4)));
4454     subs(len, len, 4);
4455     crc32w(crc, crc, tmp0);
4456     br(Assembler::GE, CRC_by4_loop);
4457     adds(len, len, 4);
4458     br(Assembler::LE, L_exit);
4459   BIND(CRC_by1_loop);
4460     ldrb(tmp0, Address(post(buf, 1)));
4461     subs(len, len, 1);
4462     crc32b(crc, crc, tmp0);
4463     br(Assembler::GT, CRC_by1_loop);
4464     b(L_exit);
4465 
4466   BIND(CRC_by64_pre);
4467     sub(buf, buf, 8);
4468     ldp(tmp0, tmp1, Address(buf, 8));
4469     crc32x(crc, crc, tmp0);
4470     ldr(tmp2, Address(buf, 24));
4471     crc32x(crc, crc, tmp1);
4472     ldr(tmp3, Address(buf, 32));
4473     crc32x(crc, crc, tmp2);
4474     ldr(tmp0, Address(buf, 40));
4475     crc32x(crc, crc, tmp3);
4476     ldr(tmp1, Address(buf, 48));
4477     crc32x(crc, crc, tmp0);
4478     ldr(tmp2, Address(buf, 56));
4479     crc32x(crc, crc, tmp1);
4480     ldr(tmp3, Address(pre(buf, 64)));
4481 
4482     b(CRC_by64_loop);
4483 
4484     align(CodeEntryAlignment);
4485   BIND(CRC_by64_loop);
4486     subs(len, len, 64);
4487     crc32x(crc, crc, tmp2);
4488     ldr(tmp0, Address(buf, 8));
4489     crc32x(crc, crc, tmp3);
4490     ldr(tmp1, Address(buf, 16));
4491     crc32x(crc, crc, tmp0);
4492     ldr(tmp2, Address(buf, 24));
4493     crc32x(crc, crc, tmp1);
4494     ldr(tmp3, Address(buf, 32));
4495     crc32x(crc, crc, tmp2);
4496     ldr(tmp0, Address(buf, 40));
4497     crc32x(crc, crc, tmp3);
4498     ldr(tmp1, Address(buf, 48));
4499     crc32x(crc, crc, tmp0);
4500     ldr(tmp2, Address(buf, 56));
4501     crc32x(crc, crc, tmp1);
4502     ldr(tmp3, Address(pre(buf, 64)));
4503     br(Assembler::GE, CRC_by64_loop);
4504 
4505     // post-loop
4506     crc32x(crc, crc, tmp2);
4507     crc32x(crc, crc, tmp3);
4508 
4509     sub(len, len, 64);
4510     add(buf, buf, 8);
4511     cmn(len, (u1)128);
4512     br(Assembler::NE, CRC_less64);
4513   BIND(L_exit);
4514     mvnw(crc, crc);
4515 }
4516 
4517 /**
4518  * @param crc   register containing existing CRC (32-bit)
4519  * @param buf   register pointing to input byte buffer (byte*)
4520  * @param len   register containing number of bytes
4521  * @param table register that will contain address of CRC table
4522  * @param tmp   scratch register
4523  */
4524 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
4525         Register table0, Register table1, Register table2, Register table3,
4526         Register tmp, Register tmp2, Register tmp3) {
4527   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
4528 
4529   if (UseCryptoPmullForCRC32) {
4530       kernel_crc32_using_crypto_pmull(crc, buf, len, table0, table1, table2, table3);
4531       return;
4532   }
4533 
4534   if (UseCRC32) {
4535       kernel_crc32_using_crc32(crc, buf, len, table0, table1, table2, table3);
4536       return;
4537   }
4538 
4539     mvnw(crc, crc);
4540 
4541     {
4542       uint64_t offset;
4543       adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
4544       add(table0, table0, offset);
4545     }
4546     add(table1, table0, 1*256*sizeof(juint));
4547     add(table2, table0, 2*256*sizeof(juint));
4548     add(table3, table0, 3*256*sizeof(juint));
4549 
4550     { // Neon code start
4551       cmp(len, (u1)64);
4552       br(Assembler::LT, L_by16);
4553       eor(v16, T16B, v16, v16);
4554 
4555     Label L_fold;
4556 
4557       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
4558 
4559       ld1(v0, v1, T2D, post(buf, 32));
4560       ld1r(v4, T2D, post(tmp, 8));
4561       ld1r(v5, T2D, post(tmp, 8));
4562       ld1r(v6, T2D, post(tmp, 8));
4563       ld1r(v7, T2D, post(tmp, 8));
4564       mov(v16, S, 0, crc);
4565 
4566       eor(v0, T16B, v0, v16);
4567       sub(len, len, 64);
4568 
4569     BIND(L_fold);
4570       pmull(v22, T8H, v0, v5, T8B);
4571       pmull(v20, T8H, v0, v7, T8B);
4572       pmull(v23, T8H, v0, v4, T8B);
4573       pmull(v21, T8H, v0, v6, T8B);
4574 
4575       pmull2(v18, T8H, v0, v5, T16B);
4576       pmull2(v16, T8H, v0, v7, T16B);
4577       pmull2(v19, T8H, v0, v4, T16B);
4578       pmull2(v17, T8H, v0, v6, T16B);
4579 
4580       uzp1(v24, T8H, v20, v22);
4581       uzp2(v25, T8H, v20, v22);
4582       eor(v20, T16B, v24, v25);
4583 
4584       uzp1(v26, T8H, v16, v18);
4585       uzp2(v27, T8H, v16, v18);
4586       eor(v16, T16B, v26, v27);
4587 
4588       ushll2(v22, T4S, v20, T8H, 8);
4589       ushll(v20, T4S, v20, T4H, 8);
4590 
4591       ushll2(v18, T4S, v16, T8H, 8);
4592       ushll(v16, T4S, v16, T4H, 8);
4593 
4594       eor(v22, T16B, v23, v22);
4595       eor(v18, T16B, v19, v18);
4596       eor(v20, T16B, v21, v20);
4597       eor(v16, T16B, v17, v16);
4598 
4599       uzp1(v17, T2D, v16, v20);
4600       uzp2(v21, T2D, v16, v20);
4601       eor(v17, T16B, v17, v21);
4602 
4603       ushll2(v20, T2D, v17, T4S, 16);
4604       ushll(v16, T2D, v17, T2S, 16);
4605 
4606       eor(v20, T16B, v20, v22);
4607       eor(v16, T16B, v16, v18);
4608 
4609       uzp1(v17, T2D, v20, v16);
4610       uzp2(v21, T2D, v20, v16);
4611       eor(v28, T16B, v17, v21);
4612 
4613       pmull(v22, T8H, v1, v5, T8B);
4614       pmull(v20, T8H, v1, v7, T8B);
4615       pmull(v23, T8H, v1, v4, T8B);
4616       pmull(v21, T8H, v1, v6, T8B);
4617 
4618       pmull2(v18, T8H, v1, v5, T16B);
4619       pmull2(v16, T8H, v1, v7, T16B);
4620       pmull2(v19, T8H, v1, v4, T16B);
4621       pmull2(v17, T8H, v1, v6, T16B);
4622 
4623       ld1(v0, v1, T2D, post(buf, 32));
4624 
4625       uzp1(v24, T8H, v20, v22);
4626       uzp2(v25, T8H, v20, v22);
4627       eor(v20, T16B, v24, v25);
4628 
4629       uzp1(v26, T8H, v16, v18);
4630       uzp2(v27, T8H, v16, v18);
4631       eor(v16, T16B, v26, v27);
4632 
4633       ushll2(v22, T4S, v20, T8H, 8);
4634       ushll(v20, T4S, v20, T4H, 8);
4635 
4636       ushll2(v18, T4S, v16, T8H, 8);
4637       ushll(v16, T4S, v16, T4H, 8);
4638 
4639       eor(v22, T16B, v23, v22);
4640       eor(v18, T16B, v19, v18);
4641       eor(v20, T16B, v21, v20);
4642       eor(v16, T16B, v17, v16);
4643 
4644       uzp1(v17, T2D, v16, v20);
4645       uzp2(v21, T2D, v16, v20);
4646       eor(v16, T16B, v17, v21);
4647 
4648       ushll2(v20, T2D, v16, T4S, 16);
4649       ushll(v16, T2D, v16, T2S, 16);
4650 
4651       eor(v20, T16B, v22, v20);
4652       eor(v16, T16B, v16, v18);
4653 
4654       uzp1(v17, T2D, v20, v16);
4655       uzp2(v21, T2D, v20, v16);
4656       eor(v20, T16B, v17, v21);
4657 
4658       shl(v16, T2D, v28, 1);
4659       shl(v17, T2D, v20, 1);
4660 
4661       eor(v0, T16B, v0, v16);
4662       eor(v1, T16B, v1, v17);
4663 
4664       subs(len, len, 32);
4665       br(Assembler::GE, L_fold);
4666 
4667       mov(crc, 0);
4668       mov(tmp, v0, D, 0);
4669       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4670       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4671       mov(tmp, v0, D, 1);
4672       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4673       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4674       mov(tmp, v1, D, 0);
4675       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4676       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4677       mov(tmp, v1, D, 1);
4678       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4679       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4680 
4681       add(len, len, 32);
4682     } // Neon code end
4683 
4684   BIND(L_by16);
4685     subs(len, len, 16);
4686     br(Assembler::GE, L_by16_loop);
4687     adds(len, len, 16-4);
4688     br(Assembler::GE, L_by4_loop);
4689     adds(len, len, 4);
4690     br(Assembler::GT, L_by1_loop);
4691     b(L_exit);
4692 
4693   BIND(L_by4_loop);
4694     ldrw(tmp, Address(post(buf, 4)));
4695     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
4696     subs(len, len, 4);
4697     br(Assembler::GE, L_by4_loop);
4698     adds(len, len, 4);
4699     br(Assembler::LE, L_exit);
4700   BIND(L_by1_loop);
4701     subs(len, len, 1);
4702     ldrb(tmp, Address(post(buf, 1)));
4703     update_byte_crc32(crc, tmp, table0);
4704     br(Assembler::GT, L_by1_loop);
4705     b(L_exit);
4706 
4707     align(CodeEntryAlignment);
4708   BIND(L_by16_loop);
4709     subs(len, len, 16);
4710     ldp(tmp, tmp3, Address(post(buf, 16)));
4711     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4712     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4713     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
4714     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
4715     br(Assembler::GE, L_by16_loop);
4716     adds(len, len, 16-4);
4717     br(Assembler::GE, L_by4_loop);
4718     adds(len, len, 4);
4719     br(Assembler::GT, L_by1_loop);
4720   BIND(L_exit);
4721     mvnw(crc, crc);
4722 }
4723 
4724 void MacroAssembler::kernel_crc32c_using_crypto_pmull(Register crc, Register buf,
4725         Register len, Register tmp0, Register tmp1, Register tmp2, Register tmp3) {
4726     Label CRC_by4_loop, CRC_by1_loop, CRC_less128, CRC_by128_pre, CRC_by32_loop, CRC_less32, L_exit;
4727     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
4728 
4729     subs(tmp0, len, 384);
4730     br(Assembler::GE, CRC_by128_pre);
4731   BIND(CRC_less128);
4732     subs(len, len, 32);
4733     br(Assembler::GE, CRC_by32_loop);
4734   BIND(CRC_less32);
4735     adds(len, len, 32 - 4);
4736     br(Assembler::GE, CRC_by4_loop);
4737     adds(len, len, 4);
4738     br(Assembler::GT, CRC_by1_loop);
4739     b(L_exit);
4740 
4741   BIND(CRC_by32_loop);
4742     ldp(tmp0, tmp1, Address(buf));
4743     crc32cx(crc, crc, tmp0);
4744     ldr(tmp2, Address(buf, 16));
4745     crc32cx(crc, crc, tmp1);
4746     ldr(tmp3, Address(buf, 24));
4747     crc32cx(crc, crc, tmp2);
4748     add(buf, buf, 32);
4749     subs(len, len, 32);
4750     crc32cx(crc, crc, tmp3);
4751     br(Assembler::GE, CRC_by32_loop);
4752     cmn(len, (u1)32);
4753     br(Assembler::NE, CRC_less32);
4754     b(L_exit);
4755 
4756   BIND(CRC_by4_loop);
4757     ldrw(tmp0, Address(post(buf, 4)));
4758     subs(len, len, 4);
4759     crc32cw(crc, crc, tmp0);
4760     br(Assembler::GE, CRC_by4_loop);
4761     adds(len, len, 4);
4762     br(Assembler::LE, L_exit);
4763   BIND(CRC_by1_loop);
4764     ldrb(tmp0, Address(post(buf, 1)));
4765     subs(len, len, 1);
4766     crc32cb(crc, crc, tmp0);
4767     br(Assembler::GT, CRC_by1_loop);
4768     b(L_exit);
4769 
4770   BIND(CRC_by128_pre);
4771     kernel_crc32_common_fold_using_crypto_pmull(crc, buf, len, tmp0, tmp1, tmp2,
4772       4*256*sizeof(juint) + 8*sizeof(juint) + 0x50);
4773     mov(crc, 0);
4774     crc32cx(crc, crc, tmp0);
4775     crc32cx(crc, crc, tmp1);
4776 
4777     cbnz(len, CRC_less128);
4778 
4779   BIND(L_exit);
4780 }
4781 
4782 void MacroAssembler::kernel_crc32c_using_crc32c(Register crc, Register buf,
4783         Register len, Register tmp0, Register tmp1, Register tmp2,
4784         Register tmp3) {
4785     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
4786     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
4787 
4788     subs(len, len, 128);
4789     br(Assembler::GE, CRC_by64_pre);
4790   BIND(CRC_less64);
4791     adds(len, len, 128-32);
4792     br(Assembler::GE, CRC_by32_loop);
4793   BIND(CRC_less32);
4794     adds(len, len, 32-4);
4795     br(Assembler::GE, CRC_by4_loop);
4796     adds(len, len, 4);
4797     br(Assembler::GT, CRC_by1_loop);
4798     b(L_exit);
4799 
4800   BIND(CRC_by32_loop);
4801     ldp(tmp0, tmp1, Address(post(buf, 16)));
4802     subs(len, len, 32);
4803     crc32cx(crc, crc, tmp0);
4804     ldr(tmp2, Address(post(buf, 8)));
4805     crc32cx(crc, crc, tmp1);
4806     ldr(tmp3, Address(post(buf, 8)));
4807     crc32cx(crc, crc, tmp2);
4808     crc32cx(crc, crc, tmp3);
4809     br(Assembler::GE, CRC_by32_loop);
4810     cmn(len, (u1)32);
4811     br(Assembler::NE, CRC_less32);
4812     b(L_exit);
4813 
4814   BIND(CRC_by4_loop);
4815     ldrw(tmp0, Address(post(buf, 4)));
4816     subs(len, len, 4);
4817     crc32cw(crc, crc, tmp0);
4818     br(Assembler::GE, CRC_by4_loop);
4819     adds(len, len, 4);
4820     br(Assembler::LE, L_exit);
4821   BIND(CRC_by1_loop);
4822     ldrb(tmp0, Address(post(buf, 1)));
4823     subs(len, len, 1);
4824     crc32cb(crc, crc, tmp0);
4825     br(Assembler::GT, CRC_by1_loop);
4826     b(L_exit);
4827 
4828   BIND(CRC_by64_pre);
4829     sub(buf, buf, 8);
4830     ldp(tmp0, tmp1, Address(buf, 8));
4831     crc32cx(crc, crc, tmp0);
4832     ldr(tmp2, Address(buf, 24));
4833     crc32cx(crc, crc, tmp1);
4834     ldr(tmp3, Address(buf, 32));
4835     crc32cx(crc, crc, tmp2);
4836     ldr(tmp0, Address(buf, 40));
4837     crc32cx(crc, crc, tmp3);
4838     ldr(tmp1, Address(buf, 48));
4839     crc32cx(crc, crc, tmp0);
4840     ldr(tmp2, Address(buf, 56));
4841     crc32cx(crc, crc, tmp1);
4842     ldr(tmp3, Address(pre(buf, 64)));
4843 
4844     b(CRC_by64_loop);
4845 
4846     align(CodeEntryAlignment);
4847   BIND(CRC_by64_loop);
4848     subs(len, len, 64);
4849     crc32cx(crc, crc, tmp2);
4850     ldr(tmp0, Address(buf, 8));
4851     crc32cx(crc, crc, tmp3);
4852     ldr(tmp1, Address(buf, 16));
4853     crc32cx(crc, crc, tmp0);
4854     ldr(tmp2, Address(buf, 24));
4855     crc32cx(crc, crc, tmp1);
4856     ldr(tmp3, Address(buf, 32));
4857     crc32cx(crc, crc, tmp2);
4858     ldr(tmp0, Address(buf, 40));
4859     crc32cx(crc, crc, tmp3);
4860     ldr(tmp1, Address(buf, 48));
4861     crc32cx(crc, crc, tmp0);
4862     ldr(tmp2, Address(buf, 56));
4863     crc32cx(crc, crc, tmp1);
4864     ldr(tmp3, Address(pre(buf, 64)));
4865     br(Assembler::GE, CRC_by64_loop);
4866 
4867     // post-loop
4868     crc32cx(crc, crc, tmp2);
4869     crc32cx(crc, crc, tmp3);
4870 
4871     sub(len, len, 64);
4872     add(buf, buf, 8);
4873     cmn(len, (u1)128);
4874     br(Assembler::NE, CRC_less64);
4875   BIND(L_exit);
4876 }
4877 
4878 /**
4879  * @param crc   register containing existing CRC (32-bit)
4880  * @param buf   register pointing to input byte buffer (byte*)
4881  * @param len   register containing number of bytes
4882  * @param table register that will contain address of CRC table
4883  * @param tmp   scratch register
4884  */
4885 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
4886         Register table0, Register table1, Register table2, Register table3,
4887         Register tmp, Register tmp2, Register tmp3) {
4888   if (UseCryptoPmullForCRC32) {
4889     kernel_crc32c_using_crypto_pmull(crc, buf, len, table0, table1, table2, table3);
4890   } else {
4891     kernel_crc32c_using_crc32c(crc, buf, len, table0, table1, table2, table3);
4892   }
4893 }
4894 
4895 void MacroAssembler::kernel_crc32_common_fold_using_crypto_pmull(Register crc, Register buf,
4896         Register len, Register tmp0, Register tmp1, Register tmp2, size_t table_offset) {
4897     Label CRC_by128_loop;
4898     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
4899 
4900     sub(len, len, 256);
4901     Register table = tmp0;
4902     {
4903       uint64_t offset;
4904       adrp(table, ExternalAddress(StubRoutines::crc_table_addr()), offset);
4905       add(table, table, offset);
4906     }
4907     add(table, table, table_offset);
4908 
4909     // Registers v0..v7 are used as data registers.
4910     // Registers v16..v31 are used as tmp registers.
4911     sub(buf, buf, 0x10);
4912     ldrq(v0, Address(buf, 0x10));
4913     ldrq(v1, Address(buf, 0x20));
4914     ldrq(v2, Address(buf, 0x30));
4915     ldrq(v3, Address(buf, 0x40));
4916     ldrq(v4, Address(buf, 0x50));
4917     ldrq(v5, Address(buf, 0x60));
4918     ldrq(v6, Address(buf, 0x70));
4919     ldrq(v7, Address(pre(buf, 0x80)));
4920 
4921     movi(v31, T4S, 0);
4922     mov(v31, S, 0, crc);
4923     eor(v0, T16B, v0, v31);
4924 
4925     // Register v16 contains constants from the crc table.
4926     ldrq(v16, Address(table));
4927     b(CRC_by128_loop);
4928 
4929     align(OptoLoopAlignment);
4930   BIND(CRC_by128_loop);
4931     pmull (v17,  T1Q, v0, v16, T1D);
4932     pmull2(v18, T1Q, v0, v16, T2D);
4933     ldrq(v0, Address(buf, 0x10));
4934     eor3(v0, T16B, v17,  v18, v0);
4935 
4936     pmull (v19, T1Q, v1, v16, T1D);
4937     pmull2(v20, T1Q, v1, v16, T2D);
4938     ldrq(v1, Address(buf, 0x20));
4939     eor3(v1, T16B, v19, v20, v1);
4940 
4941     pmull (v21, T1Q, v2, v16, T1D);
4942     pmull2(v22, T1Q, v2, v16, T2D);
4943     ldrq(v2, Address(buf, 0x30));
4944     eor3(v2, T16B, v21, v22, v2);
4945 
4946     pmull (v23, T1Q, v3, v16, T1D);
4947     pmull2(v24, T1Q, v3, v16, T2D);
4948     ldrq(v3, Address(buf, 0x40));
4949     eor3(v3, T16B, v23, v24, v3);
4950 
4951     pmull (v25, T1Q, v4, v16, T1D);
4952     pmull2(v26, T1Q, v4, v16, T2D);
4953     ldrq(v4, Address(buf, 0x50));
4954     eor3(v4, T16B, v25, v26, v4);
4955 
4956     pmull (v27, T1Q, v5, v16, T1D);
4957     pmull2(v28, T1Q, v5, v16, T2D);
4958     ldrq(v5, Address(buf, 0x60));
4959     eor3(v5, T16B, v27, v28, v5);
4960 
4961     pmull (v29, T1Q, v6, v16, T1D);
4962     pmull2(v30, T1Q, v6, v16, T2D);
4963     ldrq(v6, Address(buf, 0x70));
4964     eor3(v6, T16B, v29, v30, v6);
4965 
4966     // Reuse registers v23, v24.
4967     // Using them won't block the first instruction of the next iteration.
4968     pmull (v23, T1Q, v7, v16, T1D);
4969     pmull2(v24, T1Q, v7, v16, T2D);
4970     ldrq(v7, Address(pre(buf, 0x80)));
4971     eor3(v7, T16B, v23, v24, v7);
4972 
4973     subs(len, len, 0x80);
4974     br(Assembler::GE, CRC_by128_loop);
4975 
4976     // fold into 512 bits
4977     // Use v31 for constants because v16 can be still in use.
4978     ldrq(v31, Address(table, 0x10));
4979 
4980     pmull (v17,  T1Q, v0, v31, T1D);
4981     pmull2(v18, T1Q, v0, v31, T2D);
4982     eor3(v0, T16B, v17, v18, v4);
4983 
4984     pmull (v19, T1Q, v1, v31, T1D);
4985     pmull2(v20, T1Q, v1, v31, T2D);
4986     eor3(v1, T16B, v19, v20, v5);
4987 
4988     pmull (v21, T1Q, v2, v31, T1D);
4989     pmull2(v22, T1Q, v2, v31, T2D);
4990     eor3(v2, T16B, v21, v22, v6);
4991 
4992     pmull (v23, T1Q, v3, v31, T1D);
4993     pmull2(v24, T1Q, v3, v31, T2D);
4994     eor3(v3, T16B, v23, v24, v7);
4995 
4996     // fold into 128 bits
4997     // Use v17 for constants because v31 can be still in use.
4998     ldrq(v17, Address(table, 0x20));
4999     pmull (v25, T1Q, v0, v17, T1D);
5000     pmull2(v26, T1Q, v0, v17, T2D);
5001     eor3(v3, T16B, v3, v25, v26);
5002 
5003     // Use v18 for constants because v17 can be still in use.
5004     ldrq(v18, Address(table, 0x30));
5005     pmull (v27, T1Q, v1, v18, T1D);
5006     pmull2(v28, T1Q, v1, v18, T2D);
5007     eor3(v3, T16B, v3, v27, v28);
5008 
5009     // Use v19 for constants because v18 can be still in use.
5010     ldrq(v19, Address(table, 0x40));
5011     pmull (v29, T1Q, v2, v19, T1D);
5012     pmull2(v30, T1Q, v2, v19, T2D);
5013     eor3(v0, T16B, v3, v29, v30);
5014 
5015     add(len, len, 0x80);
5016     add(buf, buf, 0x10);
5017 
5018     mov(tmp0, v0, D, 0);
5019     mov(tmp1, v0, D, 1);
5020 }
5021 
5022 void MacroAssembler::addptr(const Address &dst, int32_t src) {
5023   Address adr;
5024   switch(dst.getMode()) {
5025   case Address::base_plus_offset:
5026     // This is the expected mode, although we allow all the other
5027     // forms below.
5028     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
5029     break;
5030   default:
5031     lea(rscratch2, dst);
5032     adr = Address(rscratch2);
5033     break;
5034   }
5035   ldr(rscratch1, adr);
5036   add(rscratch1, rscratch1, src);
5037   str(rscratch1, adr);
5038 }
5039 
5040 void MacroAssembler::cmpptr(Register src1, Address src2) {
5041   uint64_t offset;
5042   adrp(rscratch1, src2, offset);
5043   ldr(rscratch1, Address(rscratch1, offset));
5044   cmp(src1, rscratch1);
5045 }
5046 
5047 void MacroAssembler::cmpoop(Register obj1, Register obj2) {
5048   cmp(obj1, obj2);
5049 }
5050 
5051 void MacroAssembler::load_method_holder_cld(Register rresult, Register rmethod) {
5052   load_method_holder(rresult, rmethod);
5053   ldr(rresult, Address(rresult, InstanceKlass::class_loader_data_offset()));
5054 }
5055 
5056 void MacroAssembler::load_method_holder(Register holder, Register method) {
5057   ldr(holder, Address(method, Method::const_offset()));                      // ConstMethod*
5058   ldr(holder, Address(holder, ConstMethod::constants_offset()));             // ConstantPool*
5059   ldr(holder, Address(holder, ConstantPool::pool_holder_offset()));          // InstanceKlass*
5060 }
5061 
5062 // Loads the obj's Klass* into dst.
5063 // Preserves all registers (incl src, rscratch1 and rscratch2).
5064 // Input:
5065 // src - the oop we want to load the klass from.
5066 // dst - output narrow klass.
5067 void MacroAssembler::load_narrow_klass_compact(Register dst, Register src) {
5068   assert(UseCompactObjectHeaders, "expects UseCompactObjectHeaders");
5069   ldr(dst, Address(src, oopDesc::mark_offset_in_bytes()));
5070   lsr(dst, dst, markWord::klass_shift);
5071 }
5072 
5073 void MacroAssembler::load_klass(Register dst, Register src) {
5074   if (UseCompactObjectHeaders) {
5075     load_narrow_klass_compact(dst, src);
5076     decode_klass_not_null(dst);
5077   } else if (UseCompressedClassPointers) {
5078     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5079     decode_klass_not_null(dst);
5080   } else {
5081     ldr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5082   }
5083 }
5084 
5085 void MacroAssembler::restore_cpu_control_state_after_jni(Register tmp1, Register tmp2) {
5086   if (RestoreMXCSROnJNICalls) {
5087     Label OK;
5088     get_fpcr(tmp1);
5089     mov(tmp2, tmp1);
5090     // Set FPCR to the state we need. We do want Round to Nearest. We
5091     // don't want non-IEEE rounding modes or floating-point traps.
5092     bfi(tmp1, zr, 22, 4); // Clear DN, FZ, and Rmode
5093     bfi(tmp1, zr, 8, 5);  // Clear exception-control bits (8-12)
5094     bfi(tmp1, zr, 0, 2);  // Clear AH:FIZ
5095     eor(tmp2, tmp1, tmp2);
5096     cbz(tmp2, OK);        // Only reset FPCR if it's wrong
5097     set_fpcr(tmp1);
5098     bind(OK);
5099   }
5100 }
5101 
5102 // ((OopHandle)result).resolve();
5103 void MacroAssembler::resolve_oop_handle(Register result, Register tmp1, Register tmp2) {
5104   // OopHandle::resolve is an indirection.
5105   access_load_at(T_OBJECT, IN_NATIVE, result, Address(result, 0), tmp1, tmp2);
5106 }
5107 
5108 // ((WeakHandle)result).resolve();
5109 void MacroAssembler::resolve_weak_handle(Register result, Register tmp1, Register tmp2) {
5110   assert_different_registers(result, tmp1, tmp2);
5111   Label resolved;
5112 
5113   // A null weak handle resolves to null.
5114   cbz(result, resolved);
5115 
5116   // Only 64 bit platforms support GCs that require a tmp register
5117   // WeakHandle::resolve is an indirection like jweak.
5118   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
5119                  result, Address(result), tmp1, tmp2);
5120   bind(resolved);
5121 }
5122 
5123 void MacroAssembler::load_mirror(Register dst, Register method, Register tmp1, Register tmp2) {
5124   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
5125   ldr(dst, Address(rmethod, Method::const_offset()));
5126   ldr(dst, Address(dst, ConstMethod::constants_offset()));
5127   ldr(dst, Address(dst, ConstantPool::pool_holder_offset()));
5128   ldr(dst, Address(dst, mirror_offset));
5129   resolve_oop_handle(dst, tmp1, tmp2);
5130 }
5131 
5132 void MacroAssembler::cmp_klass(Register obj, Register klass, Register tmp) {
5133   assert_different_registers(obj, klass, tmp);
5134   if (UseCompressedClassPointers) {
5135     if (UseCompactObjectHeaders) {
5136       load_narrow_klass_compact(tmp, obj);
5137     } else {
5138       ldrw(tmp, Address(obj, oopDesc::klass_offset_in_bytes()));
5139     }
5140     if (CompressedKlassPointers::base() == nullptr) {
5141       cmp(klass, tmp, LSL, CompressedKlassPointers::shift());
5142       return;
5143     } else if (((uint64_t)CompressedKlassPointers::base() & 0xffffffff) == 0
5144                && CompressedKlassPointers::shift() == 0) {
5145       // Only the bottom 32 bits matter
5146       cmpw(klass, tmp);
5147       return;
5148     }
5149     decode_klass_not_null(tmp);
5150   } else {
5151     ldr(tmp, Address(obj, oopDesc::klass_offset_in_bytes()));
5152   }
5153   cmp(klass, tmp);
5154 }
5155 
5156 void MacroAssembler::cmp_klasses_from_objects(Register obj1, Register obj2, Register tmp1, Register tmp2) {
5157   if (UseCompactObjectHeaders) {
5158     load_narrow_klass_compact(tmp1, obj1);
5159     load_narrow_klass_compact(tmp2,  obj2);
5160     cmpw(tmp1, tmp2);
5161   } else if (UseCompressedClassPointers) {
5162     ldrw(tmp1, Address(obj1, oopDesc::klass_offset_in_bytes()));
5163     ldrw(tmp2, Address(obj2, oopDesc::klass_offset_in_bytes()));
5164     cmpw(tmp1, tmp2);
5165   } else {
5166     ldr(tmp1, Address(obj1, oopDesc::klass_offset_in_bytes()));
5167     ldr(tmp2, Address(obj2, oopDesc::klass_offset_in_bytes()));
5168     cmp(tmp1, tmp2);
5169   }
5170 }
5171 
5172 void MacroAssembler::store_klass(Register dst, Register src) {
5173   // FIXME: Should this be a store release?  concurrent gcs assumes
5174   // klass length is valid if klass field is not null.
5175   assert(!UseCompactObjectHeaders, "not with compact headers");
5176   if (UseCompressedClassPointers) {
5177     encode_klass_not_null(src);
5178     strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
5179   } else {
5180     str(src, Address(dst, oopDesc::klass_offset_in_bytes()));
5181   }
5182 }
5183 
5184 void MacroAssembler::store_klass_gap(Register dst, Register src) {
5185   assert(!UseCompactObjectHeaders, "not with compact headers");
5186   if (UseCompressedClassPointers) {
5187     // Store to klass gap in destination
5188     strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
5189   }
5190 }
5191 
5192 // Algorithm must match CompressedOops::encode.
5193 void MacroAssembler::encode_heap_oop(Register d, Register s) {
5194 #ifdef ASSERT
5195   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
5196 #endif
5197   verify_oop_msg(s, "broken oop in encode_heap_oop");
5198   if (CompressedOops::base() == nullptr) {
5199     if (CompressedOops::shift() != 0) {
5200       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5201       lsr(d, s, LogMinObjAlignmentInBytes);
5202     } else {
5203       mov(d, s);
5204     }
5205   } else {
5206     subs(d, s, rheapbase);
5207     csel(d, d, zr, Assembler::HS);
5208     lsr(d, d, LogMinObjAlignmentInBytes);
5209 
5210     /*  Old algorithm: is this any worse?
5211     Label nonnull;
5212     cbnz(r, nonnull);
5213     sub(r, r, rheapbase);
5214     bind(nonnull);
5215     lsr(r, r, LogMinObjAlignmentInBytes);
5216     */
5217   }
5218 }
5219 
5220 void MacroAssembler::encode_heap_oop_not_null(Register r) {
5221 #ifdef ASSERT
5222   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
5223   if (CheckCompressedOops) {
5224     Label ok;
5225     cbnz(r, ok);
5226     stop("null oop passed to encode_heap_oop_not_null");
5227     bind(ok);
5228   }
5229 #endif
5230   verify_oop_msg(r, "broken oop in encode_heap_oop_not_null");
5231   if (CompressedOops::base() != nullptr) {
5232     sub(r, r, rheapbase);
5233   }
5234   if (CompressedOops::shift() != 0) {
5235     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5236     lsr(r, r, LogMinObjAlignmentInBytes);
5237   }
5238 }
5239 
5240 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
5241 #ifdef ASSERT
5242   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
5243   if (CheckCompressedOops) {
5244     Label ok;
5245     cbnz(src, ok);
5246     stop("null oop passed to encode_heap_oop_not_null2");
5247     bind(ok);
5248   }
5249 #endif
5250   verify_oop_msg(src, "broken oop in encode_heap_oop_not_null2");
5251 
5252   Register data = src;
5253   if (CompressedOops::base() != nullptr) {
5254     sub(dst, src, rheapbase);
5255     data = dst;
5256   }
5257   if (CompressedOops::shift() != 0) {
5258     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5259     lsr(dst, data, LogMinObjAlignmentInBytes);
5260     data = dst;
5261   }
5262   if (data == src)
5263     mov(dst, src);
5264 }
5265 
5266 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
5267 #ifdef ASSERT
5268   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
5269 #endif
5270   if (CompressedOops::base() == nullptr) {
5271     if (CompressedOops::shift() != 0) {
5272       lsl(d, s, CompressedOops::shift());
5273     } else if (d != s) {
5274       mov(d, s);
5275     }
5276   } else {
5277     Label done;
5278     if (d != s)
5279       mov(d, s);
5280     cbz(s, done);
5281     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
5282     bind(done);
5283   }
5284   verify_oop_msg(d, "broken oop in decode_heap_oop");
5285 }
5286 
5287 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
5288   assert (UseCompressedOops, "should only be used for compressed headers");
5289   assert (Universe::heap() != nullptr, "java heap should be initialized");
5290   // Cannot assert, unverified entry point counts instructions (see .ad file)
5291   // vtableStubs also counts instructions in pd_code_size_limit.
5292   // Also do not verify_oop as this is called by verify_oop.
5293   if (CompressedOops::shift() != 0) {
5294     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5295     if (CompressedOops::base() != nullptr) {
5296       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
5297     } else {
5298       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
5299     }
5300   } else {
5301     assert (CompressedOops::base() == nullptr, "sanity");
5302   }
5303 }
5304 
5305 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
5306   assert (UseCompressedOops, "should only be used for compressed headers");
5307   assert (Universe::heap() != nullptr, "java heap should be initialized");
5308   // Cannot assert, unverified entry point counts instructions (see .ad file)
5309   // vtableStubs also counts instructions in pd_code_size_limit.
5310   // Also do not verify_oop as this is called by verify_oop.
5311   if (CompressedOops::shift() != 0) {
5312     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
5313     if (CompressedOops::base() != nullptr) {
5314       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
5315     } else {
5316       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
5317     }
5318   } else {
5319     assert (CompressedOops::base() == nullptr, "sanity");
5320     if (dst != src) {
5321       mov(dst, src);
5322     }
5323   }
5324 }
5325 
5326 MacroAssembler::KlassDecodeMode MacroAssembler::_klass_decode_mode(KlassDecodeNone);
5327 
5328 MacroAssembler::KlassDecodeMode MacroAssembler::klass_decode_mode() {
5329   assert(Metaspace::initialized(), "metaspace not initialized yet");
5330   assert(_klass_decode_mode != KlassDecodeNone, "should be initialized");
5331   return _klass_decode_mode;
5332 }
5333 
5334 MacroAssembler::KlassDecodeMode  MacroAssembler::klass_decode_mode(address base, int shift, const size_t range) {
5335   assert(UseCompressedClassPointers, "not using compressed class pointers");
5336 
5337   // KlassDecodeMode shouldn't be set already.
5338   assert(_klass_decode_mode == KlassDecodeNone, "set once");
5339 
5340   if (base == nullptr) {
5341     return KlassDecodeZero;
5342   }
5343 
5344   if (operand_valid_for_logical_immediate(
5345         /*is32*/false, (uint64_t)base)) {
5346     const uint64_t range_mask = right_n_bits(log2i_ceil(range));
5347     if (((uint64_t)base & range_mask) == 0) {
5348       return KlassDecodeXor;
5349     }
5350   }
5351 
5352   const uint64_t shifted_base =
5353     (uint64_t)base >> shift;
5354   if ((shifted_base & 0xffff0000ffffffff) == 0) {
5355     return KlassDecodeMovk;
5356   }
5357 
5358   // No valid encoding.
5359   return KlassDecodeNone;
5360 }
5361 
5362 // Check if one of the above decoding modes will work for given base, shift and range.
5363 bool MacroAssembler::check_klass_decode_mode(address base, int shift, const size_t range) {
5364   return klass_decode_mode(base, shift, range) != KlassDecodeNone;
5365 }
5366 
5367 bool MacroAssembler::set_klass_decode_mode(address base, int shift, const size_t range) {
5368   _klass_decode_mode = klass_decode_mode(base, shift, range);
5369   return _klass_decode_mode != KlassDecodeNone;
5370 }
5371 
5372 static Register pick_different_tmp(Register dst, Register src) {
5373   auto tmps = RegSet::of(r0, r1, r2) - RegSet::of(src, dst);
5374   return *tmps.begin();
5375 }
5376 
5377 void MacroAssembler::encode_klass_not_null_for_aot(Register dst, Register src) {
5378   // we have to load the klass base from the AOT constants area but
5379   // not the shift because it is not allowed to change
5380   int shift = CompressedKlassPointers::shift();
5381   assert(shift >= 0 && shift <= CompressedKlassPointers::max_shift(), "unexpected compressed klass shift!");
5382   if (dst != src) {
5383     // we can load the base into dst, subtract it formthe src and shift down
5384     lea(dst, ExternalAddress(CompressedKlassPointers::base_addr()));
5385     ldr(dst, dst);
5386     sub(dst, src, dst);
5387     lsr(dst, dst, shift);
5388   } else {
5389     // we need an extra register in order to load the coop base
5390     Register tmp = pick_different_tmp(dst, src);
5391     RegSet regs = RegSet::of(tmp);
5392     push(regs, sp);
5393     lea(tmp, ExternalAddress(CompressedKlassPointers::base_addr()));
5394     ldr(tmp, tmp);
5395     sub(dst, src, tmp);
5396     lsr(dst, dst, shift);
5397     pop(regs, sp);
5398   }
5399 }
5400 
5401 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
5402   if (AOTCodeCache::is_on_for_dump()) {
5403     encode_klass_not_null_for_aot(dst, src);
5404     return;
5405   }
5406 
5407   switch (klass_decode_mode()) {
5408   case KlassDecodeZero:
5409     if (CompressedKlassPointers::shift() != 0) {
5410       lsr(dst, src, CompressedKlassPointers::shift());
5411     } else {
5412       if (dst != src) mov(dst, src);
5413     }
5414     break;
5415 
5416   case KlassDecodeXor:
5417     if (CompressedKlassPointers::shift() != 0) {
5418       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5419       lsr(dst, dst, CompressedKlassPointers::shift());
5420     } else {
5421       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5422     }
5423     break;
5424 
5425   case KlassDecodeMovk:
5426     if (CompressedKlassPointers::shift() != 0) {
5427       ubfx(dst, src, CompressedKlassPointers::shift(), 32);
5428     } else {
5429       movw(dst, src);
5430     }
5431     break;
5432 
5433   case KlassDecodeNone:
5434     ShouldNotReachHere();
5435     break;
5436   }
5437 }
5438 
5439 void MacroAssembler::encode_klass_not_null(Register r) {
5440   encode_klass_not_null(r, r);
5441 }
5442 
5443 void MacroAssembler::decode_klass_not_null_for_aot(Register dst, Register src) {
5444   // we have to load the klass base from the AOT constants area but
5445   // not the shift because it is not allowed to change
5446   int shift = CompressedKlassPointers::shift();
5447   assert(shift >= 0 && shift <= CompressedKlassPointers::max_shift(), "unexpected compressed klass shift!");
5448   if (dst != src) {
5449     // we can load the base into dst then add the offset with a suitable shift
5450     lea(dst, ExternalAddress(CompressedKlassPointers::base_addr()));
5451     ldr(dst, dst);
5452     add(dst, dst, src, LSL,  shift);
5453   } else {
5454     // we need an extra register in order to load the coop base
5455     Register tmp = pick_different_tmp(dst, src);
5456     RegSet regs = RegSet::of(tmp);
5457     push(regs, sp);
5458     lea(tmp, ExternalAddress(CompressedKlassPointers::base_addr()));
5459     ldr(tmp, tmp);
5460     add(dst, tmp,  src, LSL,  shift);
5461     pop(regs, sp);
5462   }
5463 }
5464 
5465 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
5466   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5467 
5468   if (AOTCodeCache::is_on_for_dump()) {
5469     decode_klass_not_null_for_aot(dst, src);
5470     return;
5471   }
5472 
5473   switch (klass_decode_mode()) {
5474   case KlassDecodeZero:
5475     if (CompressedKlassPointers::shift() != 0) {
5476       lsl(dst, src, CompressedKlassPointers::shift());
5477     } else {
5478       if (dst != src) mov(dst, src);
5479     }
5480     break;
5481 
5482   case KlassDecodeXor:
5483     if (CompressedKlassPointers::shift() != 0) {
5484       lsl(dst, src, CompressedKlassPointers::shift());
5485       eor(dst, dst, (uint64_t)CompressedKlassPointers::base());
5486     } else {
5487       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
5488     }
5489     break;
5490 
5491   case KlassDecodeMovk: {
5492     const uint64_t shifted_base =
5493       (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
5494 
5495     if (dst != src) movw(dst, src);
5496     movk(dst, shifted_base >> 32, 32);
5497 
5498     if (CompressedKlassPointers::shift() != 0) {
5499       lsl(dst, dst, CompressedKlassPointers::shift());
5500     }
5501 
5502     break;
5503   }
5504 
5505   case KlassDecodeNone:
5506     ShouldNotReachHere();
5507     break;
5508   }
5509 }
5510 
5511 void  MacroAssembler::decode_klass_not_null(Register r) {
5512   decode_klass_not_null(r, r);
5513 }
5514 
5515 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
5516 #ifdef ASSERT
5517   {
5518     ThreadInVMfromUnknown tiv;
5519     assert (UseCompressedOops, "should only be used for compressed oops");
5520     assert (Universe::heap() != nullptr, "java heap should be initialized");
5521     assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5522     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
5523   }
5524 #endif
5525   int oop_index = oop_recorder()->find_index(obj);
5526   InstructionMark im(this);
5527   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5528   code_section()->relocate(inst_mark(), rspec);
5529   movz(dst, 0xDEAD, 16);
5530   movk(dst, 0xBEEF);
5531 }
5532 
5533 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
5534   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5535   assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5536   int index = oop_recorder()->find_index(k);
5537 
5538   InstructionMark im(this);
5539   RelocationHolder rspec = metadata_Relocation::spec(index);
5540   code_section()->relocate(inst_mark(), rspec);
5541   narrowKlass nk = CompressedKlassPointers::encode(k);
5542   movz(dst, (nk >> 16), 16);
5543   movk(dst, nk & 0xffff);
5544 }
5545 
5546 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators,
5547                                     Register dst, Address src,
5548                                     Register tmp1, Register tmp2) {
5549   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5550   decorators = AccessInternal::decorator_fixup(decorators, type);
5551   bool as_raw = (decorators & AS_RAW) != 0;
5552   if (as_raw) {
5553     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, tmp2);
5554   } else {
5555     bs->load_at(this, decorators, type, dst, src, tmp1, tmp2);
5556   }
5557 }
5558 
5559 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators,
5560                                      Address dst, Register val,
5561                                      Register tmp1, Register tmp2, Register tmp3) {
5562   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5563   decorators = AccessInternal::decorator_fixup(decorators, type);
5564   bool as_raw = (decorators & AS_RAW) != 0;
5565   if (as_raw) {
5566     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
5567   } else {
5568     bs->store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
5569   }
5570 }
5571 
5572 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
5573                                    Register tmp2, DecoratorSet decorators) {
5574   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
5575 }
5576 
5577 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
5578                                             Register tmp2, DecoratorSet decorators) {
5579   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, tmp2);
5580 }
5581 
5582 void MacroAssembler::store_heap_oop(Address dst, Register val, Register tmp1,
5583                                     Register tmp2, Register tmp3, DecoratorSet decorators) {
5584   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, val, tmp1, tmp2, tmp3);
5585 }
5586 
5587 // Used for storing nulls.
5588 void MacroAssembler::store_heap_oop_null(Address dst) {
5589   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg, noreg);
5590 }
5591 
5592 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
5593   assert(oop_recorder() != nullptr, "this assembler needs a Recorder");
5594   int index = oop_recorder()->allocate_metadata_index(obj);
5595   RelocationHolder rspec = metadata_Relocation::spec(index);
5596   return Address((address)obj, rspec);
5597 }
5598 
5599 // Move an oop into a register.
5600 void MacroAssembler::movoop(Register dst, jobject obj) {
5601   int oop_index;
5602   if (obj == nullptr) {
5603     oop_index = oop_recorder()->allocate_oop_index(obj);
5604   } else {
5605 #ifdef ASSERT
5606     {
5607       ThreadInVMfromUnknown tiv;
5608       assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
5609     }
5610 #endif
5611     oop_index = oop_recorder()->find_index(obj);
5612   }
5613   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5614 
5615   if (BarrierSet::barrier_set()->barrier_set_assembler()->supports_instruction_patching()) {
5616     mov(dst, Address((address)obj, rspec));
5617   } else {
5618     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
5619     ldr(dst, Address(dummy, rspec));
5620   }
5621 }
5622 
5623 // Move a metadata address into a register.
5624 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
5625   int oop_index;
5626   if (obj == nullptr) {
5627     oop_index = oop_recorder()->allocate_metadata_index(obj);
5628   } else {
5629     oop_index = oop_recorder()->find_index(obj);
5630   }
5631   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
5632   mov(dst, Address((address)obj, rspec));
5633 }
5634 
5635 Address MacroAssembler::constant_oop_address(jobject obj) {
5636 #ifdef ASSERT
5637   {
5638     ThreadInVMfromUnknown tiv;
5639     assert(oop_recorder() != nullptr, "this assembler needs an OopRecorder");
5640     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "not an oop");
5641   }
5642 #endif
5643   int oop_index = oop_recorder()->find_index(obj);
5644   return Address((address)obj, oop_Relocation::spec(oop_index));
5645 }
5646 
5647 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5648 void MacroAssembler::tlab_allocate(Register obj,
5649                                    Register var_size_in_bytes,
5650                                    int con_size_in_bytes,
5651                                    Register t1,
5652                                    Register t2,
5653                                    Label& slow_case) {
5654   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
5655   bs->tlab_allocate(this, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
5656 }
5657 
5658 void MacroAssembler::verify_tlab() {
5659 #ifdef ASSERT
5660   if (UseTLAB && VerifyOops) {
5661     Label next, ok;
5662 
5663     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
5664 
5665     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
5666     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
5667     cmp(rscratch2, rscratch1);
5668     br(Assembler::HS, next);
5669     STOP("assert(top >= start)");
5670     should_not_reach_here();
5671 
5672     bind(next);
5673     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
5674     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
5675     cmp(rscratch2, rscratch1);
5676     br(Assembler::HS, ok);
5677     STOP("assert(top <= end)");
5678     should_not_reach_here();
5679 
5680     bind(ok);
5681     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
5682   }
5683 #endif
5684 }
5685 
5686 // Writes to stack successive pages until offset reached to check for
5687 // stack overflow + shadow pages.  This clobbers tmp.
5688 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
5689   assert_different_registers(tmp, size, rscratch1);
5690   mov(tmp, sp);
5691   // Bang stack for total size given plus shadow page size.
5692   // Bang one page at a time because large size can bang beyond yellow and
5693   // red zones.
5694   Label loop;
5695   mov(rscratch1, (int)os::vm_page_size());
5696   bind(loop);
5697   lea(tmp, Address(tmp, -(int)os::vm_page_size()));
5698   subsw(size, size, rscratch1);
5699   str(size, Address(tmp));
5700   br(Assembler::GT, loop);
5701 
5702   // Bang down shadow pages too.
5703   // At this point, (tmp-0) is the last address touched, so don't
5704   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
5705   // was post-decremented.)  Skip this address by starting at i=1, and
5706   // touch a few more pages below.  N.B.  It is important to touch all
5707   // the way down to and including i=StackShadowPages.
5708   for (int i = 0; i < (int)(StackOverflow::stack_shadow_zone_size() / (int)os::vm_page_size()) - 1; i++) {
5709     // this could be any sized move but this is can be a debugging crumb
5710     // so the bigger the better.
5711     lea(tmp, Address(tmp, -(int)os::vm_page_size()));
5712     str(size, Address(tmp));
5713   }
5714 }
5715 
5716 // Move the address of the polling page into dest.
5717 void MacroAssembler::get_polling_page(Register dest, relocInfo::relocType rtype) {
5718   ldr(dest, Address(rthread, JavaThread::polling_page_offset()));
5719 }
5720 
5721 // Read the polling page.  The address of the polling page must
5722 // already be in r.
5723 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
5724   address mark;
5725   {
5726     InstructionMark im(this);
5727     code_section()->relocate(inst_mark(), rtype);
5728     ldrw(zr, Address(r, 0));
5729     mark = inst_mark();
5730   }
5731   verify_cross_modify_fence_not_required();
5732   return mark;
5733 }
5734 
5735 void MacroAssembler::adrp(Register reg1, const Address &dest, uint64_t &byte_offset) {
5736   relocInfo::relocType rtype = dest.rspec().reloc()->type();
5737   uint64_t low_page = (uint64_t)CodeCache::low_bound() >> 12;
5738   uint64_t high_page = (uint64_t)(CodeCache::high_bound()-1) >> 12;
5739   uint64_t dest_page = (uint64_t)dest.target() >> 12;
5740   int64_t offset_low = dest_page - low_page;
5741   int64_t offset_high = dest_page - high_page;
5742 
5743   assert(is_valid_AArch64_address(dest.target()), "bad address");
5744   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
5745 
5746   InstructionMark im(this);
5747   code_section()->relocate(inst_mark(), dest.rspec());
5748   // 8143067: Ensure that the adrp can reach the dest from anywhere within
5749   // the code cache so that if it is relocated we know it will still reach
5750   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
5751     _adrp(reg1, dest.target());
5752   } else {
5753     uint64_t target = (uint64_t)dest.target();
5754     uint64_t adrp_target
5755       = (target & 0xffffffffULL) | ((uint64_t)pc() & 0xffff00000000ULL);
5756 
5757     _adrp(reg1, (address)adrp_target);
5758     movk(reg1, target >> 32, 32);
5759   }
5760   byte_offset = (uint64_t)dest.target() & 0xfff;
5761 }
5762 
5763 void MacroAssembler::load_byte_map_base(Register reg) {
5764   CardTableBarrierSet* ctbs = CardTableBarrierSet::barrier_set();
5765 
5766   // Strictly speaking the card table base isn't an address at all, and it might
5767   // even be negative. It is thus materialised as a constant.
5768   mov(reg, (uint64_t)ctbs->card_table_base_const());
5769 }
5770 
5771 void MacroAssembler::build_frame(int framesize) {
5772   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
5773   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
5774   protect_return_address();
5775   if (framesize < ((1 << 9) + 2 * wordSize)) {
5776     sub(sp, sp, framesize);
5777     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
5778     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
5779   } else {
5780     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
5781     if (PreserveFramePointer) mov(rfp, sp);
5782     if (framesize < ((1 << 12) + 2 * wordSize))
5783       sub(sp, sp, framesize - 2 * wordSize);
5784     else {
5785       mov(rscratch1, framesize - 2 * wordSize);
5786       sub(sp, sp, rscratch1);
5787     }
5788   }
5789   verify_cross_modify_fence_not_required();
5790 }
5791 
5792 void MacroAssembler::remove_frame(int framesize) {
5793   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
5794   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
5795   if (framesize < ((1 << 9) + 2 * wordSize)) {
5796     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
5797     add(sp, sp, framesize);
5798   } else {
5799     if (framesize < ((1 << 12) + 2 * wordSize))
5800       add(sp, sp, framesize - 2 * wordSize);
5801     else {
5802       mov(rscratch1, framesize - 2 * wordSize);
5803       add(sp, sp, rscratch1);
5804     }
5805     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
5806   }
5807   authenticate_return_address();
5808 }
5809 
5810 
5811 // This method counts leading positive bytes (highest bit not set) in provided byte array
5812 address MacroAssembler::count_positives(Register ary1, Register len, Register result) {
5813     // Simple and most common case of aligned small array which is not at the
5814     // end of memory page is placed here. All other cases are in stub.
5815     Label LOOP, END, STUB, STUB_LONG, SET_RESULT, DONE;
5816     const uint64_t UPPER_BIT_MASK=0x8080808080808080;
5817     assert_different_registers(ary1, len, result);
5818 
5819     mov(result, len);
5820     cmpw(len, 0);
5821     br(LE, DONE);
5822     cmpw(len, 4 * wordSize);
5823     br(GE, STUB_LONG); // size > 32 then go to stub
5824 
5825     int shift = 64 - exact_log2(os::vm_page_size());
5826     lsl(rscratch1, ary1, shift);
5827     mov(rscratch2, (size_t)(4 * wordSize) << shift);
5828     adds(rscratch2, rscratch1, rscratch2);  // At end of page?
5829     br(CS, STUB); // at the end of page then go to stub
5830     subs(len, len, wordSize);
5831     br(LT, END);
5832 
5833   BIND(LOOP);
5834     ldr(rscratch1, Address(post(ary1, wordSize)));
5835     tst(rscratch1, UPPER_BIT_MASK);
5836     br(NE, SET_RESULT);
5837     subs(len, len, wordSize);
5838     br(GE, LOOP);
5839     cmpw(len, -wordSize);
5840     br(EQ, DONE);
5841 
5842   BIND(END);
5843     ldr(rscratch1, Address(ary1));
5844     sub(rscratch2, zr, len, LSL, 3); // LSL 3 is to get bits from bytes
5845     lslv(rscratch1, rscratch1, rscratch2);
5846     tst(rscratch1, UPPER_BIT_MASK);
5847     br(NE, SET_RESULT);
5848     b(DONE);
5849 
5850   BIND(STUB);
5851     RuntimeAddress count_pos = RuntimeAddress(StubRoutines::aarch64::count_positives());
5852     assert(count_pos.target() != nullptr, "count_positives stub has not been generated");
5853     address tpc1 = trampoline_call(count_pos);
5854     if (tpc1 == nullptr) {
5855       DEBUG_ONLY(reset_labels(STUB_LONG, SET_RESULT, DONE));
5856       postcond(pc() == badAddress);
5857       return nullptr;
5858     }
5859     b(DONE);
5860 
5861   BIND(STUB_LONG);
5862     RuntimeAddress count_pos_long = RuntimeAddress(StubRoutines::aarch64::count_positives_long());
5863     assert(count_pos_long.target() != nullptr, "count_positives_long stub has not been generated");
5864     address tpc2 = trampoline_call(count_pos_long);
5865     if (tpc2 == nullptr) {
5866       DEBUG_ONLY(reset_labels(SET_RESULT, DONE));
5867       postcond(pc() == badAddress);
5868       return nullptr;
5869     }
5870     b(DONE);
5871 
5872   BIND(SET_RESULT);
5873 
5874     add(len, len, wordSize);
5875     sub(result, result, len);
5876 
5877   BIND(DONE);
5878   postcond(pc() != badAddress);
5879   return pc();
5880 }
5881 
5882 // Clobbers: rscratch1, rscratch2, rflags
5883 // May also clobber v0-v7 when (!UseSimpleArrayEquals && UseSIMDForArrayEquals)
5884 address MacroAssembler::arrays_equals(Register a1, Register a2, Register tmp3,
5885                                       Register tmp4, Register tmp5, Register result,
5886                                       Register cnt1, int elem_size) {
5887   Label DONE, SAME;
5888   Register tmp1 = rscratch1;
5889   Register tmp2 = rscratch2;
5890   int elem_per_word = wordSize/elem_size;
5891   int log_elem_size = exact_log2(elem_size);
5892   int klass_offset  = arrayOopDesc::klass_offset_in_bytes();
5893   int length_offset = arrayOopDesc::length_offset_in_bytes();
5894   int base_offset
5895     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
5896   // When the length offset is not aligned to 8 bytes,
5897   // then we align it down. This is valid because the new
5898   // offset will always be the klass which is the same
5899   // for type arrays.
5900   int start_offset = align_down(length_offset, BytesPerWord);
5901   int extra_length = base_offset - start_offset;
5902   assert(start_offset == length_offset || start_offset == klass_offset,
5903          "start offset must be 8-byte-aligned or be the klass offset");
5904   assert(base_offset != start_offset, "must include the length field");
5905   extra_length = extra_length / elem_size; // We count in elements, not bytes.
5906   int stubBytesThreshold = 3 * 64 + (UseSIMDForArrayEquals ? 0 : 16);
5907 
5908   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
5909   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
5910 
5911 #ifndef PRODUCT
5912   {
5913     const char kind = (elem_size == 2) ? 'U' : 'L';
5914     char comment[64];
5915     os::snprintf_checked(comment, sizeof comment, "array_equals%c{", kind);
5916     BLOCK_COMMENT(comment);
5917   }
5918 #endif
5919 
5920   // if (a1 == a2)
5921   //     return true;
5922   cmpoop(a1, a2); // May have read barriers for a1 and a2.
5923   br(EQ, SAME);
5924 
5925   if (UseSimpleArrayEquals) {
5926     Label NEXT_WORD, SHORT, TAIL03, TAIL01, A_MIGHT_BE_NULL, A_IS_NOT_NULL;
5927     // if (a1 == nullptr || a2 == nullptr)
5928     //     return false;
5929     // a1 & a2 == 0 means (some-pointer is null) or
5930     // (very-rare-or-even-probably-impossible-pointer-values)
5931     // so, we can save one branch in most cases
5932     tst(a1, a2);
5933     mov(result, false);
5934     br(EQ, A_MIGHT_BE_NULL);
5935     // if (a1.length != a2.length)
5936     //      return false;
5937     bind(A_IS_NOT_NULL);
5938     ldrw(cnt1, Address(a1, length_offset));
5939     ldrw(tmp5, Address(a2, length_offset));
5940     cmp(cnt1, tmp5);
5941     br(NE, DONE); // If lengths differ, return false
5942     // Increase loop counter by diff between base- and actual start-offset.
5943     addw(cnt1, cnt1, extra_length);
5944     lea(a1, Address(a1, start_offset));
5945     lea(a2, Address(a2, start_offset));
5946     // Check for short strings, i.e. smaller than wordSize.
5947     subs(cnt1, cnt1, elem_per_word);
5948     br(Assembler::LT, SHORT);
5949     // Main 8 byte comparison loop.
5950     bind(NEXT_WORD); {
5951       ldr(tmp1, Address(post(a1, wordSize)));
5952       ldr(tmp2, Address(post(a2, wordSize)));
5953       subs(cnt1, cnt1, elem_per_word);
5954       eor(tmp5, tmp1, tmp2);
5955       cbnz(tmp5, DONE);
5956     } br(GT, NEXT_WORD);
5957     // Last longword.  In the case where length == 4 we compare the
5958     // same longword twice, but that's still faster than another
5959     // conditional branch.
5960     // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
5961     // length == 4.
5962     if (log_elem_size > 0)
5963       lsl(cnt1, cnt1, log_elem_size);
5964     ldr(tmp3, Address(a1, cnt1));
5965     ldr(tmp4, Address(a2, cnt1));
5966     eor(tmp5, tmp3, tmp4);
5967     cbnz(tmp5, DONE);
5968     b(SAME);
5969     bind(A_MIGHT_BE_NULL);
5970     // in case both a1 and a2 are not-null, proceed with loads
5971     cbz(a1, DONE);
5972     cbz(a2, DONE);
5973     b(A_IS_NOT_NULL);
5974     bind(SHORT);
5975 
5976     tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
5977     {
5978       ldrw(tmp1, Address(post(a1, 4)));
5979       ldrw(tmp2, Address(post(a2, 4)));
5980       eorw(tmp5, tmp1, tmp2);
5981       cbnzw(tmp5, DONE);
5982     }
5983     bind(TAIL03);
5984     tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
5985     {
5986       ldrh(tmp3, Address(post(a1, 2)));
5987       ldrh(tmp4, Address(post(a2, 2)));
5988       eorw(tmp5, tmp3, tmp4);
5989       cbnzw(tmp5, DONE);
5990     }
5991     bind(TAIL01);
5992     if (elem_size == 1) { // Only needed when comparing byte arrays.
5993       tbz(cnt1, 0, SAME); // 0-1 bytes left.
5994       {
5995         ldrb(tmp1, a1);
5996         ldrb(tmp2, a2);
5997         eorw(tmp5, tmp1, tmp2);
5998         cbnzw(tmp5, DONE);
5999       }
6000     }
6001   } else {
6002     Label NEXT_DWORD, SHORT, TAIL, TAIL2, STUB,
6003         CSET_EQ, LAST_CHECK;
6004     mov(result, false);
6005     cbz(a1, DONE);
6006     ldrw(cnt1, Address(a1, length_offset));
6007     cbz(a2, DONE);
6008     ldrw(tmp5, Address(a2, length_offset));
6009     cmp(cnt1, tmp5);
6010     br(NE, DONE); // If lengths differ, return false
6011     // Increase loop counter by diff between base- and actual start-offset.
6012     addw(cnt1, cnt1, extra_length);
6013 
6014     // on most CPUs a2 is still "locked"(surprisingly) in ldrw and it's
6015     // faster to perform another branch before comparing a1 and a2
6016     cmp(cnt1, (u1)elem_per_word);
6017     br(LE, SHORT); // short or same
6018     ldr(tmp3, Address(pre(a1, start_offset)));
6019     subs(zr, cnt1, stubBytesThreshold);
6020     br(GE, STUB);
6021     ldr(tmp4, Address(pre(a2, start_offset)));
6022     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
6023 
6024     // Main 16 byte comparison loop with 2 exits
6025     bind(NEXT_DWORD); {
6026       ldr(tmp1, Address(pre(a1, wordSize)));
6027       ldr(tmp2, Address(pre(a2, wordSize)));
6028       subs(cnt1, cnt1, 2 * elem_per_word);
6029       br(LE, TAIL);
6030       eor(tmp4, tmp3, tmp4);
6031       cbnz(tmp4, DONE);
6032       ldr(tmp3, Address(pre(a1, wordSize)));
6033       ldr(tmp4, Address(pre(a2, wordSize)));
6034       cmp(cnt1, (u1)elem_per_word);
6035       br(LE, TAIL2);
6036       cmp(tmp1, tmp2);
6037     } br(EQ, NEXT_DWORD);
6038     b(DONE);
6039 
6040     bind(TAIL);
6041     eor(tmp4, tmp3, tmp4);
6042     eor(tmp2, tmp1, tmp2);
6043     lslv(tmp2, tmp2, tmp5);
6044     orr(tmp5, tmp4, tmp2);
6045     cmp(tmp5, zr);
6046     b(CSET_EQ);
6047 
6048     bind(TAIL2);
6049     eor(tmp2, tmp1, tmp2);
6050     cbnz(tmp2, DONE);
6051     b(LAST_CHECK);
6052 
6053     bind(STUB);
6054     ldr(tmp4, Address(pre(a2, start_offset)));
6055     if (elem_size == 2) { // convert to byte counter
6056       lsl(cnt1, cnt1, 1);
6057     }
6058     eor(tmp5, tmp3, tmp4);
6059     cbnz(tmp5, DONE);
6060     RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_array_equals());
6061     assert(stub.target() != nullptr, "array_equals_long stub has not been generated");
6062     address tpc = trampoline_call(stub);
6063     if (tpc == nullptr) {
6064       DEBUG_ONLY(reset_labels(SHORT, LAST_CHECK, CSET_EQ, SAME, DONE));
6065       postcond(pc() == badAddress);
6066       return nullptr;
6067     }
6068     b(DONE);
6069 
6070     // (a1 != null && a2 == null) || (a1 != null && a2 != null && a1 == a2)
6071     // so, if a2 == null => return false(0), else return true, so we can return a2
6072     mov(result, a2);
6073     b(DONE);
6074     bind(SHORT);
6075     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
6076     ldr(tmp3, Address(a1, start_offset));
6077     ldr(tmp4, Address(a2, start_offset));
6078     bind(LAST_CHECK);
6079     eor(tmp4, tmp3, tmp4);
6080     lslv(tmp5, tmp4, tmp5);
6081     cmp(tmp5, zr);
6082     bind(CSET_EQ);
6083     cset(result, EQ);
6084     b(DONE);
6085   }
6086 
6087   bind(SAME);
6088   mov(result, true);
6089   // That's it.
6090   bind(DONE);
6091 
6092   BLOCK_COMMENT("} array_equals");
6093   postcond(pc() != badAddress);
6094   return pc();
6095 }
6096 
6097 // Compare Strings
6098 
6099 // For Strings we're passed the address of the first characters in a1
6100 // and a2 and the length in cnt1.
6101 // There are two implementations.  For arrays >= 8 bytes, all
6102 // comparisons (including the final one, which may overlap) are
6103 // performed 8 bytes at a time.  For strings < 8 bytes, we compare a
6104 // halfword, then a short, and then a byte.
6105 
6106 void MacroAssembler::string_equals(Register a1, Register a2,
6107                                    Register result, Register cnt1)
6108 {
6109   Label SAME, DONE, SHORT, NEXT_WORD;
6110   Register tmp1 = rscratch1;
6111   Register tmp2 = rscratch2;
6112   Register cnt2 = tmp2;  // cnt2 only used in array length compare
6113 
6114   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
6115 
6116 #ifndef PRODUCT
6117   {
6118     char comment[64];
6119     os::snprintf_checked(comment, sizeof comment, "{string_equalsL");
6120     BLOCK_COMMENT(comment);
6121   }
6122 #endif
6123 
6124   mov(result, false);
6125 
6126   // Check for short strings, i.e. smaller than wordSize.
6127   subs(cnt1, cnt1, wordSize);
6128   br(Assembler::LT, SHORT);
6129   // Main 8 byte comparison loop.
6130   bind(NEXT_WORD); {
6131     ldr(tmp1, Address(post(a1, wordSize)));
6132     ldr(tmp2, Address(post(a2, wordSize)));
6133     subs(cnt1, cnt1, wordSize);
6134     eor(tmp1, tmp1, tmp2);
6135     cbnz(tmp1, DONE);
6136   } br(GT, NEXT_WORD);
6137   // Last longword.  In the case where length == 4 we compare the
6138   // same longword twice, but that's still faster than another
6139   // conditional branch.
6140   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
6141   // length == 4.
6142   ldr(tmp1, Address(a1, cnt1));
6143   ldr(tmp2, Address(a2, cnt1));
6144   eor(tmp2, tmp1, tmp2);
6145   cbnz(tmp2, DONE);
6146   b(SAME);
6147 
6148   bind(SHORT);
6149   Label TAIL03, TAIL01;
6150 
6151   tbz(cnt1, 2, TAIL03); // 0-7 bytes left.
6152   {
6153     ldrw(tmp1, Address(post(a1, 4)));
6154     ldrw(tmp2, Address(post(a2, 4)));
6155     eorw(tmp1, tmp1, tmp2);
6156     cbnzw(tmp1, DONE);
6157   }
6158   bind(TAIL03);
6159   tbz(cnt1, 1, TAIL01); // 0-3 bytes left.
6160   {
6161     ldrh(tmp1, Address(post(a1, 2)));
6162     ldrh(tmp2, Address(post(a2, 2)));
6163     eorw(tmp1, tmp1, tmp2);
6164     cbnzw(tmp1, DONE);
6165   }
6166   bind(TAIL01);
6167   tbz(cnt1, 0, SAME); // 0-1 bytes left.
6168     {
6169     ldrb(tmp1, a1);
6170     ldrb(tmp2, a2);
6171     eorw(tmp1, tmp1, tmp2);
6172     cbnzw(tmp1, DONE);
6173   }
6174   // Arrays are equal.
6175   bind(SAME);
6176   mov(result, true);
6177 
6178   // That's it.
6179   bind(DONE);
6180   BLOCK_COMMENT("} string_equals");
6181 }
6182 
6183 
6184 // The size of the blocks erased by the zero_blocks stub.  We must
6185 // handle anything smaller than this ourselves in zero_words().
6186 const int MacroAssembler::zero_words_block_size = 8;
6187 
6188 // zero_words() is used by C2 ClearArray patterns and by
6189 // C1_MacroAssembler.  It is as small as possible, handling small word
6190 // counts locally and delegating anything larger to the zero_blocks
6191 // stub.  It is expanded many times in compiled code, so it is
6192 // important to keep it short.
6193 
6194 // ptr:   Address of a buffer to be zeroed.
6195 // cnt:   Count in HeapWords.
6196 //
6197 // ptr, cnt, rscratch1, and rscratch2 are clobbered.
6198 address MacroAssembler::zero_words(Register ptr, Register cnt)
6199 {
6200   assert(is_power_of_2(zero_words_block_size), "adjust this");
6201 
6202   BLOCK_COMMENT("zero_words {");
6203   assert(ptr == r10 && cnt == r11, "mismatch in register usage");
6204   RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
6205   assert(zero_blocks.target() != nullptr, "zero_blocks stub has not been generated");
6206 
6207   subs(rscratch1, cnt, zero_words_block_size);
6208   Label around;
6209   br(LO, around);
6210   {
6211     RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
6212     assert(zero_blocks.target() != nullptr, "zero_blocks stub has not been generated");
6213     // Make sure this is a C2 compilation. C1 allocates space only for
6214     // trampoline stubs generated by Call LIR ops, and in any case it
6215     // makes sense for a C1 compilation task to proceed as quickly as
6216     // possible.
6217     CompileTask* task;
6218     if (StubRoutines::aarch64::complete()
6219         && Thread::current()->is_Compiler_thread()
6220         && (task = ciEnv::current()->task())
6221         && is_c2_compile(task->comp_level())) {
6222       address tpc = trampoline_call(zero_blocks);
6223       if (tpc == nullptr) {
6224         DEBUG_ONLY(reset_labels(around));
6225         return nullptr;
6226       }
6227     } else {
6228       far_call(zero_blocks);
6229     }
6230   }
6231   bind(around);
6232 
6233   // We have a few words left to do. zero_blocks has adjusted r10 and r11
6234   // for us.
6235   for (int i = zero_words_block_size >> 1; i > 1; i >>= 1) {
6236     Label l;
6237     tbz(cnt, exact_log2(i), l);
6238     for (int j = 0; j < i; j += 2) {
6239       stp(zr, zr, post(ptr, 2 * BytesPerWord));
6240     }
6241     bind(l);
6242   }
6243   {
6244     Label l;
6245     tbz(cnt, 0, l);
6246     str(zr, Address(ptr));
6247     bind(l);
6248   }
6249 
6250   BLOCK_COMMENT("} zero_words");
6251   return pc();
6252 }
6253 
6254 // base:         Address of a buffer to be zeroed, 8 bytes aligned.
6255 // cnt:          Immediate count in HeapWords.
6256 //
6257 // r10, r11, rscratch1, and rscratch2 are clobbered.
6258 address MacroAssembler::zero_words(Register base, uint64_t cnt)
6259 {
6260   assert(wordSize <= BlockZeroingLowLimit,
6261             "increase BlockZeroingLowLimit");
6262   address result = nullptr;
6263   if (cnt <= (uint64_t)BlockZeroingLowLimit / BytesPerWord) {
6264 #ifndef PRODUCT
6265     {
6266       char buf[64];
6267       os::snprintf_checked(buf, sizeof buf, "zero_words (count = %" PRIu64 ") {", cnt);
6268       BLOCK_COMMENT(buf);
6269     }
6270 #endif
6271     if (cnt >= 16) {
6272       uint64_t loops = cnt/16;
6273       if (loops > 1) {
6274         mov(rscratch2, loops - 1);
6275       }
6276       {
6277         Label loop;
6278         bind(loop);
6279         for (int i = 0; i < 16; i += 2) {
6280           stp(zr, zr, Address(base, i * BytesPerWord));
6281         }
6282         add(base, base, 16 * BytesPerWord);
6283         if (loops > 1) {
6284           subs(rscratch2, rscratch2, 1);
6285           br(GE, loop);
6286         }
6287       }
6288     }
6289     cnt %= 16;
6290     int i = cnt & 1;  // store any odd word to start
6291     if (i) str(zr, Address(base));
6292     for (; i < (int)cnt; i += 2) {
6293       stp(zr, zr, Address(base, i * wordSize));
6294     }
6295     BLOCK_COMMENT("} zero_words");
6296     result = pc();
6297   } else {
6298     mov(r10, base); mov(r11, cnt);
6299     result = zero_words(r10, r11);
6300   }
6301   return result;
6302 }
6303 
6304 // Zero blocks of memory by using DC ZVA.
6305 //
6306 // Aligns the base address first sufficiently for DC ZVA, then uses
6307 // DC ZVA repeatedly for every full block.  cnt is the size to be
6308 // zeroed in HeapWords.  Returns the count of words left to be zeroed
6309 // in cnt.
6310 //
6311 // NOTE: This is intended to be used in the zero_blocks() stub.  If
6312 // you want to use it elsewhere, note that cnt must be >= 2*zva_length.
6313 void MacroAssembler::zero_dcache_blocks(Register base, Register cnt) {
6314   Register tmp = rscratch1;
6315   Register tmp2 = rscratch2;
6316   int zva_length = VM_Version::zva_length();
6317   Label initial_table_end, loop_zva;
6318   Label fini;
6319 
6320   // Base must be 16 byte aligned. If not just return and let caller handle it
6321   tst(base, 0x0f);
6322   br(Assembler::NE, fini);
6323   // Align base with ZVA length.
6324   neg(tmp, base);
6325   andr(tmp, tmp, zva_length - 1);
6326 
6327   // tmp: the number of bytes to be filled to align the base with ZVA length.
6328   add(base, base, tmp);
6329   sub(cnt, cnt, tmp, Assembler::ASR, 3);
6330   adr(tmp2, initial_table_end);
6331   sub(tmp2, tmp2, tmp, Assembler::LSR, 2);
6332   br(tmp2);
6333 
6334   for (int i = -zva_length + 16; i < 0; i += 16)
6335     stp(zr, zr, Address(base, i));
6336   bind(initial_table_end);
6337 
6338   sub(cnt, cnt, zva_length >> 3);
6339   bind(loop_zva);
6340   dc(Assembler::ZVA, base);
6341   subs(cnt, cnt, zva_length >> 3);
6342   add(base, base, zva_length);
6343   br(Assembler::GE, loop_zva);
6344   add(cnt, cnt, zva_length >> 3); // count not zeroed by DC ZVA
6345   bind(fini);
6346 }
6347 
6348 // base:   Address of a buffer to be filled, 8 bytes aligned.
6349 // cnt:    Count in 8-byte unit.
6350 // value:  Value to be filled with.
6351 // base will point to the end of the buffer after filling.
6352 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
6353 {
6354 //  Algorithm:
6355 //
6356 //    if (cnt == 0) {
6357 //      return;
6358 //    }
6359 //    if ((p & 8) != 0) {
6360 //      *p++ = v;
6361 //    }
6362 //
6363 //    scratch1 = cnt & 14;
6364 //    cnt -= scratch1;
6365 //    p += scratch1;
6366 //    switch (scratch1 / 2) {
6367 //      do {
6368 //        cnt -= 16;
6369 //          p[-16] = v;
6370 //          p[-15] = v;
6371 //        case 7:
6372 //          p[-14] = v;
6373 //          p[-13] = v;
6374 //        case 6:
6375 //          p[-12] = v;
6376 //          p[-11] = v;
6377 //          // ...
6378 //        case 1:
6379 //          p[-2] = v;
6380 //          p[-1] = v;
6381 //        case 0:
6382 //          p += 16;
6383 //      } while (cnt);
6384 //    }
6385 //    if ((cnt & 1) == 1) {
6386 //      *p++ = v;
6387 //    }
6388 
6389   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
6390 
6391   Label fini, skip, entry, loop;
6392   const int unroll = 8; // Number of stp instructions we'll unroll
6393 
6394   cbz(cnt, fini);
6395   tbz(base, 3, skip);
6396   str(value, Address(post(base, 8)));
6397   sub(cnt, cnt, 1);
6398   bind(skip);
6399 
6400   andr(rscratch1, cnt, (unroll-1) * 2);
6401   sub(cnt, cnt, rscratch1);
6402   add(base, base, rscratch1, Assembler::LSL, 3);
6403   adr(rscratch2, entry);
6404   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
6405   br(rscratch2);
6406 
6407   bind(loop);
6408   add(base, base, unroll * 16);
6409   for (int i = -unroll; i < 0; i++)
6410     stp(value, value, Address(base, i * 16));
6411   bind(entry);
6412   subs(cnt, cnt, unroll * 2);
6413   br(Assembler::GE, loop);
6414 
6415   tbz(cnt, 0, fini);
6416   str(value, Address(post(base, 8)));
6417   bind(fini);
6418 }
6419 
6420 // Intrinsic for
6421 //
6422 // - sun/nio/cs/ISO_8859_1$Encoder.implEncodeISOArray
6423 //     return the number of characters copied.
6424 // - java/lang/StringUTF16.compress
6425 //     return index of non-latin1 character if copy fails, otherwise 'len'.
6426 //
6427 // This version always returns the number of characters copied, and does not
6428 // clobber the 'len' register. A successful copy will complete with the post-
6429 // condition: 'res' == 'len', while an unsuccessful copy will exit with the
6430 // post-condition: 0 <= 'res' < 'len'.
6431 //
6432 // NOTE: Attempts to use 'ld2' (and 'umaxv' in the ISO part) has proven to
6433 //       degrade performance (on Ampere Altra - Neoverse N1), to an extent
6434 //       beyond the acceptable, even though the footprint would be smaller.
6435 //       Using 'umaxv' in the ASCII-case comes with a small penalty but does
6436 //       avoid additional bloat.
6437 //
6438 // Clobbers: src, dst, res, rscratch1, rscratch2, rflags
6439 void MacroAssembler::encode_iso_array(Register src, Register dst,
6440                                       Register len, Register res, bool ascii,
6441                                       FloatRegister vtmp0, FloatRegister vtmp1,
6442                                       FloatRegister vtmp2, FloatRegister vtmp3,
6443                                       FloatRegister vtmp4, FloatRegister vtmp5)
6444 {
6445   Register cnt = res;
6446   Register max = rscratch1;
6447   Register chk = rscratch2;
6448 
6449   prfm(Address(src), PLDL1STRM);
6450   movw(cnt, len);
6451 
6452 #define ASCII(insn) do { if (ascii) { insn; } } while (0)
6453 
6454   Label LOOP_32, DONE_32, FAIL_32;
6455 
6456   BIND(LOOP_32);
6457   {
6458     cmpw(cnt, 32);
6459     br(LT, DONE_32);
6460     ld1(vtmp0, vtmp1, vtmp2, vtmp3, T8H, Address(post(src, 64)));
6461     // Extract lower bytes.
6462     FloatRegister vlo0 = vtmp4;
6463     FloatRegister vlo1 = vtmp5;
6464     uzp1(vlo0, T16B, vtmp0, vtmp1);
6465     uzp1(vlo1, T16B, vtmp2, vtmp3);
6466     // Merge bits...
6467     orr(vtmp0, T16B, vtmp0, vtmp1);
6468     orr(vtmp2, T16B, vtmp2, vtmp3);
6469     // Extract merged upper bytes.
6470     FloatRegister vhix = vtmp0;
6471     uzp2(vhix, T16B, vtmp0, vtmp2);
6472     // ISO-check on hi-parts (all zero).
6473     //                          ASCII-check on lo-parts (no sign).
6474     FloatRegister vlox = vtmp1; // Merge lower bytes.
6475                                 ASCII(orr(vlox, T16B, vlo0, vlo1));
6476     umov(chk, vhix, D, 1);      ASCII(cm(LT, vlox, T16B, vlox));
6477     fmovd(max, vhix);           ASCII(umaxv(vlox, T16B, vlox));
6478     orr(chk, chk, max);         ASCII(umov(max, vlox, B, 0));
6479                                 ASCII(orr(chk, chk, max));
6480     cbnz(chk, FAIL_32);
6481     subw(cnt, cnt, 32);
6482     st1(vlo0, vlo1, T16B, Address(post(dst, 32)));
6483     b(LOOP_32);
6484   }
6485   BIND(FAIL_32);
6486   sub(src, src, 64);
6487   BIND(DONE_32);
6488 
6489   Label LOOP_8, SKIP_8;
6490 
6491   BIND(LOOP_8);
6492   {
6493     cmpw(cnt, 8);
6494     br(LT, SKIP_8);
6495     FloatRegister vhi = vtmp0;
6496     FloatRegister vlo = vtmp1;
6497     ld1(vtmp3, T8H, src);
6498     uzp1(vlo, T16B, vtmp3, vtmp3);
6499     uzp2(vhi, T16B, vtmp3, vtmp3);
6500     // ISO-check on hi-parts (all zero).
6501     //                          ASCII-check on lo-parts (no sign).
6502                                 ASCII(cm(LT, vtmp2, T16B, vlo));
6503     fmovd(chk, vhi);            ASCII(umaxv(vtmp2, T16B, vtmp2));
6504                                 ASCII(umov(max, vtmp2, B, 0));
6505                                 ASCII(orr(chk, chk, max));
6506     cbnz(chk, SKIP_8);
6507 
6508     strd(vlo, Address(post(dst, 8)));
6509     subw(cnt, cnt, 8);
6510     add(src, src, 16);
6511     b(LOOP_8);
6512   }
6513   BIND(SKIP_8);
6514 
6515 #undef ASCII
6516 
6517   Label LOOP, DONE;
6518 
6519   cbz(cnt, DONE);
6520   BIND(LOOP);
6521   {
6522     Register chr = rscratch1;
6523     ldrh(chr, Address(post(src, 2)));
6524     tst(chr, ascii ? 0xff80 : 0xff00);
6525     br(NE, DONE);
6526     strb(chr, Address(post(dst, 1)));
6527     subs(cnt, cnt, 1);
6528     br(GT, LOOP);
6529   }
6530   BIND(DONE);
6531   // Return index where we stopped.
6532   subw(res, len, cnt);
6533 }
6534 
6535 // Inflate byte[] array to char[].
6536 // Clobbers: src, dst, len, rflags, rscratch1, v0-v6
6537 address MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
6538                                            FloatRegister vtmp1, FloatRegister vtmp2,
6539                                            FloatRegister vtmp3, Register tmp4) {
6540   Label big, done, after_init, to_stub;
6541 
6542   assert_different_registers(src, dst, len, tmp4, rscratch1);
6543 
6544   fmovd(vtmp1, 0.0);
6545   lsrw(tmp4, len, 3);
6546   bind(after_init);
6547   cbnzw(tmp4, big);
6548   // Short string: less than 8 bytes.
6549   {
6550     Label loop, tiny;
6551 
6552     cmpw(len, 4);
6553     br(LT, tiny);
6554     // Use SIMD to do 4 bytes.
6555     ldrs(vtmp2, post(src, 4));
6556     zip1(vtmp3, T8B, vtmp2, vtmp1);
6557     subw(len, len, 4);
6558     strd(vtmp3, post(dst, 8));
6559 
6560     cbzw(len, done);
6561 
6562     // Do the remaining bytes by steam.
6563     bind(loop);
6564     ldrb(tmp4, post(src, 1));
6565     strh(tmp4, post(dst, 2));
6566     subw(len, len, 1);
6567 
6568     bind(tiny);
6569     cbnz(len, loop);
6570 
6571     b(done);
6572   }
6573 
6574   if (SoftwarePrefetchHintDistance >= 0) {
6575     bind(to_stub);
6576       RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_byte_array_inflate());
6577       assert(stub.target() != nullptr, "large_byte_array_inflate stub has not been generated");
6578       address tpc = trampoline_call(stub);
6579       if (tpc == nullptr) {
6580         DEBUG_ONLY(reset_labels(big, done));
6581         postcond(pc() == badAddress);
6582         return nullptr;
6583       }
6584       b(after_init);
6585   }
6586 
6587   // Unpack the bytes 8 at a time.
6588   bind(big);
6589   {
6590     Label loop, around, loop_last, loop_start;
6591 
6592     if (SoftwarePrefetchHintDistance >= 0) {
6593       const int large_loop_threshold = (64 + 16)/8;
6594       ldrd(vtmp2, post(src, 8));
6595       andw(len, len, 7);
6596       cmp(tmp4, (u1)large_loop_threshold);
6597       br(GE, to_stub);
6598       b(loop_start);
6599 
6600       bind(loop);
6601       ldrd(vtmp2, post(src, 8));
6602       bind(loop_start);
6603       subs(tmp4, tmp4, 1);
6604       br(EQ, loop_last);
6605       zip1(vtmp2, T16B, vtmp2, vtmp1);
6606       ldrd(vtmp3, post(src, 8));
6607       st1(vtmp2, T8H, post(dst, 16));
6608       subs(tmp4, tmp4, 1);
6609       zip1(vtmp3, T16B, vtmp3, vtmp1);
6610       st1(vtmp3, T8H, post(dst, 16));
6611       br(NE, loop);
6612       b(around);
6613       bind(loop_last);
6614       zip1(vtmp2, T16B, vtmp2, vtmp1);
6615       st1(vtmp2, T8H, post(dst, 16));
6616       bind(around);
6617       cbz(len, done);
6618     } else {
6619       andw(len, len, 7);
6620       bind(loop);
6621       ldrd(vtmp2, post(src, 8));
6622       sub(tmp4, tmp4, 1);
6623       zip1(vtmp3, T16B, vtmp2, vtmp1);
6624       st1(vtmp3, T8H, post(dst, 16));
6625       cbnz(tmp4, loop);
6626     }
6627   }
6628 
6629   // Do the tail of up to 8 bytes.
6630   add(src, src, len);
6631   ldrd(vtmp3, Address(src, -8));
6632   add(dst, dst, len, ext::uxtw, 1);
6633   zip1(vtmp3, T16B, vtmp3, vtmp1);
6634   strq(vtmp3, Address(dst, -16));
6635 
6636   bind(done);
6637   postcond(pc() != badAddress);
6638   return pc();
6639 }
6640 
6641 // Compress char[] array to byte[].
6642 // Intrinsic for java.lang.StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
6643 // Return the array length if every element in array can be encoded,
6644 // otherwise, the index of first non-latin1 (> 0xff) character.
6645 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
6646                                          Register res,
6647                                          FloatRegister tmp0, FloatRegister tmp1,
6648                                          FloatRegister tmp2, FloatRegister tmp3,
6649                                          FloatRegister tmp4, FloatRegister tmp5) {
6650   encode_iso_array(src, dst, len, res, false, tmp0, tmp1, tmp2, tmp3, tmp4, tmp5);
6651 }
6652 
6653 // java.math.round(double a)
6654 // Returns the closest long to the argument, with ties rounding to
6655 // positive infinity.  This requires some fiddling for corner
6656 // cases. We take care to avoid double rounding in e.g. (jlong)(a + 0.5).
6657 void MacroAssembler::java_round_double(Register dst, FloatRegister src,
6658                                        FloatRegister ftmp) {
6659   Label DONE;
6660   BLOCK_COMMENT("java_round_double: { ");
6661   fmovd(rscratch1, src);
6662   // Use RoundToNearestTiesAway unless src small and -ve.
6663   fcvtasd(dst, src);
6664   // Test if src >= 0 || abs(src) >= 0x1.0p52
6665   eor(rscratch1, rscratch1, UCONST64(1) << 63); // flip sign bit
6666   mov(rscratch2, julong_cast(0x1.0p52));
6667   cmp(rscratch1, rscratch2);
6668   br(HS, DONE); {
6669     // src < 0 && abs(src) < 0x1.0p52
6670     // src may have a fractional part, so add 0.5
6671     fmovd(ftmp, 0.5);
6672     faddd(ftmp, src, ftmp);
6673     // Convert double to jlong, use RoundTowardsNegative
6674     fcvtmsd(dst, ftmp);
6675   }
6676   bind(DONE);
6677   BLOCK_COMMENT("} java_round_double");
6678 }
6679 
6680 void MacroAssembler::java_round_float(Register dst, FloatRegister src,
6681                                       FloatRegister ftmp) {
6682   Label DONE;
6683   BLOCK_COMMENT("java_round_float: { ");
6684   fmovs(rscratch1, src);
6685   // Use RoundToNearestTiesAway unless src small and -ve.
6686   fcvtassw(dst, src);
6687   // Test if src >= 0 || abs(src) >= 0x1.0p23
6688   eor(rscratch1, rscratch1, 0x80000000); // flip sign bit
6689   mov(rscratch2, jint_cast(0x1.0p23f));
6690   cmp(rscratch1, rscratch2);
6691   br(HS, DONE); {
6692     // src < 0 && |src| < 0x1.0p23
6693     // src may have a fractional part, so add 0.5
6694     fmovs(ftmp, 0.5f);
6695     fadds(ftmp, src, ftmp);
6696     // Convert float to jint, use RoundTowardsNegative
6697     fcvtmssw(dst, ftmp);
6698   }
6699   bind(DONE);
6700   BLOCK_COMMENT("} java_round_float");
6701 }
6702 
6703 // get_thread() can be called anywhere inside generated code so we
6704 // need to save whatever non-callee save context might get clobbered
6705 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
6706 // the call setup code.
6707 //
6708 // On Linux, aarch64_get_thread_helper() clobbers only r0, r1, and flags.
6709 // On other systems, the helper is a usual C function.
6710 //
6711 void MacroAssembler::get_thread(Register dst) {
6712   RegSet saved_regs =
6713     LINUX_ONLY(RegSet::range(r0, r1)  + lr - dst)
6714     NOT_LINUX (RegSet::range(r0, r17) + lr - dst);
6715 
6716   protect_return_address();
6717   push(saved_regs, sp);
6718 
6719   mov(lr, ExternalAddress(CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper)));
6720   blr(lr);
6721   if (dst != c_rarg0) {
6722     mov(dst, c_rarg0);
6723   }
6724 
6725   pop(saved_regs, sp);
6726   authenticate_return_address();
6727 }
6728 
6729 void MacroAssembler::cache_wb(Address line) {
6730   assert(line.getMode() == Address::base_plus_offset, "mode should be base_plus_offset");
6731   assert(line.index() == noreg, "index should be noreg");
6732   assert(line.offset() == 0, "offset should be 0");
6733   // would like to assert this
6734   // assert(line._ext.shift == 0, "shift should be zero");
6735   if (VM_Version::supports_dcpop()) {
6736     // writeback using clear virtual address to point of persistence
6737     dc(Assembler::CVAP, line.base());
6738   } else {
6739     // no need to generate anything as Unsafe.writebackMemory should
6740     // never invoke this stub
6741   }
6742 }
6743 
6744 void MacroAssembler::cache_wbsync(bool is_pre) {
6745   // we only need a barrier post sync
6746   if (!is_pre) {
6747     membar(Assembler::AnyAny);
6748   }
6749 }
6750 
6751 void MacroAssembler::verify_sve_vector_length(Register tmp) {
6752   if (!UseSVE || VM_Version::get_max_supported_sve_vector_length() == FloatRegister::sve_vl_min) {
6753     return;
6754   }
6755   // Make sure that native code does not change SVE vector length.
6756   Label verify_ok;
6757   movw(tmp, zr);
6758   sve_inc(tmp, B);
6759   subsw(zr, tmp, VM_Version::get_initial_sve_vector_length());
6760   br(EQ, verify_ok);
6761   stop("Error: SVE vector length has changed since jvm startup");
6762   bind(verify_ok);
6763 }
6764 
6765 void MacroAssembler::verify_ptrue() {
6766   Label verify_ok;
6767   if (!UseSVE) {
6768     return;
6769   }
6770   sve_cntp(rscratch1, B, ptrue, ptrue); // get true elements count.
6771   sve_dec(rscratch1, B);
6772   cbz(rscratch1, verify_ok);
6773   stop("Error: the preserved predicate register (p7) elements are not all true");
6774   bind(verify_ok);
6775 }
6776 
6777 void MacroAssembler::safepoint_isb() {
6778   isb();
6779 #ifndef PRODUCT
6780   if (VerifyCrossModifyFence) {
6781     // Clear the thread state.
6782     strb(zr, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
6783   }
6784 #endif
6785 }
6786 
6787 #ifndef PRODUCT
6788 void MacroAssembler::verify_cross_modify_fence_not_required() {
6789   if (VerifyCrossModifyFence) {
6790     // Check if thread needs a cross modify fence.
6791     ldrb(rscratch1, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
6792     Label fence_not_required;
6793     cbz(rscratch1, fence_not_required);
6794     // If it does then fail.
6795     lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::verify_cross_modify_fence_failure)));
6796     mov(c_rarg0, rthread);
6797     blr(rscratch1);
6798     bind(fence_not_required);
6799   }
6800 }
6801 #endif
6802 
6803 void MacroAssembler::spin_wait() {
6804   block_comment("spin_wait {");
6805   for (int i = 0; i < VM_Version::spin_wait_desc().inst_count(); ++i) {
6806     switch (VM_Version::spin_wait_desc().inst()) {
6807       case SpinWait::NOP:
6808         nop();
6809         break;
6810       case SpinWait::ISB:
6811         isb();
6812         break;
6813       case SpinWait::YIELD:
6814         yield();
6815         break;
6816       case SpinWait::SB:
6817         assert(VM_Version::supports_sb(), "current CPU does not support SB instruction");
6818         sb();
6819         break;
6820       default:
6821         ShouldNotReachHere();
6822     }
6823   }
6824   block_comment("}");
6825 }
6826 
6827 // Stack frame creation/removal
6828 
6829 void MacroAssembler::enter(bool strip_ret_addr) {
6830   if (strip_ret_addr) {
6831     // Addresses can only be signed once. If there are multiple nested frames being created
6832     // in the same function, then the return address needs stripping first.
6833     strip_return_address();
6834   }
6835   protect_return_address();
6836   stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
6837   mov(rfp, sp);
6838 }
6839 
6840 void MacroAssembler::leave() {
6841   mov(sp, rfp);
6842   ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
6843   authenticate_return_address();
6844 }
6845 
6846 // ROP Protection
6847 // Use the AArch64 PAC feature to add ROP protection for generated code. Use whenever creating/
6848 // destroying stack frames or whenever directly loading/storing the LR to memory.
6849 // If ROP protection is not set then these functions are no-ops.
6850 // For more details on PAC see pauth_aarch64.hpp.
6851 
6852 // Sign the LR. Use during construction of a stack frame, before storing the LR to memory.
6853 // Uses value zero as the modifier.
6854 //
6855 void MacroAssembler::protect_return_address() {
6856   if (VM_Version::use_rop_protection()) {
6857     check_return_address();
6858     paciaz();
6859   }
6860 }
6861 
6862 // Sign the return value in the given register. Use before updating the LR in the existing stack
6863 // frame for the current function.
6864 // Uses value zero as the modifier.
6865 //
6866 void MacroAssembler::protect_return_address(Register return_reg) {
6867   if (VM_Version::use_rop_protection()) {
6868     check_return_address(return_reg);
6869     paciza(return_reg);
6870   }
6871 }
6872 
6873 // Authenticate the LR. Use before function return, after restoring FP and loading LR from memory.
6874 // Uses value zero as the modifier.
6875 //
6876 void MacroAssembler::authenticate_return_address() {
6877   if (VM_Version::use_rop_protection()) {
6878     autiaz();
6879     check_return_address();
6880   }
6881 }
6882 
6883 // Authenticate the return value in the given register. Use before updating the LR in the existing
6884 // stack frame for the current function.
6885 // Uses value zero as the modifier.
6886 //
6887 void MacroAssembler::authenticate_return_address(Register return_reg) {
6888   if (VM_Version::use_rop_protection()) {
6889     autiza(return_reg);
6890     check_return_address(return_reg);
6891   }
6892 }
6893 
6894 // Strip any PAC data from LR without performing any authentication. Use with caution - only if
6895 // there is no guaranteed way of authenticating the LR.
6896 //
6897 void MacroAssembler::strip_return_address() {
6898   if (VM_Version::use_rop_protection()) {
6899     xpaclri();
6900   }
6901 }
6902 
6903 #ifndef PRODUCT
6904 // PAC failures can be difficult to debug. After an authentication failure, a segfault will only
6905 // occur when the pointer is used - ie when the program returns to the invalid LR. At this point
6906 // it is difficult to debug back to the callee function.
6907 // This function simply loads from the address in the given register.
6908 // Use directly after authentication to catch authentication failures.
6909 // Also use before signing to check that the pointer is valid and hasn't already been signed.
6910 //
6911 void MacroAssembler::check_return_address(Register return_reg) {
6912   if (VM_Version::use_rop_protection()) {
6913     ldr(zr, Address(return_reg));
6914   }
6915 }
6916 #endif
6917 
6918 // The java_calling_convention describes stack locations as ideal slots on
6919 // a frame with no abi restrictions. Since we must observe abi restrictions
6920 // (like the placement of the register window) the slots must be biased by
6921 // the following value.
6922 static int reg2offset_in(VMReg r) {
6923   // Account for saved rfp and lr
6924   // This should really be in_preserve_stack_slots
6925   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
6926 }
6927 
6928 static int reg2offset_out(VMReg r) {
6929   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
6930 }
6931 
6932 // On 64bit we will store integer like items to the stack as
6933 // 64bits items (AArch64 ABI) even though java would only store
6934 // 32bits for a parameter. On 32bit it will simply be 32bits
6935 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
6936 void MacroAssembler::move32_64(VMRegPair src, VMRegPair dst, Register tmp) {
6937   if (src.first()->is_stack()) {
6938     if (dst.first()->is_stack()) {
6939       // stack to stack
6940       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
6941       str(tmp, Address(sp, reg2offset_out(dst.first())));
6942     } else {
6943       // stack to reg
6944       ldrsw(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
6945     }
6946   } else if (dst.first()->is_stack()) {
6947     // reg to stack
6948     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
6949   } else {
6950     if (dst.first() != src.first()) {
6951       sxtw(dst.first()->as_Register(), src.first()->as_Register());
6952     }
6953   }
6954 }
6955 
6956 // An oop arg. Must pass a handle not the oop itself
6957 void MacroAssembler::object_move(
6958                         OopMap* map,
6959                         int oop_handle_offset,
6960                         int framesize_in_slots,
6961                         VMRegPair src,
6962                         VMRegPair dst,
6963                         bool is_receiver,
6964                         int* receiver_offset) {
6965 
6966   // must pass a handle. First figure out the location we use as a handle
6967 
6968   Register rHandle = dst.first()->is_stack() ? rscratch2 : dst.first()->as_Register();
6969 
6970   // See if oop is null if it is we need no handle
6971 
6972   if (src.first()->is_stack()) {
6973 
6974     // Oop is already on the stack as an argument
6975     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
6976     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
6977     if (is_receiver) {
6978       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
6979     }
6980 
6981     ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
6982     lea(rHandle, Address(rfp, reg2offset_in(src.first())));
6983     // conditionally move a null
6984     cmp(rscratch1, zr);
6985     csel(rHandle, zr, rHandle, Assembler::EQ);
6986   } else {
6987 
6988     // Oop is in an a register we must store it to the space we reserve
6989     // on the stack for oop_handles and pass a handle if oop is non-null
6990 
6991     const Register rOop = src.first()->as_Register();
6992     int oop_slot;
6993     if (rOop == j_rarg0)
6994       oop_slot = 0;
6995     else if (rOop == j_rarg1)
6996       oop_slot = 1;
6997     else if (rOop == j_rarg2)
6998       oop_slot = 2;
6999     else if (rOop == j_rarg3)
7000       oop_slot = 3;
7001     else if (rOop == j_rarg4)
7002       oop_slot = 4;
7003     else if (rOop == j_rarg5)
7004       oop_slot = 5;
7005     else if (rOop == j_rarg6)
7006       oop_slot = 6;
7007     else {
7008       assert(rOop == j_rarg7, "wrong register");
7009       oop_slot = 7;
7010     }
7011 
7012     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
7013     int offset = oop_slot*VMRegImpl::stack_slot_size;
7014 
7015     map->set_oop(VMRegImpl::stack2reg(oop_slot));
7016     // Store oop in handle area, may be null
7017     str(rOop, Address(sp, offset));
7018     if (is_receiver) {
7019       *receiver_offset = offset;
7020     }
7021 
7022     cmp(rOop, zr);
7023     lea(rHandle, Address(sp, offset));
7024     // conditionally move a null
7025     csel(rHandle, zr, rHandle, Assembler::EQ);
7026   }
7027 
7028   // If arg is on the stack then place it otherwise it is already in correct reg.
7029   if (dst.first()->is_stack()) {
7030     str(rHandle, Address(sp, reg2offset_out(dst.first())));
7031   }
7032 }
7033 
7034 // A float arg may have to do float reg int reg conversion
7035 void MacroAssembler::float_move(VMRegPair src, VMRegPair dst, Register tmp) {
7036  if (src.first()->is_stack()) {
7037     if (dst.first()->is_stack()) {
7038       ldrw(tmp, Address(rfp, reg2offset_in(src.first())));
7039       strw(tmp, Address(sp, reg2offset_out(dst.first())));
7040     } else {
7041       ldrs(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
7042     }
7043   } else if (src.first() != dst.first()) {
7044     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
7045       fmovs(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
7046     else
7047       strs(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
7048   }
7049 }
7050 
7051 // A long move
7052 void MacroAssembler::long_move(VMRegPair src, VMRegPair dst, Register tmp) {
7053   if (src.first()->is_stack()) {
7054     if (dst.first()->is_stack()) {
7055       // stack to stack
7056       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7057       str(tmp, Address(sp, reg2offset_out(dst.first())));
7058     } else {
7059       // stack to reg
7060       ldr(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
7061     }
7062   } else if (dst.first()->is_stack()) {
7063     // reg to stack
7064     // Do we really have to sign extend???
7065     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
7066     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
7067   } else {
7068     if (dst.first() != src.first()) {
7069       mov(dst.first()->as_Register(), src.first()->as_Register());
7070     }
7071   }
7072 }
7073 
7074 
7075 // A double move
7076 void MacroAssembler::double_move(VMRegPair src, VMRegPair dst, Register tmp) {
7077  if (src.first()->is_stack()) {
7078     if (dst.first()->is_stack()) {
7079       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
7080       str(tmp, Address(sp, reg2offset_out(dst.first())));
7081     } else {
7082       ldrd(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
7083     }
7084   } else if (src.first() != dst.first()) {
7085     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
7086       fmovd(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
7087     else
7088       strd(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
7089   }
7090 }
7091 
7092 // Implements fast-locking.
7093 //
7094 //  - obj: the object to be locked
7095 //  - t1, t2, t3: temporary registers, will be destroyed
7096 //  - slow: branched to if locking fails, absolute offset may larger than 32KB (imm14 encoding).
7097 void MacroAssembler::fast_lock(Register basic_lock, Register obj, Register t1, Register t2, Register t3, Label& slow) {
7098   assert_different_registers(basic_lock, obj, t1, t2, t3, rscratch1);
7099 
7100   Label push;
7101   const Register top = t1;
7102   const Register mark = t2;
7103   const Register t = t3;
7104 
7105   // Preload the markWord. It is important that this is the first
7106   // instruction emitted as it is part of C1's null check semantics.
7107   ldr(mark, Address(obj, oopDesc::mark_offset_in_bytes()));
7108 
7109   if (UseObjectMonitorTable) {
7110     // Clear cache in case fast locking succeeds or we need to take the slow-path.
7111     str(zr, Address(basic_lock, BasicObjectLock::lock_offset() + in_ByteSize((BasicLock::object_monitor_cache_offset_in_bytes()))));
7112   }
7113 
7114   if (DiagnoseSyncOnValueBasedClasses != 0) {
7115     load_klass(t1, obj);
7116     ldrb(t1, Address(t1, Klass::misc_flags_offset()));
7117     tst(t1, KlassFlags::_misc_is_value_based_class);
7118     br(Assembler::NE, slow);
7119   }
7120 
7121   // Check if the lock-stack is full.
7122   ldrw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7123   cmpw(top, (unsigned)LockStack::end_offset());
7124   br(Assembler::GE, slow);
7125 
7126   // Check for recursion.
7127   subw(t, top, oopSize);
7128   ldr(t, Address(rthread, t));
7129   cmp(obj, t);
7130   br(Assembler::EQ, push);
7131 
7132   // Check header for monitor (0b10).
7133   tst(mark, markWord::monitor_value);
7134   br(Assembler::NE, slow);
7135 
7136   // Try to lock. Transition lock bits 0b01 => 0b00
7137   assert(oopDesc::mark_offset_in_bytes() == 0, "required to avoid lea");
7138   orr(mark, mark, markWord::unlocked_value);
7139   eor(t, mark, markWord::unlocked_value);
7140   cmpxchg(/*addr*/ obj, /*expected*/ mark, /*new*/ t, Assembler::xword,
7141           /*acquire*/ true, /*release*/ false, /*weak*/ false, noreg);
7142   br(Assembler::NE, slow);
7143 
7144   bind(push);
7145   // After successful lock, push object on lock-stack.
7146   str(obj, Address(rthread, top));
7147   addw(top, top, oopSize);
7148   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7149 }
7150 
7151 // Implements fast-unlocking.
7152 //
7153 // - obj: the object to be unlocked
7154 // - t1, t2, t3: temporary registers
7155 // - slow: branched to if unlocking fails, absolute offset may larger than 32KB (imm14 encoding).
7156 void MacroAssembler::fast_unlock(Register obj, Register t1, Register t2, Register t3, Label& slow) {
7157   // cmpxchg clobbers rscratch1.
7158   assert_different_registers(obj, t1, t2, t3, rscratch1);
7159 
7160 #ifdef ASSERT
7161   {
7162     // Check for lock-stack underflow.
7163     Label stack_ok;
7164     ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
7165     cmpw(t1, (unsigned)LockStack::start_offset());
7166     br(Assembler::GE, stack_ok);
7167     STOP("Lock-stack underflow");
7168     bind(stack_ok);
7169   }
7170 #endif
7171 
7172   Label unlocked, push_and_slow;
7173   const Register top = t1;
7174   const Register mark = t2;
7175   const Register t = t3;
7176 
7177   // Check if obj is top of lock-stack.
7178   ldrw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7179   subw(top, top, oopSize);
7180   ldr(t, Address(rthread, top));
7181   cmp(obj, t);
7182   br(Assembler::NE, slow);
7183 
7184   // Pop lock-stack.
7185   DEBUG_ONLY(str(zr, Address(rthread, top));)
7186   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7187 
7188   // Check if recursive.
7189   subw(t, top, oopSize);
7190   ldr(t, Address(rthread, t));
7191   cmp(obj, t);
7192   br(Assembler::EQ, unlocked);
7193 
7194   // Not recursive. Check header for monitor (0b10).
7195   ldr(mark, Address(obj, oopDesc::mark_offset_in_bytes()));
7196   tbnz(mark, log2i_exact(markWord::monitor_value), push_and_slow);
7197 
7198 #ifdef ASSERT
7199   // Check header not unlocked (0b01).
7200   Label not_unlocked;
7201   tbz(mark, log2i_exact(markWord::unlocked_value), not_unlocked);
7202   stop("fast_unlock already unlocked");
7203   bind(not_unlocked);
7204 #endif
7205 
7206   // Try to unlock. Transition lock bits 0b00 => 0b01
7207   assert(oopDesc::mark_offset_in_bytes() == 0, "required to avoid lea");
7208   orr(t, mark, markWord::unlocked_value);
7209   cmpxchg(obj, mark, t, Assembler::xword,
7210           /*acquire*/ false, /*release*/ true, /*weak*/ false, noreg);
7211   br(Assembler::EQ, unlocked);
7212 
7213   bind(push_and_slow);
7214   // Restore lock-stack and handle the unlock in runtime.
7215   DEBUG_ONLY(str(obj, Address(rthread, top));)
7216   addw(top, top, oopSize);
7217   strw(top, Address(rthread, JavaThread::lock_stack_top_offset()));
7218   b(slow);
7219 
7220   bind(unlocked);
7221 }