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