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