1 /*
   2  * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2014, 2021, Red Hat Inc. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include <sys/types.h>
  27 
  28 #include "precompiled.hpp"
  29 #include "asm/assembler.hpp"
  30 #include "asm/assembler.inline.hpp"
  31 #include "ci/ciEnv.hpp"

  32 #include "compiler/compileTask.hpp"
  33 #include "compiler/disassembler.hpp"
  34 #include "compiler/oopMap.hpp"
  35 #include "gc/shared/barrierSet.hpp"
  36 #include "gc/shared/barrierSetAssembler.hpp"
  37 #include "gc/shared/cardTableBarrierSet.hpp"
  38 #include "gc/shared/cardTable.hpp"
  39 #include "gc/shared/collectedHeap.hpp"
  40 #include "gc/shared/tlab_globals.hpp"
  41 #include "interpreter/bytecodeHistogram.hpp"
  42 #include "interpreter/interpreter.hpp"
  43 #include "jvm.h"
  44 #include "memory/resourceArea.hpp"
  45 #include "memory/universe.hpp"
  46 #include "nativeInst_aarch64.hpp"
  47 #include "oops/accessDecorators.hpp"
  48 #include "oops/compressedKlass.inline.hpp"
  49 #include "oops/compressedOops.inline.hpp"
  50 #include "oops/klass.inline.hpp"

  51 #include "runtime/continuation.hpp"
  52 #include "runtime/icache.hpp"
  53 #include "runtime/interfaceSupport.inline.hpp"
  54 #include "runtime/javaThread.hpp"
  55 #include "runtime/jniHandles.inline.hpp"
  56 #include "runtime/sharedRuntime.hpp"

  57 #include "runtime/stubRoutines.hpp"
  58 #include "utilities/powerOfTwo.hpp"

  59 #ifdef COMPILER1
  60 #include "c1/c1_LIRAssembler.hpp"
  61 #endif
  62 #ifdef COMPILER2
  63 #include "oops/oop.hpp"
  64 #include "opto/compile.hpp"
  65 #include "opto/node.hpp"
  66 #include "opto/output.hpp"
  67 #endif
  68 
  69 #ifdef PRODUCT
  70 #define BLOCK_COMMENT(str) /* nothing */
  71 #else
  72 #define BLOCK_COMMENT(str) block_comment(str)
  73 #endif
  74 #define STOP(str) stop(str);
  75 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  76 
  77 #ifdef ASSERT
  78 extern "C" void disnm(intptr_t p);
  79 #endif
  80 // Target-dependent relocation processing
  81 //
  82 // Instruction sequences whose target may need to be retrieved or
  83 // patched are distinguished by their leading instruction, sorting
  84 // them into three main instruction groups and related subgroups.
  85 //
  86 // 1) Branch, Exception and System (insn count = 1)
  87 //    1a) Unconditional branch (immediate):
  88 //      b/bl imm19
  89 //    1b) Compare & branch (immediate):
  90 //      cbz/cbnz Rt imm19
  91 //    1c) Test & branch (immediate):
  92 //      tbz/tbnz Rt imm14
  93 //    1d) Conditional branch (immediate):
  94 //      b.cond imm19
  95 //
  96 // 2) Loads and Stores (insn count = 1)
  97 //    2a) Load register literal:
  98 //      ldr Rt imm19
  99 //
 100 // 3) Data Processing Immediate (insn count = 2 or 3)
 101 //    3a) PC-rel. addressing
 102 //      adr/adrp Rx imm21; ldr/str Ry Rx  #imm12
 103 //      adr/adrp Rx imm21; add Ry Rx  #imm12
 104 //      adr/adrp Rx imm21; movk Rx #imm16<<32; ldr/str Ry, [Rx, #offset_in_page]
 105 //      adr/adrp Rx imm21
 106 //      adr/adrp Rx imm21; movk Rx #imm16<<32
 107 //      adr/adrp Rx imm21; movk Rx #imm16<<32; add Ry, Rx, #offset_in_page
 108 //      The latter form can only happen when the target is an
 109 //      ExternalAddress, and (by definition) ExternalAddresses don't
 110 //      move. Because of that property, there is never any need to
 111 //      patch the last of the three instructions. However,
 112 //      MacroAssembler::target_addr_for_insn takes all three
 113 //      instructions into account and returns the correct address.
 114 //    3b) Move wide (immediate)
 115 //      movz Rx #imm16; movk Rx #imm16 << 16; movk Rx #imm16 << 32;
 116 //
 117 // A switch on a subset of the instruction's bits provides an
 118 // efficient dispatch to these subcases.
 119 //
 120 // insn[28:26] -> main group ('x' == don't care)
 121 //   00x -> UNALLOCATED
 122 //   100 -> Data Processing Immediate
 123 //   101 -> Branch, Exception and System
 124 //   x1x -> Loads and Stores
 125 //
 126 // insn[30:25] -> subgroup ('_' == group, 'x' == don't care).
 127 // n.b. in some cases extra bits need to be checked to verify the
 128 // instruction is as expected
 129 //
 130 // 1) ... xx101x Branch, Exception and System
 131 //   1a)  00___x Unconditional branch (immediate)
 132 //   1b)  01___0 Compare & branch (immediate)
 133 //   1c)  01___1 Test & branch (immediate)
 134 //   1d)  10___0 Conditional branch (immediate)
 135 //        other  Should not happen
 136 //
 137 // 2) ... xxx1x0 Loads and Stores
 138 //   2a)  xx1__00 Load/Store register (insn[28] == 1 && insn[24] == 0)
 139 //   2aa) x01__00 Load register literal (i.e. requires insn[29] == 0)
 140 //                strictly should be 64 bit non-FP/SIMD i.e.
 141 //       0101_000 (i.e. requires insn[31:24] == 01011000)
 142 //
 143 // 3) ... xx100x Data Processing Immediate
 144 //   3a)  xx___00 PC-rel. addressing (n.b. requires insn[24] == 0)
 145 //   3b)  xx___101 Move wide (immediate) (n.b. requires insn[24:23] == 01)
 146 //                 strictly should be 64 bit movz #imm16<<0
 147 //       110___10100 (i.e. requires insn[31:21] == 11010010100)
 148 //
 149 class RelocActions {
 150 protected:
 151   typedef int (*reloc_insn)(address insn_addr, address &target);
 152 
 153   virtual reloc_insn adrpMem() = 0;
 154   virtual reloc_insn adrpAdd() = 0;
 155   virtual reloc_insn adrpMovk() = 0;
 156 
 157   const address _insn_addr;
 158   const uint32_t _insn;
 159 
 160   static uint32_t insn_at(address insn_addr, int n) {
 161     return ((uint32_t*)insn_addr)[n];
 162   }
 163   uint32_t insn_at(int n) const {
 164     return insn_at(_insn_addr, n);
 165   }
 166 
 167 public:
 168 
 169   RelocActions(address insn_addr) : _insn_addr(insn_addr), _insn(insn_at(insn_addr, 0)) {}
 170   RelocActions(address insn_addr, uint32_t insn)
 171     :  _insn_addr(insn_addr), _insn(insn) {}
 172 
 173   virtual int unconditionalBranch(address insn_addr, address &target) = 0;
 174   virtual int conditionalBranch(address insn_addr, address &target) = 0;
 175   virtual int testAndBranch(address insn_addr, address &target) = 0;
 176   virtual int loadStore(address insn_addr, address &target) = 0;
 177   virtual int adr(address insn_addr, address &target) = 0;
 178   virtual int adrp(address insn_addr, address &target, reloc_insn inner) = 0;
 179   virtual int immediate(address insn_addr, address &target) = 0;
 180   virtual void verify(address insn_addr, address &target) = 0;
 181 
 182   int ALWAYSINLINE run(address insn_addr, address &target) {
 183     int instructions = 1;
 184 
 185     uint32_t dispatch = Instruction_aarch64::extract(_insn, 30, 25);
 186     switch(dispatch) {
 187       case 0b001010:
 188       case 0b001011: {
 189         instructions = unconditionalBranch(insn_addr, target);
 190         break;
 191       }
 192       case 0b101010:   // Conditional branch (immediate)
 193       case 0b011010: { // Compare & branch (immediate)
 194         instructions = conditionalBranch(insn_addr, target);
 195           break;
 196       }
 197       case 0b011011: {
 198         instructions = testAndBranch(insn_addr, target);
 199         break;
 200       }
 201       case 0b001100:
 202       case 0b001110:
 203       case 0b011100:
 204       case 0b011110:
 205       case 0b101100:
 206       case 0b101110:
 207       case 0b111100:
 208       case 0b111110: {
 209         // load/store
 210         if ((Instruction_aarch64::extract(_insn, 29, 24) & 0b111011) == 0b011000) {
 211           // Load register (literal)
 212           instructions = loadStore(insn_addr, target);
 213           break;
 214         } else {
 215           // nothing to do
 216           assert(target == 0, "did not expect to relocate target for polling page load");
 217         }
 218         break;
 219       }
 220       case 0b001000:
 221       case 0b011000:
 222       case 0b101000:
 223       case 0b111000: {
 224         // adr/adrp
 225         assert(Instruction_aarch64::extract(_insn, 28, 24) == 0b10000, "must be");
 226         int shift = Instruction_aarch64::extract(_insn, 31, 31);
 227         if (shift) {
 228           uint32_t insn2 = insn_at(1);
 229           if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
 230               Instruction_aarch64::extract(_insn, 4, 0) ==
 231               Instruction_aarch64::extract(insn2, 9, 5)) {
 232             instructions = adrp(insn_addr, target, adrpMem());
 233           } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
 234                      Instruction_aarch64::extract(_insn, 4, 0) ==
 235                      Instruction_aarch64::extract(insn2, 4, 0)) {
 236             instructions = adrp(insn_addr, target, adrpAdd());
 237           } else if (Instruction_aarch64::extract(insn2, 31, 21) == 0b11110010110 &&
 238                      Instruction_aarch64::extract(_insn, 4, 0) ==
 239                      Instruction_aarch64::extract(insn2, 4, 0)) {
 240             instructions = adrp(insn_addr, target, adrpMovk());
 241           } else {
 242             ShouldNotReachHere();
 243           }
 244         } else {
 245           instructions = adr(insn_addr, target);
 246         }
 247         break;
 248       }
 249       case 0b001001:
 250       case 0b011001:
 251       case 0b101001:
 252       case 0b111001: {
 253         instructions = immediate(insn_addr, target);
 254         break;
 255       }
 256       default: {
 257         ShouldNotReachHere();
 258       }
 259     }
 260 
 261     verify(insn_addr, target);
 262     return instructions * NativeInstruction::instruction_size;
 263   }
 264 };
 265 
 266 class Patcher : public RelocActions {
 267   virtual reloc_insn adrpMem() { return &Patcher::adrpMem_impl; }
 268   virtual reloc_insn adrpAdd() { return &Patcher::adrpAdd_impl; }
 269   virtual reloc_insn adrpMovk() { return &Patcher::adrpMovk_impl; }
 270 
 271 public:
 272   Patcher(address insn_addr) : RelocActions(insn_addr) {}
 273 
 274   virtual int unconditionalBranch(address insn_addr, address &target) {
 275     intptr_t offset = (target - insn_addr) >> 2;
 276     Instruction_aarch64::spatch(insn_addr, 25, 0, offset);
 277     return 1;
 278   }
 279   virtual int conditionalBranch(address insn_addr, address &target) {
 280     intptr_t offset = (target - insn_addr) >> 2;
 281     Instruction_aarch64::spatch(insn_addr, 23, 5, offset);
 282     return 1;
 283   }
 284   virtual int testAndBranch(address insn_addr, address &target) {
 285     intptr_t offset = (target - insn_addr) >> 2;
 286     Instruction_aarch64::spatch(insn_addr, 18, 5, offset);
 287     return 1;
 288   }
 289   virtual int loadStore(address insn_addr, address &target) {
 290     intptr_t offset = (target - insn_addr) >> 2;
 291     Instruction_aarch64::spatch(insn_addr, 23, 5, offset);
 292     return 1;
 293   }
 294   virtual int adr(address insn_addr, address &target) {
 295 #ifdef ASSERT
 296     assert(Instruction_aarch64::extract(_insn, 28, 24) == 0b10000, "must be");
 297 #endif
 298     // PC-rel. addressing
 299     ptrdiff_t offset = target - insn_addr;
 300     int offset_lo = offset & 3;
 301     offset >>= 2;
 302     Instruction_aarch64::spatch(insn_addr, 23, 5, offset);
 303     Instruction_aarch64::patch(insn_addr, 30, 29, offset_lo);
 304     return 1;
 305   }
 306   virtual int adrp(address insn_addr, address &target, reloc_insn inner) {
 307     int instructions = 1;
 308 #ifdef ASSERT
 309     assert(Instruction_aarch64::extract(_insn, 28, 24) == 0b10000, "must be");
 310 #endif
 311     ptrdiff_t offset = target - insn_addr;
 312     instructions = 2;
 313     precond(inner != nullptr);
 314     // Give the inner reloc a chance to modify the target.
 315     address adjusted_target = target;
 316     instructions = (*inner)(insn_addr, adjusted_target);
 317     uintptr_t pc_page = (uintptr_t)insn_addr >> 12;
 318     uintptr_t adr_page = (uintptr_t)adjusted_target >> 12;
 319     offset = adr_page - pc_page;
 320     int offset_lo = offset & 3;
 321     offset >>= 2;
 322     Instruction_aarch64::spatch(insn_addr, 23, 5, offset);
 323     Instruction_aarch64::patch(insn_addr, 30, 29, offset_lo);
 324     return instructions;
 325   }
 326   static int adrpMem_impl(address insn_addr, address &target) {
 327     uintptr_t dest = (uintptr_t)target;
 328     int offset_lo = dest & 0xfff;
 329     uint32_t insn2 = insn_at(insn_addr, 1);
 330     uint32_t size = Instruction_aarch64::extract(insn2, 31, 30);
 331     Instruction_aarch64::patch(insn_addr + sizeof (uint32_t), 21, 10, offset_lo >> size);
 332     guarantee(((dest >> size) << size) == dest, "misaligned target");
 333     return 2;
 334   }
 335   static int adrpAdd_impl(address insn_addr, address &target) {
 336     uintptr_t dest = (uintptr_t)target;
 337     int offset_lo = dest & 0xfff;
 338     Instruction_aarch64::patch(insn_addr + sizeof (uint32_t), 21, 10, offset_lo);
 339     return 2;
 340   }
 341   static int adrpMovk_impl(address insn_addr, address &target) {
 342     uintptr_t dest = uintptr_t(target);
 343     Instruction_aarch64::patch(insn_addr + sizeof (uint32_t), 20, 5, (uintptr_t)target >> 32);
 344     dest = (dest & 0xffffffffULL) | (uintptr_t(insn_addr) & 0xffff00000000ULL);
 345     target = address(dest);
 346     return 2;
 347   }
 348   virtual int immediate(address insn_addr, address &target) {
 349     assert(Instruction_aarch64::extract(_insn, 31, 21) == 0b11010010100, "must be");
 350     uint64_t dest = (uint64_t)target;
 351     // Move wide constant
 352     assert(nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 353     assert(nativeInstruction_at(insn_addr+8)->is_movk(), "wrong insns in patch");
 354     Instruction_aarch64::patch(insn_addr, 20, 5, dest & 0xffff);
 355     Instruction_aarch64::patch(insn_addr+4, 20, 5, (dest >>= 16) & 0xffff);
 356     Instruction_aarch64::patch(insn_addr+8, 20, 5, (dest >>= 16) & 0xffff);
 357     return 3;
 358   }
 359   virtual void verify(address insn_addr, address &target) {
 360 #ifdef ASSERT
 361     address address_is = MacroAssembler::target_addr_for_insn(insn_addr);
 362     if (!(address_is == target)) {
 363       tty->print_cr("%p at %p should be %p", address_is, insn_addr, target);
 364       disnm((intptr_t)insn_addr);
 365       assert(address_is == target, "should be");
 366     }
 367 #endif
 368   }
 369 };
 370 
 371 // If insn1 and insn2 use the same register to form an address, either
 372 // by an offsetted LDR or a simple ADD, return the offset. If the
 373 // second instruction is an LDR, the offset may be scaled.
 374 static bool offset_for(uint32_t insn1, uint32_t insn2, ptrdiff_t &byte_offset) {
 375   if (Instruction_aarch64::extract(insn2, 29, 24) == 0b111001 &&
 376       Instruction_aarch64::extract(insn1, 4, 0) ==
 377       Instruction_aarch64::extract(insn2, 9, 5)) {
 378     // Load/store register (unsigned immediate)
 379     byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 380     uint32_t size = Instruction_aarch64::extract(insn2, 31, 30);
 381     byte_offset <<= size;
 382     return true;
 383   } else if (Instruction_aarch64::extract(insn2, 31, 22) == 0b1001000100 &&
 384              Instruction_aarch64::extract(insn1, 4, 0) ==
 385              Instruction_aarch64::extract(insn2, 4, 0)) {
 386     // add (immediate)
 387     byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 388     return true;
 389   }
 390   return false;
 391 }
 392 
 393 class Decoder : public RelocActions {
 394   virtual reloc_insn adrpMem() { return &Decoder::adrpMem_impl; }
 395   virtual reloc_insn adrpAdd() { return &Decoder::adrpAdd_impl; }
 396   virtual reloc_insn adrpMovk() { return &Decoder::adrpMovk_impl; }
 397 
 398 public:
 399   Decoder(address insn_addr, uint32_t insn) : RelocActions(insn_addr, insn) {}
 400 
 401   virtual int loadStore(address insn_addr, address &target) {
 402     intptr_t offset = Instruction_aarch64::sextract(_insn, 23, 5);
 403     target = insn_addr + (offset << 2);
 404     return 1;
 405   }
 406   virtual int unconditionalBranch(address insn_addr, address &target) {
 407     intptr_t offset = Instruction_aarch64::sextract(_insn, 25, 0);
 408     target = insn_addr + (offset << 2);
 409     return 1;
 410   }
 411   virtual int conditionalBranch(address insn_addr, address &target) {
 412     intptr_t offset = Instruction_aarch64::sextract(_insn, 23, 5);
 413     target = address(((uint64_t)insn_addr + (offset << 2)));
 414     return 1;
 415   }
 416   virtual int testAndBranch(address insn_addr, address &target) {
 417     intptr_t offset = Instruction_aarch64::sextract(_insn, 18, 5);
 418     target = address(((uint64_t)insn_addr + (offset << 2)));
 419     return 1;
 420   }
 421   virtual int adr(address insn_addr, address &target) {
 422     // PC-rel. addressing
 423     intptr_t offset = Instruction_aarch64::extract(_insn, 30, 29);
 424     offset |= Instruction_aarch64::sextract(_insn, 23, 5) << 2;
 425     target = address((uint64_t)insn_addr + offset);
 426     return 1;
 427   }
 428   virtual int adrp(address insn_addr, address &target, reloc_insn inner) {
 429     assert(Instruction_aarch64::extract(_insn, 28, 24) == 0b10000, "must be");
 430     intptr_t offset = Instruction_aarch64::extract(_insn, 30, 29);
 431     offset |= Instruction_aarch64::sextract(_insn, 23, 5) << 2;
 432     int shift = 12;
 433     offset <<= shift;
 434     uint64_t target_page = ((uint64_t)insn_addr) + offset;
 435     target_page &= ((uint64_t)-1) << shift;
 436     uint32_t insn2 = insn_at(1);
 437     target = address(target_page);
 438     precond(inner != nullptr);
 439     (*inner)(insn_addr, target);
 440     return 2;
 441   }
 442   static int adrpMem_impl(address insn_addr, address &target) {
 443     uint32_t insn2 = insn_at(insn_addr, 1);
 444     // Load/store register (unsigned immediate)
 445     ptrdiff_t byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 446     uint32_t size = Instruction_aarch64::extract(insn2, 31, 30);
 447     byte_offset <<= size;
 448     target += byte_offset;
 449     return 2;
 450   }
 451   static int adrpAdd_impl(address insn_addr, address &target) {
 452     uint32_t insn2 = insn_at(insn_addr, 1);
 453     // add (immediate)
 454     ptrdiff_t byte_offset = Instruction_aarch64::extract(insn2, 21, 10);
 455     target += byte_offset;
 456     return 2;
 457   }
 458   static int adrpMovk_impl(address insn_addr, address &target) {
 459     uint32_t insn2 = insn_at(insn_addr, 1);
 460     uint64_t dest = uint64_t(target);
 461     dest = (dest & 0xffff0000ffffffff) |
 462       ((uint64_t)Instruction_aarch64::extract(insn2, 20, 5) << 32);
 463     target = address(dest);
 464 
 465     // We know the destination 4k page. Maybe we have a third
 466     // instruction.
 467     uint32_t insn = insn_at(insn_addr, 0);
 468     uint32_t insn3 = insn_at(insn_addr, 2);
 469     ptrdiff_t byte_offset;
 470     if (offset_for(insn, insn3, byte_offset)) {
 471       target += byte_offset;
 472       return 3;
 473     } else {
 474       return 2;
 475     }
 476   }
 477   virtual int immediate(address insn_addr, address &target) {
 478     uint32_t *insns = (uint32_t *)insn_addr;
 479     assert(Instruction_aarch64::extract(_insn, 31, 21) == 0b11010010100, "must be");
 480     // Move wide constant: movz, movk, movk.  See movptr().
 481     assert(nativeInstruction_at(insns+1)->is_movk(), "wrong insns in patch");
 482     assert(nativeInstruction_at(insns+2)->is_movk(), "wrong insns in patch");
 483     target = address(uint64_t(Instruction_aarch64::extract(_insn, 20, 5))
 484                  + (uint64_t(Instruction_aarch64::extract(insns[1], 20, 5)) << 16)
 485                  + (uint64_t(Instruction_aarch64::extract(insns[2], 20, 5)) << 32));
 486     assert(nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 487     assert(nativeInstruction_at(insn_addr+8)->is_movk(), "wrong insns in patch");
 488     return 3;
 489   }
 490   virtual void verify(address insn_addr, address &target) {
 491   }
 492 };
 493 
 494 address MacroAssembler::target_addr_for_insn(address insn_addr, uint32_t insn) {
 495   Decoder decoder(insn_addr, insn);
 496   address target;
 497   decoder.run(insn_addr, target);
 498   return target;
 499 }
 500 
 501 // Patch any kind of instruction; there may be several instructions.
 502 // Return the total length (in bytes) of the instructions.
 503 int MacroAssembler::pd_patch_instruction_size(address insn_addr, address target) {
 504   Patcher patcher(insn_addr);
 505   return patcher.run(insn_addr, target);
 506 }
 507 
 508 int MacroAssembler::patch_oop(address insn_addr, address o) {
 509   int instructions;
 510   unsigned insn = *(unsigned*)insn_addr;
 511   assert(nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 512 
 513   // OOPs are either narrow (32 bits) or wide (48 bits).  We encode
 514   // narrow OOPs by setting the upper 16 bits in the first
 515   // instruction.
 516   if (Instruction_aarch64::extract(insn, 31, 21) == 0b11010010101) {
 517     // Move narrow OOP
 518     uint32_t n = CompressedOops::narrow_oop_value(cast_to_oop(o));
 519     Instruction_aarch64::patch(insn_addr, 20, 5, n >> 16);
 520     Instruction_aarch64::patch(insn_addr+4, 20, 5, n & 0xffff);
 521     instructions = 2;
 522   } else {
 523     // Move wide OOP
 524     assert(nativeInstruction_at(insn_addr+8)->is_movk(), "wrong insns in patch");
 525     uintptr_t dest = (uintptr_t)o;
 526     Instruction_aarch64::patch(insn_addr, 20, 5, dest & 0xffff);
 527     Instruction_aarch64::patch(insn_addr+4, 20, 5, (dest >>= 16) & 0xffff);
 528     Instruction_aarch64::patch(insn_addr+8, 20, 5, (dest >>= 16) & 0xffff);
 529     instructions = 3;
 530   }
 531   return instructions * NativeInstruction::instruction_size;
 532 }
 533 
 534 int MacroAssembler::patch_narrow_klass(address insn_addr, narrowKlass n) {
 535   // Metadata pointers are either narrow (32 bits) or wide (48 bits).
 536   // We encode narrow ones by setting the upper 16 bits in the first
 537   // instruction.
 538   NativeInstruction *insn = nativeInstruction_at(insn_addr);
 539   assert(Instruction_aarch64::extract(insn->encoding(), 31, 21) == 0b11010010101 &&
 540          nativeInstruction_at(insn_addr+4)->is_movk(), "wrong insns in patch");
 541 
 542   Instruction_aarch64::patch(insn_addr, 20, 5, n >> 16);
 543   Instruction_aarch64::patch(insn_addr+4, 20, 5, n & 0xffff);
 544   return 2 * NativeInstruction::instruction_size;
 545 }
 546 
 547 address MacroAssembler::target_addr_for_insn_or_null(address insn_addr, unsigned insn) {
 548   if (NativeInstruction::is_ldrw_to_zr(address(&insn))) {
 549     return nullptr;
 550   }
 551   return MacroAssembler::target_addr_for_insn(insn_addr, insn);
 552 }
 553 
 554 void MacroAssembler::safepoint_poll(Label& slow_path, bool at_return, bool acquire, bool in_nmethod, Register tmp) {
 555   if (acquire) {
 556     lea(tmp, Address(rthread, JavaThread::polling_word_offset()));
 557     ldar(tmp, tmp);
 558   } else {
 559     ldr(tmp, Address(rthread, JavaThread::polling_word_offset()));
 560   }
 561   if (at_return) {
 562     // Note that when in_nmethod is set, the stack pointer is incremented before the poll. Therefore,
 563     // we may safely use the sp instead to perform the stack watermark check.
 564     cmp(in_nmethod ? sp : rfp, tmp);
 565     br(Assembler::HI, slow_path);
 566   } else {
 567     tbnz(tmp, log2i_exact(SafepointMechanism::poll_bit()), slow_path);
 568   }
 569 }
 570 
 571 void MacroAssembler::rt_call(address dest, Register tmp) {
 572   CodeBlob *cb = CodeCache::find_blob(dest);
 573   if (cb) {
 574     far_call(RuntimeAddress(dest));
 575   } else {
 576     lea(tmp, RuntimeAddress(dest));
 577     blr(tmp);
 578   }
 579 }
 580 
 581 void MacroAssembler::push_cont_fastpath(Register java_thread) {
 582   if (!Continuations::enabled()) return;
 583   Label done;
 584   ldr(rscratch1, Address(java_thread, JavaThread::cont_fastpath_offset()));
 585   cmp(sp, rscratch1);
 586   br(Assembler::LS, done);
 587   mov(rscratch1, sp); // we can't use sp as the source in str
 588   str(rscratch1, Address(java_thread, JavaThread::cont_fastpath_offset()));
 589   bind(done);
 590 }
 591 
 592 void MacroAssembler::pop_cont_fastpath(Register java_thread) {
 593   if (!Continuations::enabled()) return;
 594   Label done;
 595   ldr(rscratch1, Address(java_thread, JavaThread::cont_fastpath_offset()));
 596   cmp(sp, rscratch1);
 597   br(Assembler::LO, done);
 598   str(zr, Address(java_thread, JavaThread::cont_fastpath_offset()));
 599   bind(done);
 600 }
 601 
 602 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 603   // we must set sp to zero to clear frame
 604   str(zr, Address(rthread, JavaThread::last_Java_sp_offset()));
 605 
 606   // must clear fp, so that compiled frames are not confused; it is
 607   // possible that we need it only for debugging
 608   if (clear_fp) {
 609     str(zr, Address(rthread, JavaThread::last_Java_fp_offset()));
 610   }
 611 
 612   // Always clear the pc because it could have been set by make_walkable()
 613   str(zr, Address(rthread, JavaThread::last_Java_pc_offset()));
 614 }
 615 
 616 // Calls to C land
 617 //
 618 // When entering C land, the rfp, & resp of the last Java frame have to be recorded
 619 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
 620 // has to be reset to 0. This is required to allow proper stack traversal.
 621 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 622                                          Register last_java_fp,
 623                                          Register last_java_pc,
 624                                          Register scratch) {
 625 
 626   if (last_java_pc->is_valid()) {
 627       str(last_java_pc, Address(rthread,
 628                                 JavaThread::frame_anchor_offset()
 629                                 + JavaFrameAnchor::last_Java_pc_offset()));
 630     }
 631 
 632   // determine last_java_sp register
 633   if (last_java_sp == sp) {
 634     mov(scratch, sp);
 635     last_java_sp = scratch;
 636   } else if (!last_java_sp->is_valid()) {
 637     last_java_sp = esp;
 638   }
 639 
 640   str(last_java_sp, Address(rthread, JavaThread::last_Java_sp_offset()));
 641 
 642   // last_java_fp is optional
 643   if (last_java_fp->is_valid()) {
 644     str(last_java_fp, Address(rthread, JavaThread::last_Java_fp_offset()));
 645   }
 646 }
 647 
 648 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 649                                          Register last_java_fp,
 650                                          address  last_java_pc,
 651                                          Register scratch) {
 652   assert(last_java_pc != nullptr, "must provide a valid PC");
 653 
 654   adr(scratch, last_java_pc);
 655   str(scratch, Address(rthread,
 656                        JavaThread::frame_anchor_offset()
 657                        + JavaFrameAnchor::last_Java_pc_offset()));
 658 
 659   set_last_Java_frame(last_java_sp, last_java_fp, noreg, scratch);
 660 }
 661 
 662 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 663                                          Register last_java_fp,
 664                                          Label &L,
 665                                          Register scratch) {
 666   if (L.is_bound()) {
 667     set_last_Java_frame(last_java_sp, last_java_fp, target(L), scratch);
 668   } else {
 669     InstructionMark im(this);
 670     L.add_patch_at(code(), locator());
 671     set_last_Java_frame(last_java_sp, last_java_fp, pc() /* Patched later */, scratch);
 672   }
 673 }
 674 
 675 static inline bool target_needs_far_branch(address addr) {
 676   // codecache size <= 128M
 677   if (!MacroAssembler::far_branches()) {
 678     return false;
 679   }
 680   // codecache size > 240M
 681   if (MacroAssembler::codestub_branch_needs_far_jump()) {
 682     return true;
 683   }
 684   // codecache size: 128M..240M
 685   return !CodeCache::is_non_nmethod(addr);
 686 }
 687 
 688 void MacroAssembler::far_call(Address entry, Register tmp) {
 689   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
 690   assert(CodeCache::find_blob(entry.target()) != nullptr,
 691          "destination of far call not found in code cache");
 692   assert(entry.rspec().type() == relocInfo::external_word_type
 693          || entry.rspec().type() == relocInfo::runtime_call_type
 694          || entry.rspec().type() == relocInfo::none, "wrong entry relocInfo type");
 695   if (target_needs_far_branch(entry.target())) {
 696     uint64_t offset;
 697     // We can use ADRP here because we know that the total size of
 698     // the code cache cannot exceed 2Gb (ADRP limit is 4GB).
 699     adrp(tmp, entry, offset);
 700     add(tmp, tmp, offset);
 701     blr(tmp);
 702   } else {
 703     bl(entry);
 704   }
 705 }
 706 
 707 int MacroAssembler::far_jump(Address entry, Register tmp) {
 708   assert(ReservedCodeCacheSize < 4*G, "branch out of range");
 709   assert(CodeCache::find_blob(entry.target()) != nullptr,
 710          "destination of far call not found in code cache");
 711   assert(entry.rspec().type() == relocInfo::external_word_type
 712          || entry.rspec().type() == relocInfo::runtime_call_type
 713          || entry.rspec().type() == relocInfo::none, "wrong entry relocInfo type");
 714   address start = pc();
 715   if (target_needs_far_branch(entry.target())) {
 716     uint64_t offset;
 717     // We can use ADRP here because we know that the total size of
 718     // the code cache cannot exceed 2Gb (ADRP limit is 4GB).
 719     adrp(tmp, entry, offset);
 720     add(tmp, tmp, offset);
 721     br(tmp);
 722   } else {
 723     b(entry);
 724   }
 725   return pc() - start;
 726 }
 727 
 728 void MacroAssembler::reserved_stack_check() {
 729     // testing if reserved zone needs to be enabled
 730     Label no_reserved_zone_enabling;
 731 
 732     ldr(rscratch1, Address(rthread, JavaThread::reserved_stack_activation_offset()));
 733     cmp(sp, rscratch1);
 734     br(Assembler::LO, no_reserved_zone_enabling);
 735 
 736     enter();   // LR and FP are live.
 737     lea(rscratch1, CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone));
 738     mov(c_rarg0, rthread);
 739     blr(rscratch1);
 740     leave();
 741 
 742     // We have already removed our own frame.
 743     // throw_delayed_StackOverflowError will think that it's been
 744     // called by our caller.
 745     lea(rscratch1, RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
 746     br(rscratch1);
 747     should_not_reach_here();
 748 
 749     bind(no_reserved_zone_enabling);
 750 }
 751 
 752 static void pass_arg0(MacroAssembler* masm, Register arg) {
 753   if (c_rarg0 != arg ) {
 754     masm->mov(c_rarg0, arg);
 755   }
 756 }
 757 
 758 static void pass_arg1(MacroAssembler* masm, Register arg) {
 759   if (c_rarg1 != arg ) {
 760     masm->mov(c_rarg1, arg);
 761   }
 762 }
 763 
 764 static void pass_arg2(MacroAssembler* masm, Register arg) {
 765   if (c_rarg2 != arg ) {
 766     masm->mov(c_rarg2, arg);
 767   }
 768 }
 769 
 770 static void pass_arg3(MacroAssembler* masm, Register arg) {
 771   if (c_rarg3 != arg ) {
 772     masm->mov(c_rarg3, arg);
 773   }
 774 }
 775 
 776 void MacroAssembler::call_VM_base(Register oop_result,
 777                                   Register java_thread,
 778                                   Register last_java_sp,
 779                                   address  entry_point,
 780                                   int      number_of_arguments,
 781                                   bool     check_exceptions) {
 782    // determine java_thread register
 783   if (!java_thread->is_valid()) {
 784     java_thread = rthread;
 785   }
 786 
 787   // determine last_java_sp register
 788   if (!last_java_sp->is_valid()) {
 789     last_java_sp = esp;
 790   }
 791 
 792   // debugging support
 793   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
 794   assert(java_thread == rthread, "unexpected register");
 795 #ifdef ASSERT
 796   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
 797   // if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");
 798 #endif // ASSERT
 799 
 800   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
 801   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
 802 
 803   // push java thread (becomes first argument of C function)
 804 
 805   mov(c_rarg0, java_thread);
 806 
 807   // set last Java frame before call
 808   assert(last_java_sp != rfp, "can't use rfp");
 809 
 810   Label l;
 811   set_last_Java_frame(last_java_sp, rfp, l, rscratch1);
 812 
 813   // do the call, remove parameters
 814   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments, &l);
 815 
 816   // lr could be poisoned with PAC signature during throw_pending_exception
 817   // if it was tail-call optimized by compiler, since lr is not callee-saved
 818   // reload it with proper value
 819   adr(lr, l);
 820 
 821   // reset last Java frame
 822   // Only interpreter should have to clear fp
 823   reset_last_Java_frame(true);
 824 
 825    // C++ interp handles this in the interpreter
 826   check_and_handle_popframe(java_thread);
 827   check_and_handle_earlyret(java_thread);
 828 
 829   if (check_exceptions) {
 830     // check for pending exceptions (java_thread is set upon return)
 831     ldr(rscratch1, Address(java_thread, in_bytes(Thread::pending_exception_offset())));
 832     Label ok;
 833     cbz(rscratch1, ok);
 834     lea(rscratch1, RuntimeAddress(StubRoutines::forward_exception_entry()));
 835     br(rscratch1);
 836     bind(ok);
 837   }
 838 
 839   // get oop result if there is one and reset the value in the thread
 840   if (oop_result->is_valid()) {
 841     get_vm_result(oop_result, java_thread);
 842   }
 843 }
 844 
 845 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
 846   call_VM_base(oop_result, noreg, noreg, entry_point, number_of_arguments, check_exceptions);
 847 }
 848 
 849 // Check the entry target is always reachable from any branch.
 850 static bool is_always_within_branch_range(Address entry) {
 851   const address target = entry.target();
 852 
 853   if (!CodeCache::contains(target)) {
 854     // We always use trampolines for callees outside CodeCache.
 855     assert(entry.rspec().type() == relocInfo::runtime_call_type, "non-runtime call of an external target");
 856     return false;
 857   }
 858 
 859   if (!MacroAssembler::far_branches()) {
 860     return true;
 861   }
 862 
 863   if (entry.rspec().type() == relocInfo::runtime_call_type) {
 864     // Runtime calls are calls of a non-compiled method (stubs, adapters).
 865     // Non-compiled methods stay forever in CodeCache.
 866     // We check whether the longest possible branch is within the branch range.
 867     assert(CodeCache::find_blob(target) != nullptr &&
 868           !CodeCache::find_blob(target)->is_compiled(),
 869           "runtime call of compiled method");
 870     const address right_longest_branch_start = CodeCache::high_bound() - NativeInstruction::instruction_size;
 871     const address left_longest_branch_start = CodeCache::low_bound();
 872     const bool is_reachable = Assembler::reachable_from_branch_at(left_longest_branch_start, target) &&
 873                               Assembler::reachable_from_branch_at(right_longest_branch_start, target);
 874     return is_reachable;
 875   }
 876 
 877   return false;
 878 }
 879 
 880 // Maybe emit a call via a trampoline. If the code cache is small
 881 // trampolines won't be emitted.
 882 address MacroAssembler::trampoline_call(Address entry) {
 883   assert(entry.rspec().type() == relocInfo::runtime_call_type
 884          || entry.rspec().type() == relocInfo::opt_virtual_call_type
 885          || entry.rspec().type() == relocInfo::static_call_type
 886          || entry.rspec().type() == relocInfo::virtual_call_type, "wrong reloc type");
 887 
 888   address target = entry.target();
 889 
 890   if (!is_always_within_branch_range(entry)) {
 891     if (!in_scratch_emit_size()) {
 892       // We don't want to emit a trampoline if C2 is generating dummy
 893       // code during its branch shortening phase.
 894       if (entry.rspec().type() == relocInfo::runtime_call_type) {
 895         assert(CodeBuffer::supports_shared_stubs(), "must support shared stubs");
 896         code()->share_trampoline_for(entry.target(), offset());
 897       } else {
 898         address stub = emit_trampoline_stub(offset(), target);
 899         if (stub == nullptr) {
 900           postcond(pc() == badAddress);
 901           return nullptr; // CodeCache is full
 902         }
 903       }
 904     }
 905     target = pc();
 906   }
 907 
 908   address call_pc = pc();
 909   relocate(entry.rspec());
 910   bl(target);
 911 
 912   postcond(pc() != badAddress);
 913   return call_pc;
 914 }
 915 
 916 // Emit a trampoline stub for a call to a target which is too far away.
 917 //
 918 // code sequences:
 919 //
 920 // call-site:
 921 //   branch-and-link to <destination> or <trampoline stub>
 922 //
 923 // Related trampoline stub for this call site in the stub section:
 924 //   load the call target from the constant pool
 925 //   branch (LR still points to the call site above)
 926 
 927 address MacroAssembler::emit_trampoline_stub(int insts_call_instruction_offset,
 928                                              address dest) {
 929   // Max stub size: alignment nop, TrampolineStub.
 930   address stub = start_a_stub(max_trampoline_stub_size());
 931   if (stub == nullptr) {
 932     return nullptr;  // CodeBuffer::expand failed
 933   }
 934 
 935   // Create a trampoline stub relocation which relates this trampoline stub
 936   // with the call instruction at insts_call_instruction_offset in the
 937   // instructions code-section.
 938   align(wordSize);
 939   relocate(trampoline_stub_Relocation::spec(code()->insts()->start()
 940                                             + insts_call_instruction_offset));
 941   const int stub_start_offset = offset();
 942 
 943   // Now, create the trampoline stub's code:
 944   // - load the call
 945   // - call
 946   Label target;
 947   ldr(rscratch1, target);
 948   br(rscratch1);
 949   bind(target);
 950   assert(offset() - stub_start_offset == NativeCallTrampolineStub::data_offset,
 951          "should be");
 952   emit_int64((int64_t)dest);
 953 
 954   const address stub_start_addr = addr_at(stub_start_offset);
 955 
 956   assert(is_NativeCallTrampolineStub_at(stub_start_addr), "doesn't look like a trampoline");
 957 
 958   end_a_stub();
 959   return stub_start_addr;
 960 }
 961 
 962 int MacroAssembler::max_trampoline_stub_size() {
 963   // Max stub size: alignment nop, TrampolineStub.
 964   return NativeInstruction::instruction_size + NativeCallTrampolineStub::instruction_size;
 965 }
 966 
 967 void MacroAssembler::emit_static_call_stub() {
 968   // CompiledDirectStaticCall::set_to_interpreted knows the
 969   // exact layout of this stub.
 970 
 971   isb();
 972   mov_metadata(rmethod, nullptr);
 973 
 974   // Jump to the entry point of the c2i stub.
 975   movptr(rscratch1, 0);
 976   br(rscratch1);
 977 }
 978 
 979 int MacroAssembler::static_call_stub_size() {
 980   // isb; movk; movz; movz; movk; movz; movz; br
 981   return 8 * NativeInstruction::instruction_size;
 982 }
 983 
 984 void MacroAssembler::c2bool(Register x) {
 985   // implements x == 0 ? 0 : 1
 986   // note: must only look at least-significant byte of x
 987   //       since C-style booleans are stored in one byte
 988   //       only! (was bug)
 989   tst(x, 0xff);
 990   cset(x, Assembler::NE);
 991 }
 992 
 993 address MacroAssembler::ic_call(address entry, jint method_index) {
 994   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
 995   // address const_ptr = long_constant((jlong)Universe::non_oop_word());
 996   // uintptr_t offset;
 997   // ldr_constant(rscratch2, const_ptr);
 998   movptr(rscratch2, (uintptr_t)Universe::non_oop_word());
 999   return trampoline_call(Address(entry, rh));
1000 }
1001 
1002 // Implementation of call_VM versions
1003 
1004 void MacroAssembler::call_VM(Register oop_result,
1005                              address entry_point,
1006                              bool check_exceptions) {
1007   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
1008 }
1009 
1010 void MacroAssembler::call_VM(Register oop_result,
1011                              address entry_point,
1012                              Register arg_1,
1013                              bool check_exceptions) {
1014   pass_arg1(this, arg_1);
1015   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
1016 }
1017 
1018 void MacroAssembler::call_VM(Register oop_result,
1019                              address entry_point,
1020                              Register arg_1,
1021                              Register arg_2,
1022                              bool check_exceptions) {
1023   assert_different_registers(arg_1, c_rarg2);
1024   pass_arg2(this, arg_2);
1025   pass_arg1(this, arg_1);
1026   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
1027 }
1028 
1029 void MacroAssembler::call_VM(Register oop_result,
1030                              address entry_point,
1031                              Register arg_1,
1032                              Register arg_2,
1033                              Register arg_3,
1034                              bool check_exceptions) {
1035   assert_different_registers(arg_1, c_rarg2, c_rarg3);
1036   assert_different_registers(arg_2, c_rarg3);
1037   pass_arg3(this, arg_3);
1038 
1039   pass_arg2(this, arg_2);
1040 
1041   pass_arg1(this, arg_1);
1042   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
1043 }
1044 
1045 void MacroAssembler::call_VM(Register oop_result,
1046                              Register last_java_sp,
1047                              address entry_point,
1048                              int number_of_arguments,
1049                              bool check_exceptions) {
1050   call_VM_base(oop_result, rthread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
1051 }
1052 
1053 void MacroAssembler::call_VM(Register oop_result,
1054                              Register last_java_sp,
1055                              address entry_point,
1056                              Register arg_1,
1057                              bool check_exceptions) {
1058   pass_arg1(this, arg_1);
1059   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
1060 }
1061 
1062 void MacroAssembler::call_VM(Register oop_result,
1063                              Register last_java_sp,
1064                              address entry_point,
1065                              Register arg_1,
1066                              Register arg_2,
1067                              bool check_exceptions) {
1068 
1069   assert_different_registers(arg_1, c_rarg2);
1070   pass_arg2(this, arg_2);
1071   pass_arg1(this, arg_1);
1072   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
1073 }
1074 
1075 void MacroAssembler::call_VM(Register oop_result,
1076                              Register last_java_sp,
1077                              address entry_point,
1078                              Register arg_1,
1079                              Register arg_2,
1080                              Register arg_3,
1081                              bool check_exceptions) {
1082   assert_different_registers(arg_1, c_rarg2, c_rarg3);
1083   assert_different_registers(arg_2, c_rarg3);
1084   pass_arg3(this, arg_3);
1085   pass_arg2(this, arg_2);
1086   pass_arg1(this, arg_1);
1087   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
1088 }
1089 
1090 
1091 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
1092   ldr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
1093   str(zr, Address(java_thread, JavaThread::vm_result_offset()));
1094   verify_oop_msg(oop_result, "broken oop in call_VM_base");
1095 }
1096 
1097 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
1098   ldr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
1099   str(zr, Address(java_thread, JavaThread::vm_result_2_offset()));
1100 }
1101 
1102 void MacroAssembler::align(int modulus) {
1103   while (offset() % modulus != 0) nop();
1104 }
1105 
1106 void MacroAssembler::post_call_nop() {
1107   if (!Continuations::enabled()) {
1108     return;
1109   }
1110   InstructionMark im(this);
1111   relocate(post_call_nop_Relocation::spec());
1112   InlineSkippedInstructionsCounter skipCounter(this);
1113   nop();
1114   movk(zr, 0);
1115   movk(zr, 0);
1116 }
1117 
1118 // these are no-ops overridden by InterpreterMacroAssembler
1119 
1120 void MacroAssembler::check_and_handle_earlyret(Register java_thread) { }
1121 
1122 void MacroAssembler::check_and_handle_popframe(Register java_thread) { }
1123 



































1124 // Look up the method for a megamorphic invokeinterface call.
1125 // The target method is determined by <intf_klass, itable_index>.
1126 // The receiver klass is in recv_klass.
1127 // On success, the result will be in method_result, and execution falls through.
1128 // On failure, execution transfers to the given label.
1129 void MacroAssembler::lookup_interface_method(Register recv_klass,
1130                                              Register intf_klass,
1131                                              RegisterOrConstant itable_index,
1132                                              Register method_result,
1133                                              Register scan_temp,
1134                                              Label& L_no_such_interface,
1135                          bool return_method) {
1136   assert_different_registers(recv_klass, intf_klass, scan_temp);
1137   assert_different_registers(method_result, intf_klass, scan_temp);
1138   assert(recv_klass != method_result || !return_method,
1139      "recv_klass can be destroyed when method isn't needed");
1140   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
1141          "caller must use same register for non-constant itable index as for method");
1142 
1143   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
1144   int vtable_base = in_bytes(Klass::vtable_start_offset());
1145   int itentry_off = in_bytes(itableMethodEntry::method_offset());
1146   int scan_step   = itableOffsetEntry::size() * wordSize;
1147   int vte_size    = vtableEntry::size_in_bytes();
1148   assert(vte_size == wordSize, "else adjust times_vte_scale");
1149 
1150   ldrw(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
1151 
1152   // %%% Could store the aligned, prescaled offset in the klassoop.
1153   // lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
1154   lea(scan_temp, Address(recv_klass, scan_temp, Address::lsl(3)));
1155   add(scan_temp, scan_temp, vtable_base);
1156 
1157   if (return_method) {
1158     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
1159     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
1160     // lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
1161     lea(recv_klass, Address(recv_klass, itable_index, Address::lsl(3)));
1162     if (itentry_off)
1163       add(recv_klass, recv_klass, itentry_off);
1164   }
1165 
1166   // for (scan = klass->itable(); scan->interface() != nullptr; scan += scan_step) {
1167   //   if (scan->interface() == intf) {
1168   //     result = (klass + scan->offset() + itable_index);
1169   //   }
1170   // }
1171   Label search, found_method;
1172 
1173   ldr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset()));
1174   cmp(intf_klass, method_result);
1175   br(Assembler::EQ, found_method);
1176   bind(search);
1177   // Check that the previous entry is non-null.  A null entry means that
1178   // the receiver class doesn't implement the interface, and wasn't the
1179   // same as when the caller was compiled.
1180   cbz(method_result, L_no_such_interface);
1181   if (itableOffsetEntry::interface_offset() != 0) {
1182     add(scan_temp, scan_temp, scan_step);
1183     ldr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset()));
1184   } else {
1185     ldr(method_result, Address(pre(scan_temp, scan_step)));
1186   }
1187   cmp(intf_klass, method_result);
1188   br(Assembler::NE, search);
1189 
1190   bind(found_method);
1191 
1192   // Got a hit.
1193   if (return_method) {
1194     ldrw(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset()));
1195     ldr(method_result, Address(recv_klass, scan_temp, Address::uxtw(0)));
1196   }
1197 }
1198 
1199 // Look up the method for a megamorphic invokeinterface call in a single pass over itable:
1200 // - check recv_klass (actual object class) is a subtype of resolved_klass from CompiledICHolder
1201 // - find a holder_klass (class that implements the method) vtable offset and get the method from vtable by index
1202 // The target method is determined by <holder_klass, itable_index>.
1203 // The receiver klass is in recv_klass.
1204 // On success, the result will be in method_result, and execution falls through.
1205 // On failure, execution transfers to the given label.
1206 void MacroAssembler::lookup_interface_method_stub(Register recv_klass,
1207                                                   Register holder_klass,
1208                                                   Register resolved_klass,
1209                                                   Register method_result,
1210                                                   Register temp_itbl_klass,
1211                                                   Register scan_temp,
1212                                                   int itable_index,
1213                                                   Label& L_no_such_interface) {
1214   // 'method_result' is only used as output register at the very end of this method.
1215   // Until then we can reuse it as 'holder_offset'.
1216   Register holder_offset = method_result;
1217   assert_different_registers(resolved_klass, recv_klass, holder_klass, temp_itbl_klass, scan_temp, holder_offset);
1218 
1219   int vtable_start_offset = in_bytes(Klass::vtable_start_offset());
1220   int itable_offset_entry_size = itableOffsetEntry::size() * wordSize;
1221   int ioffset = in_bytes(itableOffsetEntry::interface_offset());
1222   int ooffset = in_bytes(itableOffsetEntry::offset_offset());
1223 
1224   Label L_loop_search_resolved_entry, L_resolved_found, L_holder_found;
1225 
1226   ldrw(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
1227   add(recv_klass, recv_klass, vtable_start_offset + ioffset);
1228   // itableOffsetEntry[] itable = recv_klass + Klass::vtable_start_offset() + sizeof(vtableEntry) * recv_klass->_vtable_len;
1229   // temp_itbl_klass = itable[0]._interface;
1230   int vtblEntrySize = vtableEntry::size_in_bytes();
1231   assert(vtblEntrySize == wordSize, "ldr lsl shift amount must be 3");
1232   ldr(temp_itbl_klass, Address(recv_klass, scan_temp, Address::lsl(exact_log2(vtblEntrySize))));
1233   mov(holder_offset, zr);
1234   // scan_temp = &(itable[0]._interface)
1235   lea(scan_temp, Address(recv_klass, scan_temp, Address::lsl(exact_log2(vtblEntrySize))));
1236 
1237   // Initial checks:
1238   //   - if (holder_klass != resolved_klass), go to "scan for resolved"
1239   //   - if (itable[0] == holder_klass), shortcut to "holder found"
1240   //   - if (itable[0] == 0), no such interface
1241   cmp(resolved_klass, holder_klass);
1242   br(Assembler::NE, L_loop_search_resolved_entry);
1243   cmp(holder_klass, temp_itbl_klass);
1244   br(Assembler::EQ, L_holder_found);
1245   cbz(temp_itbl_klass, L_no_such_interface);
1246 
1247   // Loop: Look for holder_klass record in itable
1248   //   do {
1249   //     temp_itbl_klass = *(scan_temp += itable_offset_entry_size);
1250   //     if (temp_itbl_klass == holder_klass) {
1251   //       goto L_holder_found; // Found!
1252   //     }
1253   //   } while (temp_itbl_klass != 0);
1254   //   goto L_no_such_interface // Not found.
1255   Label L_search_holder;
1256   bind(L_search_holder);
1257     ldr(temp_itbl_klass, Address(pre(scan_temp, itable_offset_entry_size)));
1258     cmp(holder_klass, temp_itbl_klass);
1259     br(Assembler::EQ, L_holder_found);
1260     cbnz(temp_itbl_klass, L_search_holder);
1261 
1262   b(L_no_such_interface);
1263 
1264   // Loop: Look for resolved_class record in itable
1265   //   while (true) {
1266   //     temp_itbl_klass = *(scan_temp += itable_offset_entry_size);
1267   //     if (temp_itbl_klass == 0) {
1268   //       goto L_no_such_interface;
1269   //     }
1270   //     if (temp_itbl_klass == resolved_klass) {
1271   //        goto L_resolved_found;  // Found!
1272   //     }
1273   //     if (temp_itbl_klass == holder_klass) {
1274   //        holder_offset = scan_temp;
1275   //     }
1276   //   }
1277   //
1278   Label L_loop_search_resolved;
1279   bind(L_loop_search_resolved);
1280     ldr(temp_itbl_klass, Address(pre(scan_temp, itable_offset_entry_size)));
1281   bind(L_loop_search_resolved_entry);
1282     cbz(temp_itbl_klass, L_no_such_interface);
1283     cmp(resolved_klass, temp_itbl_klass);
1284     br(Assembler::EQ, L_resolved_found);
1285     cmp(holder_klass, temp_itbl_klass);
1286     br(Assembler::NE, L_loop_search_resolved);
1287     mov(holder_offset, scan_temp);
1288     b(L_loop_search_resolved);
1289 
1290   // See if we already have a holder klass. If not, go and scan for it.
1291   bind(L_resolved_found);
1292   cbz(holder_offset, L_search_holder);
1293   mov(scan_temp, holder_offset);
1294 
1295   // Finally, scan_temp contains holder_klass vtable offset
1296   bind(L_holder_found);
1297   ldrw(method_result, Address(scan_temp, ooffset - ioffset));
1298   add(recv_klass, recv_klass, itable_index * wordSize + in_bytes(itableMethodEntry::method_offset())
1299     - vtable_start_offset - ioffset); // substract offsets to restore the original value of recv_klass
1300   ldr(method_result, Address(recv_klass, method_result, Address::uxtw(0)));
1301 }
1302 
1303 // virtual method calling
1304 void MacroAssembler::lookup_virtual_method(Register recv_klass,
1305                                            RegisterOrConstant vtable_index,
1306                                            Register method_result) {
1307   assert(vtableEntry::size() * wordSize == 8,
1308          "adjust the scaling in the code below");
1309   int64_t vtable_offset_in_bytes = in_bytes(Klass::vtable_start_offset() + vtableEntry::method_offset());
1310 
1311   if (vtable_index.is_register()) {
1312     lea(method_result, Address(recv_klass,
1313                                vtable_index.as_register(),
1314                                Address::lsl(LogBytesPerWord)));
1315     ldr(method_result, Address(method_result, vtable_offset_in_bytes));
1316   } else {
1317     vtable_offset_in_bytes += vtable_index.as_constant() * wordSize;
1318     ldr(method_result,
1319         form_address(rscratch1, recv_klass, vtable_offset_in_bytes, 0));
1320   }
1321 }
1322 
1323 void MacroAssembler::check_klass_subtype(Register sub_klass,
1324                            Register super_klass,
1325                            Register temp_reg,
1326                            Label& L_success) {
1327   Label L_failure;
1328   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, nullptr);
1329   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, nullptr);
1330   bind(L_failure);
1331 }
1332 
1333 
1334 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
1335                                                    Register super_klass,
1336                                                    Register temp_reg,
1337                                                    Label* L_success,
1338                                                    Label* L_failure,
1339                                                    Label* L_slow_path,
1340                                         RegisterOrConstant super_check_offset) {
1341   assert_different_registers(sub_klass, super_klass, temp_reg);
1342   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
1343   if (super_check_offset.is_register()) {
1344     assert_different_registers(sub_klass, super_klass,
1345                                super_check_offset.as_register());
1346   } else if (must_load_sco) {
1347     assert(temp_reg != noreg, "supply either a temp or a register offset");
1348   }
1349 
1350   Label L_fallthrough;
1351   int label_nulls = 0;
1352   if (L_success == nullptr)   { L_success   = &L_fallthrough; label_nulls++; }
1353   if (L_failure == nullptr)   { L_failure   = &L_fallthrough; label_nulls++; }
1354   if (L_slow_path == nullptr) { L_slow_path = &L_fallthrough; label_nulls++; }
1355   assert(label_nulls <= 1, "at most one null in the batch");
1356 
1357   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1358   int sco_offset = in_bytes(Klass::super_check_offset_offset());
1359   Address super_check_offset_addr(super_klass, sco_offset);
1360 
1361   // Hacked jmp, which may only be used just before L_fallthrough.
1362 #define final_jmp(label)                                                \
1363   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
1364   else                            b(label)                /*omit semi*/
1365 
1366   // If the pointers are equal, we are done (e.g., String[] elements).
1367   // This self-check enables sharing of secondary supertype arrays among
1368   // non-primary types such as array-of-interface.  Otherwise, each such
1369   // type would need its own customized SSA.
1370   // We move this check to the front of the fast path because many
1371   // type checks are in fact trivially successful in this manner,
1372   // so we get a nicely predicted branch right at the start of the check.
1373   cmp(sub_klass, super_klass);
1374   br(Assembler::EQ, *L_success);
1375 
1376   // Check the supertype display:
1377   if (must_load_sco) {
1378     ldrw(temp_reg, super_check_offset_addr);
1379     super_check_offset = RegisterOrConstant(temp_reg);
1380   }
1381   Address super_check_addr(sub_klass, super_check_offset);
1382   ldr(rscratch1, super_check_addr);
1383   cmp(super_klass, rscratch1); // load displayed supertype
1384 
1385   // This check has worked decisively for primary supers.
1386   // Secondary supers are sought in the super_cache ('super_cache_addr').
1387   // (Secondary supers are interfaces and very deeply nested subtypes.)
1388   // This works in the same check above because of a tricky aliasing
1389   // between the super_cache and the primary super display elements.
1390   // (The 'super_check_addr' can address either, as the case requires.)
1391   // Note that the cache is updated below if it does not help us find
1392   // what we need immediately.
1393   // So if it was a primary super, we can just fail immediately.
1394   // Otherwise, it's the slow path for us (no success at this point).
1395 
1396   if (super_check_offset.is_register()) {
1397     br(Assembler::EQ, *L_success);
1398     subs(zr, super_check_offset.as_register(), sc_offset);
1399     if (L_failure == &L_fallthrough) {
1400       br(Assembler::EQ, *L_slow_path);
1401     } else {
1402       br(Assembler::NE, *L_failure);
1403       final_jmp(*L_slow_path);
1404     }
1405   } else if (super_check_offset.as_constant() == sc_offset) {
1406     // Need a slow path; fast failure is impossible.
1407     if (L_slow_path == &L_fallthrough) {
1408       br(Assembler::EQ, *L_success);
1409     } else {
1410       br(Assembler::NE, *L_slow_path);
1411       final_jmp(*L_success);
1412     }
1413   } else {
1414     // No slow path; it's a fast decision.
1415     if (L_failure == &L_fallthrough) {
1416       br(Assembler::EQ, *L_success);
1417     } else {
1418       br(Assembler::NE, *L_failure);
1419       final_jmp(*L_success);
1420     }
1421   }
1422 
1423   bind(L_fallthrough);
1424 
1425 #undef final_jmp
1426 }
1427 
1428 // These two are taken from x86, but they look generally useful
1429 
1430 // scans count pointer sized words at [addr] for occurrence of value,
1431 // generic
1432 void MacroAssembler::repne_scan(Register addr, Register value, Register count,
1433                                 Register scratch) {
1434   Label Lloop, Lexit;
1435   cbz(count, Lexit);
1436   bind(Lloop);
1437   ldr(scratch, post(addr, wordSize));
1438   cmp(value, scratch);
1439   br(EQ, Lexit);
1440   sub(count, count, 1);
1441   cbnz(count, Lloop);
1442   bind(Lexit);
1443 }
1444 
1445 // scans count 4 byte words at [addr] for occurrence of value,
1446 // generic
1447 void MacroAssembler::repne_scanw(Register addr, Register value, Register count,
1448                                 Register scratch) {
1449   Label Lloop, Lexit;
1450   cbz(count, Lexit);
1451   bind(Lloop);
1452   ldrw(scratch, post(addr, wordSize));
1453   cmpw(value, scratch);
1454   br(EQ, Lexit);
1455   sub(count, count, 1);
1456   cbnz(count, Lloop);
1457   bind(Lexit);
1458 }
1459 
1460 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
1461                                                    Register super_klass,
1462                                                    Register temp_reg,
1463                                                    Register temp2_reg,
1464                                                    Label* L_success,
1465                                                    Label* L_failure,
1466                                                    bool set_cond_codes) {
1467   assert_different_registers(sub_klass, super_klass, temp_reg);
1468   if (temp2_reg != noreg)
1469     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg, rscratch1);
1470 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
1471 
1472   Label L_fallthrough;
1473   int label_nulls = 0;
1474   if (L_success == nullptr)   { L_success   = &L_fallthrough; label_nulls++; }
1475   if (L_failure == nullptr)   { L_failure   = &L_fallthrough; label_nulls++; }
1476   assert(label_nulls <= 1, "at most one null in the batch");
1477 
1478   // a couple of useful fields in sub_klass:
1479   int ss_offset = in_bytes(Klass::secondary_supers_offset());
1480   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1481   Address secondary_supers_addr(sub_klass, ss_offset);
1482   Address super_cache_addr(     sub_klass, sc_offset);
1483 
1484   BLOCK_COMMENT("check_klass_subtype_slow_path");
1485 
1486   // Do a linear scan of the secondary super-klass chain.
1487   // This code is rarely used, so simplicity is a virtue here.
1488   // The repne_scan instruction uses fixed registers, which we must spill.
1489   // Don't worry too much about pre-existing connections with the input regs.
1490 
1491   assert(sub_klass != r0, "killed reg"); // killed by mov(r0, super)
1492   assert(sub_klass != r2, "killed reg"); // killed by lea(r2, &pst_counter)
1493 
1494   RegSet pushed_registers;
1495   if (!IS_A_TEMP(r2))    pushed_registers += r2;
1496   if (!IS_A_TEMP(r5))    pushed_registers += r5;
1497 
1498   if (super_klass != r0) {
1499     if (!IS_A_TEMP(r0))   pushed_registers += r0;
1500   }
1501 
1502   push(pushed_registers, sp);
1503 
1504   // Get super_klass value into r0 (even if it was in r5 or r2).
1505   if (super_klass != r0) {
1506     mov(r0, super_klass);
1507   }
1508 
1509 #ifndef PRODUCT
1510   mov(rscratch2, (address)&SharedRuntime::_partial_subtype_ctr);
1511   Address pst_counter_addr(rscratch2);
1512   ldr(rscratch1, pst_counter_addr);
1513   add(rscratch1, rscratch1, 1);
1514   str(rscratch1, pst_counter_addr);
1515 #endif //PRODUCT
1516 
1517   // We will consult the secondary-super array.
1518   ldr(r5, secondary_supers_addr);
1519   // Load the array length.
1520   ldrw(r2, Address(r5, Array<Klass*>::length_offset_in_bytes()));
1521   // Skip to start of data.
1522   add(r5, r5, Array<Klass*>::base_offset_in_bytes());
1523 
1524   cmp(sp, zr); // Clear Z flag; SP is never zero
1525   // Scan R2 words at [R5] for an occurrence of R0.
1526   // Set NZ/Z based on last compare.
1527   repne_scan(r5, r0, r2, rscratch1);
1528 
1529   // Unspill the temp. registers:
1530   pop(pushed_registers, sp);
1531 
1532   br(Assembler::NE, *L_failure);
1533 
1534   // Success.  Cache the super we found and proceed in triumph.
1535   str(super_klass, super_cache_addr);
1536 
1537   if (L_success != &L_fallthrough) {
1538     b(*L_success);
1539   }
1540 
1541 #undef IS_A_TEMP
1542 
1543   bind(L_fallthrough);
1544 }
1545 
1546 void MacroAssembler::clinit_barrier(Register klass, Register scratch, Label* L_fast_path, Label* L_slow_path) {
1547   assert(L_fast_path != nullptr || L_slow_path != nullptr, "at least one is required");
1548   assert_different_registers(klass, rthread, scratch);
1549 
1550   Label L_fallthrough, L_tmp;
1551   if (L_fast_path == nullptr) {
1552     L_fast_path = &L_fallthrough;
1553   } else if (L_slow_path == nullptr) {
1554     L_slow_path = &L_fallthrough;
1555   }
1556   // Fast path check: class is fully initialized
1557   ldrb(scratch, Address(klass, InstanceKlass::init_state_offset()));
1558   subs(zr, scratch, InstanceKlass::fully_initialized);
1559   br(Assembler::EQ, *L_fast_path);
1560 
1561   // Fast path check: current thread is initializer thread
1562   ldr(scratch, Address(klass, InstanceKlass::init_thread_offset()));
1563   cmp(rthread, scratch);
1564 
1565   if (L_slow_path == &L_fallthrough) {
1566     br(Assembler::EQ, *L_fast_path);
1567     bind(*L_slow_path);
1568   } else if (L_fast_path == &L_fallthrough) {
1569     br(Assembler::NE, *L_slow_path);
1570     bind(*L_fast_path);
1571   } else {
1572     Unimplemented();
1573   }
1574 }
1575 
1576 void MacroAssembler::_verify_oop(Register reg, const char* s, const char* file, int line) {
1577   if (!VerifyOops) return;




1578 
1579   // Pass register number to verify_oop_subroutine
1580   const char* b = nullptr;
1581   {
1582     ResourceMark rm;
1583     stringStream ss;
1584     ss.print("verify_oop: %s: %s (%s:%d)", reg->name(), s, file, line);
1585     b = code_string(ss.as_string());
1586   }
1587   BLOCK_COMMENT("verify_oop {");
1588 
1589   strip_return_address(); // This might happen within a stack frame.
1590   protect_return_address();
1591   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
1592   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
1593 
1594   mov(r0, reg);
1595   movptr(rscratch1, (uintptr_t)(address)b);
1596 
1597   // call indirectly to solve generation ordering problem
1598   lea(rscratch2, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
1599   ldr(rscratch2, Address(rscratch2));
1600   blr(rscratch2);
1601 
1602   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
1603   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
1604   authenticate_return_address();
1605 
1606   BLOCK_COMMENT("} verify_oop");
1607 }
1608 
1609 void MacroAssembler::_verify_oop_addr(Address addr, const char* s, const char* file, int line) {
1610   if (!VerifyOops) return;




1611 
1612   const char* b = nullptr;
1613   {
1614     ResourceMark rm;
1615     stringStream ss;
1616     ss.print("verify_oop_addr: %s (%s:%d)", s, file, line);
1617     b = code_string(ss.as_string());
1618   }
1619   BLOCK_COMMENT("verify_oop_addr {");
1620 
1621   strip_return_address(); // This might happen within a stack frame.
1622   protect_return_address();
1623   stp(r0, rscratch1, Address(pre(sp, -2 * wordSize)));
1624   stp(rscratch2, lr, Address(pre(sp, -2 * wordSize)));
1625 
1626   // addr may contain sp so we will have to adjust it based on the
1627   // pushes that we just did.
1628   if (addr.uses(sp)) {
1629     lea(r0, addr);
1630     ldr(r0, Address(r0, 4 * wordSize));
1631   } else {
1632     ldr(r0, addr);
1633   }
1634   movptr(rscratch1, (uintptr_t)(address)b);
1635 
1636   // call indirectly to solve generation ordering problem
1637   lea(rscratch2, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
1638   ldr(rscratch2, Address(rscratch2));
1639   blr(rscratch2);
1640 
1641   ldp(rscratch2, lr, Address(post(sp, 2 * wordSize)));
1642   ldp(r0, rscratch1, Address(post(sp, 2 * wordSize)));
1643   authenticate_return_address();
1644 
1645   BLOCK_COMMENT("} verify_oop_addr");
1646 }
1647 
1648 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
1649                                          int extra_slot_offset) {
1650   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
1651   int stackElementSize = Interpreter::stackElementSize;
1652   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
1653 #ifdef ASSERT
1654   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
1655   assert(offset1 - offset == stackElementSize, "correct arithmetic");
1656 #endif
1657   if (arg_slot.is_constant()) {
1658     return Address(esp, arg_slot.as_constant() * stackElementSize
1659                    + offset);
1660   } else {
1661     add(rscratch1, esp, arg_slot.as_register(),
1662         ext::uxtx, exact_log2(stackElementSize));
1663     return Address(rscratch1, offset);
1664   }
1665 }
1666 
1667 void MacroAssembler::call_VM_leaf_base(address entry_point,
1668                                        int number_of_arguments,
1669                                        Label *retaddr) {
1670   Label E, L;
1671 
1672   stp(rscratch1, rmethod, Address(pre(sp, -2 * wordSize)));
1673 
1674   mov(rscratch1, entry_point);
1675   blr(rscratch1);
1676   if (retaddr)
1677     bind(*retaddr);
1678 
1679   ldp(rscratch1, rmethod, Address(post(sp, 2 * wordSize)));
1680 }
1681 
1682 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
1683   call_VM_leaf_base(entry_point, number_of_arguments);
1684 }
1685 
1686 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
1687   pass_arg0(this, arg_0);
1688   call_VM_leaf_base(entry_point, 1);
1689 }
1690 
1691 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1692   assert_different_registers(arg_1, c_rarg0);
1693   pass_arg0(this, arg_0);
1694   pass_arg1(this, arg_1);
1695   call_VM_leaf_base(entry_point, 2);
1696 }
1697 
1698 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0,
1699                                   Register arg_1, Register arg_2) {
1700   assert_different_registers(arg_1, c_rarg0);
1701   assert_different_registers(arg_2, c_rarg0, c_rarg1);
1702   pass_arg0(this, arg_0);
1703   pass_arg1(this, arg_1);
1704   pass_arg2(this, arg_2);
1705   call_VM_leaf_base(entry_point, 3);
1706 }
1707 




1708 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
1709   pass_arg0(this, arg_0);
1710   MacroAssembler::call_VM_leaf_base(entry_point, 1);
1711 }
1712 
1713 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
1714 
1715   assert_different_registers(arg_0, c_rarg1);
1716   pass_arg1(this, arg_1);
1717   pass_arg0(this, arg_0);
1718   MacroAssembler::call_VM_leaf_base(entry_point, 2);
1719 }
1720 
1721 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
1722   assert_different_registers(arg_0, c_rarg1, c_rarg2);
1723   assert_different_registers(arg_1, c_rarg2);
1724   pass_arg2(this, arg_2);
1725   pass_arg1(this, arg_1);
1726   pass_arg0(this, arg_0);
1727   MacroAssembler::call_VM_leaf_base(entry_point, 3);
1728 }
1729 
1730 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
1731   assert_different_registers(arg_0, c_rarg1, c_rarg2, c_rarg3);
1732   assert_different_registers(arg_1, c_rarg2, c_rarg3);
1733   assert_different_registers(arg_2, c_rarg3);
1734   pass_arg3(this, arg_3);
1735   pass_arg2(this, arg_2);
1736   pass_arg1(this, arg_1);
1737   pass_arg0(this, arg_0);
1738   MacroAssembler::call_VM_leaf_base(entry_point, 4);
1739 }
1740 
1741 void MacroAssembler::null_check(Register reg, int offset) {
1742   if (needs_explicit_null_check(offset)) {
1743     // provoke OS null exception if reg is null by
1744     // accessing M[reg] w/o changing any registers
1745     // NOTE: this is plenty to provoke a segv
1746     ldr(zr, Address(reg));
1747   } else {
1748     // nothing to do, (later) access of M[reg + offset]
1749     // will provoke OS null exception if reg is null
1750   }
1751 }
1752 









































































































1753 // MacroAssembler protected routines needed to implement
1754 // public methods
1755 
1756 void MacroAssembler::mov(Register r, Address dest) {
1757   code_section()->relocate(pc(), dest.rspec());
1758   uint64_t imm64 = (uint64_t)dest.target();
1759   movptr(r, imm64);
1760 }
1761 
1762 // Move a constant pointer into r.  In AArch64 mode the virtual
1763 // address space is 48 bits in size, so we only need three
1764 // instructions to create a patchable instruction sequence that can
1765 // reach anywhere.
1766 void MacroAssembler::movptr(Register r, uintptr_t imm64) {
1767 #ifndef PRODUCT
1768   {
1769     char buffer[64];
1770     snprintf(buffer, sizeof(buffer), "0x%" PRIX64, (uint64_t)imm64);
1771     block_comment(buffer);
1772   }
1773 #endif
1774   assert(imm64 < (1ull << 48), "48-bit overflow in address constant");
1775   movz(r, imm64 & 0xffff);
1776   imm64 >>= 16;
1777   movk(r, imm64 & 0xffff, 16);
1778   imm64 >>= 16;
1779   movk(r, imm64 & 0xffff, 32);
1780 }
1781 
1782 // Macro to mov replicated immediate to vector register.
1783 // imm64: only the lower 8/16/32 bits are considered for B/H/S type. That is,
1784 //        the upper 56/48/32 bits must be zeros for B/H/S type.
1785 // Vd will get the following values for different arrangements in T
1786 //   imm64 == hex 000000gh  T8B:  Vd = ghghghghghghghgh
1787 //   imm64 == hex 000000gh  T16B: Vd = ghghghghghghghghghghghghghghghgh
1788 //   imm64 == hex 0000efgh  T4H:  Vd = efghefghefghefgh
1789 //   imm64 == hex 0000efgh  T8H:  Vd = efghefghefghefghefghefghefghefgh
1790 //   imm64 == hex abcdefgh  T2S:  Vd = abcdefghabcdefgh
1791 //   imm64 == hex abcdefgh  T4S:  Vd = abcdefghabcdefghabcdefghabcdefgh
1792 //   imm64 == hex abcdefgh  T1D:  Vd = 00000000abcdefgh
1793 //   imm64 == hex abcdefgh  T2D:  Vd = 00000000abcdefgh00000000abcdefgh
1794 // Clobbers rscratch1
1795 void MacroAssembler::mov(FloatRegister Vd, SIMD_Arrangement T, uint64_t imm64) {
1796   assert(T != T1Q, "unsupported");
1797   if (T == T1D || T == T2D) {
1798     int imm = operand_valid_for_movi_immediate(imm64, T);
1799     if (-1 != imm) {
1800       movi(Vd, T, imm);
1801     } else {
1802       mov(rscratch1, imm64);
1803       dup(Vd, T, rscratch1);
1804     }
1805     return;
1806   }
1807 
1808 #ifdef ASSERT
1809   if (T == T8B || T == T16B) assert((imm64 & ~0xff) == 0, "extraneous bits (T8B/T16B)");
1810   if (T == T4H || T == T8H) assert((imm64  & ~0xffff) == 0, "extraneous bits (T4H/T8H)");
1811   if (T == T2S || T == T4S) assert((imm64  & ~0xffffffff) == 0, "extraneous bits (T2S/T4S)");
1812 #endif
1813   int shift = operand_valid_for_movi_immediate(imm64, T);
1814   uint32_t imm32 = imm64 & 0xffffffffULL;
1815   if (shift >= 0) {
1816     movi(Vd, T, (imm32 >> shift) & 0xff, shift);
1817   } else {
1818     movw(rscratch1, imm32);
1819     dup(Vd, T, rscratch1);
1820   }
1821 }
1822 
1823 void MacroAssembler::mov_immediate64(Register dst, uint64_t imm64)
1824 {
1825 #ifndef PRODUCT
1826   {
1827     char buffer[64];
1828     snprintf(buffer, sizeof(buffer), "0x%" PRIX64, imm64);
1829     block_comment(buffer);
1830   }
1831 #endif
1832   if (operand_valid_for_logical_immediate(false, imm64)) {
1833     orr(dst, zr, imm64);
1834   } else {
1835     // we can use a combination of MOVZ or MOVN with
1836     // MOVK to build up the constant
1837     uint64_t imm_h[4];
1838     int zero_count = 0;
1839     int neg_count = 0;
1840     int i;
1841     for (i = 0; i < 4; i++) {
1842       imm_h[i] = ((imm64 >> (i * 16)) & 0xffffL);
1843       if (imm_h[i] == 0) {
1844         zero_count++;
1845       } else if (imm_h[i] == 0xffffL) {
1846         neg_count++;
1847       }
1848     }
1849     if (zero_count == 4) {
1850       // one MOVZ will do
1851       movz(dst, 0);
1852     } else if (neg_count == 4) {
1853       // one MOVN will do
1854       movn(dst, 0);
1855     } else if (zero_count == 3) {
1856       for (i = 0; i < 4; i++) {
1857         if (imm_h[i] != 0L) {
1858           movz(dst, (uint32_t)imm_h[i], (i << 4));
1859           break;
1860         }
1861       }
1862     } else if (neg_count == 3) {
1863       // one MOVN will do
1864       for (int i = 0; i < 4; i++) {
1865         if (imm_h[i] != 0xffffL) {
1866           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
1867           break;
1868         }
1869       }
1870     } else if (zero_count == 2) {
1871       // one MOVZ and one MOVK will do
1872       for (i = 0; i < 3; i++) {
1873         if (imm_h[i] != 0L) {
1874           movz(dst, (uint32_t)imm_h[i], (i << 4));
1875           i++;
1876           break;
1877         }
1878       }
1879       for (;i < 4; i++) {
1880         if (imm_h[i] != 0L) {
1881           movk(dst, (uint32_t)imm_h[i], (i << 4));
1882         }
1883       }
1884     } else if (neg_count == 2) {
1885       // one MOVN and one MOVK will do
1886       for (i = 0; i < 4; i++) {
1887         if (imm_h[i] != 0xffffL) {
1888           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
1889           i++;
1890           break;
1891         }
1892       }
1893       for (;i < 4; i++) {
1894         if (imm_h[i] != 0xffffL) {
1895           movk(dst, (uint32_t)imm_h[i], (i << 4));
1896         }
1897       }
1898     } else if (zero_count == 1) {
1899       // one MOVZ and two MOVKs will do
1900       for (i = 0; i < 4; i++) {
1901         if (imm_h[i] != 0L) {
1902           movz(dst, (uint32_t)imm_h[i], (i << 4));
1903           i++;
1904           break;
1905         }
1906       }
1907       for (;i < 4; i++) {
1908         if (imm_h[i] != 0x0L) {
1909           movk(dst, (uint32_t)imm_h[i], (i << 4));
1910         }
1911       }
1912     } else if (neg_count == 1) {
1913       // one MOVN and two MOVKs will do
1914       for (i = 0; i < 4; i++) {
1915         if (imm_h[i] != 0xffffL) {
1916           movn(dst, (uint32_t)imm_h[i] ^ 0xffffL, (i << 4));
1917           i++;
1918           break;
1919         }
1920       }
1921       for (;i < 4; i++) {
1922         if (imm_h[i] != 0xffffL) {
1923           movk(dst, (uint32_t)imm_h[i], (i << 4));
1924         }
1925       }
1926     } else {
1927       // use a MOVZ and 3 MOVKs (makes it easier to debug)
1928       movz(dst, (uint32_t)imm_h[0], 0);
1929       for (i = 1; i < 4; i++) {
1930         movk(dst, (uint32_t)imm_h[i], (i << 4));
1931       }
1932     }
1933   }
1934 }
1935 
1936 void MacroAssembler::mov_immediate32(Register dst, uint32_t imm32)
1937 {
1938 #ifndef PRODUCT
1939     {
1940       char buffer[64];
1941       snprintf(buffer, sizeof(buffer), "0x%" PRIX32, imm32);
1942       block_comment(buffer);
1943     }
1944 #endif
1945   if (operand_valid_for_logical_immediate(true, imm32)) {
1946     orrw(dst, zr, imm32);
1947   } else {
1948     // we can use MOVZ, MOVN or two calls to MOVK to build up the
1949     // constant
1950     uint32_t imm_h[2];
1951     imm_h[0] = imm32 & 0xffff;
1952     imm_h[1] = ((imm32 >> 16) & 0xffff);
1953     if (imm_h[0] == 0) {
1954       movzw(dst, imm_h[1], 16);
1955     } else if (imm_h[0] == 0xffff) {
1956       movnw(dst, imm_h[1] ^ 0xffff, 16);
1957     } else if (imm_h[1] == 0) {
1958       movzw(dst, imm_h[0], 0);
1959     } else if (imm_h[1] == 0xffff) {
1960       movnw(dst, imm_h[0] ^ 0xffff, 0);
1961     } else {
1962       // use a MOVZ and MOVK (makes it easier to debug)
1963       movzw(dst, imm_h[0], 0);
1964       movkw(dst, imm_h[1], 16);
1965     }
1966   }
1967 }
1968 
1969 // Form an address from base + offset in Rd.  Rd may or may
1970 // not actually be used: you must use the Address that is returned.
1971 // It is up to you to ensure that the shift provided matches the size
1972 // of your data.
1973 Address MacroAssembler::form_address(Register Rd, Register base, int64_t byte_offset, int shift) {
1974   if (Address::offset_ok_for_immed(byte_offset, shift))
1975     // It fits; no need for any heroics
1976     return Address(base, byte_offset);
1977 
1978   // Don't do anything clever with negative or misaligned offsets
1979   unsigned mask = (1 << shift) - 1;
1980   if (byte_offset < 0 || byte_offset & mask) {
1981     mov(Rd, byte_offset);
1982     add(Rd, base, Rd);
1983     return Address(Rd);
1984   }
1985 
1986   // See if we can do this with two 12-bit offsets
1987   {
1988     uint64_t word_offset = byte_offset >> shift;
1989     uint64_t masked_offset = word_offset & 0xfff000;
1990     if (Address::offset_ok_for_immed(word_offset - masked_offset, 0)
1991         && Assembler::operand_valid_for_add_sub_immediate(masked_offset << shift)) {
1992       add(Rd, base, masked_offset << shift);
1993       word_offset -= masked_offset;
1994       return Address(Rd, word_offset << shift);
1995     }
1996   }
1997 
1998   // Do it the hard way
1999   mov(Rd, byte_offset);
2000   add(Rd, base, Rd);
2001   return Address(Rd);
2002 }
2003 
2004 int MacroAssembler::corrected_idivl(Register result, Register ra, Register rb,
2005                                     bool want_remainder, Register scratch)
2006 {
2007   // Full implementation of Java idiv and irem.  The function
2008   // returns the (pc) offset of the div instruction - may be needed
2009   // for implicit exceptions.
2010   //
2011   // constraint : ra/rb =/= scratch
2012   //         normal case
2013   //
2014   // input : ra: dividend
2015   //         rb: divisor
2016   //
2017   // result: either
2018   //         quotient  (= ra idiv rb)
2019   //         remainder (= ra irem rb)
2020 
2021   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
2022 
2023   int idivl_offset = offset();
2024   if (! want_remainder) {
2025     sdivw(result, ra, rb);
2026   } else {
2027     sdivw(scratch, ra, rb);
2028     Assembler::msubw(result, scratch, rb, ra);
2029   }
2030 
2031   return idivl_offset;
2032 }
2033 
2034 int MacroAssembler::corrected_idivq(Register result, Register ra, Register rb,
2035                                     bool want_remainder, Register scratch)
2036 {
2037   // Full implementation of Java ldiv and lrem.  The function
2038   // returns the (pc) offset of the div instruction - may be needed
2039   // for implicit exceptions.
2040   //
2041   // constraint : ra/rb =/= scratch
2042   //         normal case
2043   //
2044   // input : ra: dividend
2045   //         rb: divisor
2046   //
2047   // result: either
2048   //         quotient  (= ra idiv rb)
2049   //         remainder (= ra irem rb)
2050 
2051   assert(ra != scratch && rb != scratch, "reg cannot be scratch");
2052 
2053   int idivq_offset = offset();
2054   if (! want_remainder) {
2055     sdiv(result, ra, rb);
2056   } else {
2057     sdiv(scratch, ra, rb);
2058     Assembler::msub(result, scratch, rb, ra);
2059   }
2060 
2061   return idivq_offset;
2062 }
2063 
2064 void MacroAssembler::membar(Membar_mask_bits order_constraint) {
2065   address prev = pc() - NativeMembar::instruction_size;
2066   address last = code()->last_insn();
2067   if (last != nullptr && nativeInstruction_at(last)->is_Membar() && prev == last) {
2068     NativeMembar *bar = NativeMembar_at(prev);
2069     // Don't promote DMB ST|DMB LD to DMB (a full barrier) because
2070     // doing so would introduce a StoreLoad which the caller did not
2071     // intend
2072     if (AlwaysMergeDMB || bar->get_kind() == order_constraint
2073         || bar->get_kind() == AnyAny
2074         || order_constraint == AnyAny) {
2075       // We are merging two memory barrier instructions.  On AArch64 we
2076       // can do this simply by ORing them together.
2077       bar->set_kind(bar->get_kind() | order_constraint);
2078       BLOCK_COMMENT("merged membar");
2079       return;
2080     }
2081   }
2082   code()->set_last_insn(pc());
2083   dmb(Assembler::barrier(order_constraint));
2084 }
2085 
2086 bool MacroAssembler::try_merge_ldst(Register rt, const Address &adr, size_t size_in_bytes, bool is_store) {
2087   if (ldst_can_merge(rt, adr, size_in_bytes, is_store)) {
2088     merge_ldst(rt, adr, size_in_bytes, is_store);
2089     code()->clear_last_insn();
2090     return true;
2091   } else {
2092     assert(size_in_bytes == 8 || size_in_bytes == 4, "only 8 bytes or 4 bytes load/store is supported.");
2093     const uint64_t mask = size_in_bytes - 1;
2094     if (adr.getMode() == Address::base_plus_offset &&
2095         (adr.offset() & mask) == 0) { // only supports base_plus_offset.
2096       code()->set_last_insn(pc());
2097     }
2098     return false;
2099   }
2100 }
2101 
2102 void MacroAssembler::ldr(Register Rx, const Address &adr) {
2103   // We always try to merge two adjacent loads into one ldp.
2104   if (!try_merge_ldst(Rx, adr, 8, false)) {
2105     Assembler::ldr(Rx, adr);
2106   }
2107 }
2108 
2109 void MacroAssembler::ldrw(Register Rw, const Address &adr) {
2110   // We always try to merge two adjacent loads into one ldp.
2111   if (!try_merge_ldst(Rw, adr, 4, false)) {
2112     Assembler::ldrw(Rw, adr);
2113   }
2114 }
2115 
2116 void MacroAssembler::str(Register Rx, const Address &adr) {
2117   // We always try to merge two adjacent stores into one stp.
2118   if (!try_merge_ldst(Rx, adr, 8, true)) {
2119     Assembler::str(Rx, adr);
2120   }
2121 }
2122 
2123 void MacroAssembler::strw(Register Rw, const Address &adr) {
2124   // We always try to merge two adjacent stores into one stp.
2125   if (!try_merge_ldst(Rw, adr, 4, true)) {
2126     Assembler::strw(Rw, adr);
2127   }
2128 }
2129 
2130 // MacroAssembler routines found actually to be needed
2131 
2132 void MacroAssembler::push(Register src)
2133 {
2134   str(src, Address(pre(esp, -1 * wordSize)));
2135 }
2136 
2137 void MacroAssembler::pop(Register dst)
2138 {
2139   ldr(dst, Address(post(esp, 1 * wordSize)));
2140 }
2141 
2142 // Note: load_unsigned_short used to be called load_unsigned_word.
2143 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
2144   int off = offset();
2145   ldrh(dst, src);
2146   return off;
2147 }
2148 
2149 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
2150   int off = offset();
2151   ldrb(dst, src);
2152   return off;
2153 }
2154 
2155 int MacroAssembler::load_signed_short(Register dst, Address src) {
2156   int off = offset();
2157   ldrsh(dst, src);
2158   return off;
2159 }
2160 
2161 int MacroAssembler::load_signed_byte(Register dst, Address src) {
2162   int off = offset();
2163   ldrsb(dst, src);
2164   return off;
2165 }
2166 
2167 int MacroAssembler::load_signed_short32(Register dst, Address src) {
2168   int off = offset();
2169   ldrshw(dst, src);
2170   return off;
2171 }
2172 
2173 int MacroAssembler::load_signed_byte32(Register dst, Address src) {
2174   int off = offset();
2175   ldrsbw(dst, src);
2176   return off;
2177 }
2178 
2179 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed) {
2180   switch (size_in_bytes) {
2181   case  8:  ldr(dst, src); break;
2182   case  4:  ldrw(dst, src); break;
2183   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
2184   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
2185   default:  ShouldNotReachHere();
2186   }
2187 }
2188 
2189 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes) {
2190   switch (size_in_bytes) {
2191   case  8:  str(src, dst); break;
2192   case  4:  strw(src, dst); break;
2193   case  2:  strh(src, dst); break;
2194   case  1:  strb(src, dst); break;
2195   default:  ShouldNotReachHere();
2196   }
2197 }
2198 
2199 void MacroAssembler::decrementw(Register reg, int value)
2200 {
2201   if (value < 0)  { incrementw(reg, -value);      return; }
2202   if (value == 0) {                               return; }
2203   if (value < (1 << 12)) { subw(reg, reg, value); return; }
2204   /* else */ {
2205     guarantee(reg != rscratch2, "invalid dst for register decrement");
2206     movw(rscratch2, (unsigned)value);
2207     subw(reg, reg, rscratch2);
2208   }
2209 }
2210 
2211 void MacroAssembler::decrement(Register reg, int value)
2212 {
2213   if (value < 0)  { increment(reg, -value);      return; }
2214   if (value == 0) {                              return; }
2215   if (value < (1 << 12)) { sub(reg, reg, value); return; }
2216   /* else */ {
2217     assert(reg != rscratch2, "invalid dst for register decrement");
2218     mov(rscratch2, (uint64_t)value);
2219     sub(reg, reg, rscratch2);
2220   }
2221 }
2222 
2223 void MacroAssembler::decrementw(Address dst, int value)
2224 {
2225   assert(!dst.uses(rscratch1), "invalid dst for address decrement");
2226   if (dst.getMode() == Address::literal) {
2227     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2228     lea(rscratch2, dst);
2229     dst = Address(rscratch2);
2230   }
2231   ldrw(rscratch1, dst);
2232   decrementw(rscratch1, value);
2233   strw(rscratch1, dst);
2234 }
2235 
2236 void MacroAssembler::decrement(Address dst, int value)
2237 {
2238   assert(!dst.uses(rscratch1), "invalid address for decrement");
2239   if (dst.getMode() == Address::literal) {
2240     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2241     lea(rscratch2, dst);
2242     dst = Address(rscratch2);
2243   }
2244   ldr(rscratch1, dst);
2245   decrement(rscratch1, value);
2246   str(rscratch1, dst);
2247 }
2248 
2249 void MacroAssembler::incrementw(Register reg, int value)
2250 {
2251   if (value < 0)  { decrementw(reg, -value);      return; }
2252   if (value == 0) {                               return; }
2253   if (value < (1 << 12)) { addw(reg, reg, value); return; }
2254   /* else */ {
2255     assert(reg != rscratch2, "invalid dst for register increment");
2256     movw(rscratch2, (unsigned)value);
2257     addw(reg, reg, rscratch2);
2258   }
2259 }
2260 
2261 void MacroAssembler::increment(Register reg, int value)
2262 {
2263   if (value < 0)  { decrement(reg, -value);      return; }
2264   if (value == 0) {                              return; }
2265   if (value < (1 << 12)) { add(reg, reg, value); return; }
2266   /* else */ {
2267     assert(reg != rscratch2, "invalid dst for register increment");
2268     movw(rscratch2, (unsigned)value);
2269     add(reg, reg, rscratch2);
2270   }
2271 }
2272 
2273 void MacroAssembler::incrementw(Address dst, int value)
2274 {
2275   assert(!dst.uses(rscratch1), "invalid dst for address increment");
2276   if (dst.getMode() == Address::literal) {
2277     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2278     lea(rscratch2, dst);
2279     dst = Address(rscratch2);
2280   }
2281   ldrw(rscratch1, dst);
2282   incrementw(rscratch1, value);
2283   strw(rscratch1, dst);
2284 }
2285 
2286 void MacroAssembler::increment(Address dst, int value)
2287 {
2288   assert(!dst.uses(rscratch1), "invalid dst for address increment");
2289   if (dst.getMode() == Address::literal) {
2290     assert(abs(value) < (1 << 12), "invalid value and address mode combination");
2291     lea(rscratch2, dst);
2292     dst = Address(rscratch2);
2293   }
2294   ldr(rscratch1, dst);
2295   increment(rscratch1, value);
2296   str(rscratch1, dst);
2297 }
2298 
2299 // Push lots of registers in the bit set supplied.  Don't push sp.
2300 // Return the number of words pushed
2301 int MacroAssembler::push(unsigned int bitset, Register stack) {
2302   int words_pushed = 0;
2303 
2304   // Scan bitset to accumulate register pairs
2305   unsigned char regs[32];
2306   int count = 0;
2307   for (int reg = 0; reg <= 30; reg++) {
2308     if (1 & bitset)
2309       regs[count++] = reg;
2310     bitset >>= 1;
2311   }
2312   regs[count++] = zr->raw_encoding();
2313   count &= ~1;  // Only push an even number of regs
2314 
2315   if (count) {
2316     stp(as_Register(regs[0]), as_Register(regs[1]),
2317        Address(pre(stack, -count * wordSize)));
2318     words_pushed += 2;
2319   }
2320   for (int i = 2; i < count; i += 2) {
2321     stp(as_Register(regs[i]), as_Register(regs[i+1]),
2322        Address(stack, i * wordSize));
2323     words_pushed += 2;
2324   }
2325 
2326   assert(words_pushed == count, "oops, pushed != count");
2327 
2328   return count;
2329 }
2330 
2331 int MacroAssembler::pop(unsigned int bitset, Register stack) {
2332   int words_pushed = 0;
2333 
2334   // Scan bitset to accumulate register pairs
2335   unsigned char regs[32];
2336   int count = 0;
2337   for (int reg = 0; reg <= 30; reg++) {
2338     if (1 & bitset)
2339       regs[count++] = reg;
2340     bitset >>= 1;
2341   }
2342   regs[count++] = zr->raw_encoding();
2343   count &= ~1;
2344 
2345   for (int i = 2; i < count; i += 2) {
2346     ldp(as_Register(regs[i]), as_Register(regs[i+1]),
2347        Address(stack, i * wordSize));
2348     words_pushed += 2;
2349   }
2350   if (count) {
2351     ldp(as_Register(regs[0]), as_Register(regs[1]),
2352        Address(post(stack, count * wordSize)));
2353     words_pushed += 2;
2354   }
2355 
2356   assert(words_pushed == count, "oops, pushed != count");
2357 
2358   return count;
2359 }
2360 
2361 // Push lots of registers in the bit set supplied.  Don't push sp.
2362 // Return the number of dwords pushed
2363 int MacroAssembler::push_fp(unsigned int bitset, Register stack) {
2364   int words_pushed = 0;
2365   bool use_sve = false;
2366   int sve_vector_size_in_bytes = 0;
2367 
2368 #ifdef COMPILER2
2369   use_sve = Matcher::supports_scalable_vector();
2370   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
2371 #endif
2372 
2373   // Scan bitset to accumulate register pairs
2374   unsigned char regs[32];
2375   int count = 0;
2376   for (int reg = 0; reg <= 31; reg++) {
2377     if (1 & bitset)
2378       regs[count++] = reg;
2379     bitset >>= 1;
2380   }
2381 
2382   if (count == 0) {
2383     return 0;
2384   }
2385 
2386   // SVE
2387   if (use_sve && sve_vector_size_in_bytes > 16) {
2388     sub(stack, stack, sve_vector_size_in_bytes * count);
2389     for (int i = 0; i < count; i++) {
2390       sve_str(as_FloatRegister(regs[i]), Address(stack, i));
2391     }
2392     return count * sve_vector_size_in_bytes / 8;
2393   }
2394 
2395   // NEON
2396   if (count == 1) {
2397     strq(as_FloatRegister(regs[0]), Address(pre(stack, -wordSize * 2)));
2398     return 2;
2399   }
2400 
2401   bool odd = (count & 1) == 1;
2402   int push_slots = count + (odd ? 1 : 0);
2403 
2404   // Always pushing full 128 bit registers.
2405   stpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(pre(stack, -push_slots * wordSize * 2)));
2406   words_pushed += 2;
2407 
2408   for (int i = 2; i + 1 < count; i += 2) {
2409     stpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
2410     words_pushed += 2;
2411   }
2412 
2413   if (odd) {
2414     strq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
2415     words_pushed++;
2416   }
2417 
2418   assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
2419   return count * 2;
2420 }
2421 
2422 // Return the number of dwords popped
2423 int MacroAssembler::pop_fp(unsigned int bitset, Register stack) {
2424   int words_pushed = 0;
2425   bool use_sve = false;
2426   int sve_vector_size_in_bytes = 0;
2427 
2428 #ifdef COMPILER2
2429   use_sve = Matcher::supports_scalable_vector();
2430   sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
2431 #endif
2432   // Scan bitset to accumulate register pairs
2433   unsigned char regs[32];
2434   int count = 0;
2435   for (int reg = 0; reg <= 31; reg++) {
2436     if (1 & bitset)
2437       regs[count++] = reg;
2438     bitset >>= 1;
2439   }
2440 
2441   if (count == 0) {
2442     return 0;
2443   }
2444 
2445   // SVE
2446   if (use_sve && sve_vector_size_in_bytes > 16) {
2447     for (int i = count - 1; i >= 0; i--) {
2448       sve_ldr(as_FloatRegister(regs[i]), Address(stack, i));
2449     }
2450     add(stack, stack, sve_vector_size_in_bytes * count);
2451     return count * sve_vector_size_in_bytes / 8;
2452   }
2453 
2454   // NEON
2455   if (count == 1) {
2456     ldrq(as_FloatRegister(regs[0]), Address(post(stack, wordSize * 2)));
2457     return 2;
2458   }
2459 
2460   bool odd = (count & 1) == 1;
2461   int push_slots = count + (odd ? 1 : 0);
2462 
2463   if (odd) {
2464     ldrq(as_FloatRegister(regs[count - 1]), Address(stack, (count - 1) * wordSize * 2));
2465     words_pushed++;
2466   }
2467 
2468   for (int i = 2; i + 1 < count; i += 2) {
2469     ldpq(as_FloatRegister(regs[i]), as_FloatRegister(regs[i+1]), Address(stack, i * wordSize * 2));
2470     words_pushed += 2;
2471   }
2472 
2473   ldpq(as_FloatRegister(regs[0]), as_FloatRegister(regs[1]), Address(post(stack, push_slots * wordSize * 2)));
2474   words_pushed += 2;
2475 
2476   assert(words_pushed == count, "oops, pushed(%d) != count(%d)", words_pushed, count);
2477 
2478   return count * 2;
2479 }
2480 
2481 // Return the number of dwords pushed
2482 int MacroAssembler::push_p(unsigned int bitset, Register stack) {
2483   bool use_sve = false;
2484   int sve_predicate_size_in_slots = 0;
2485 
2486 #ifdef COMPILER2
2487   use_sve = Matcher::supports_scalable_vector();
2488   if (use_sve) {
2489     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
2490   }
2491 #endif
2492 
2493   if (!use_sve) {
2494     return 0;
2495   }
2496 
2497   unsigned char regs[PRegister::number_of_registers];
2498   int count = 0;
2499   for (int reg = 0; reg < PRegister::number_of_registers; reg++) {
2500     if (1 & bitset)
2501       regs[count++] = reg;
2502     bitset >>= 1;
2503   }
2504 
2505   if (count == 0) {
2506     return 0;
2507   }
2508 
2509   int total_push_bytes = align_up(sve_predicate_size_in_slots *
2510                                   VMRegImpl::stack_slot_size * count, 16);
2511   sub(stack, stack, total_push_bytes);
2512   for (int i = 0; i < count; i++) {
2513     sve_str(as_PRegister(regs[i]), Address(stack, i));
2514   }
2515   return total_push_bytes / 8;
2516 }
2517 
2518 // Return the number of dwords popped
2519 int MacroAssembler::pop_p(unsigned int bitset, Register stack) {
2520   bool use_sve = false;
2521   int sve_predicate_size_in_slots = 0;
2522 
2523 #ifdef COMPILER2
2524   use_sve = Matcher::supports_scalable_vector();
2525   if (use_sve) {
2526     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
2527   }
2528 #endif
2529 
2530   if (!use_sve) {
2531     return 0;
2532   }
2533 
2534   unsigned char regs[PRegister::number_of_registers];
2535   int count = 0;
2536   for (int reg = 0; reg < PRegister::number_of_registers; reg++) {
2537     if (1 & bitset)
2538       regs[count++] = reg;
2539     bitset >>= 1;
2540   }
2541 
2542   if (count == 0) {
2543     return 0;
2544   }
2545 
2546   int total_pop_bytes = align_up(sve_predicate_size_in_slots *
2547                                  VMRegImpl::stack_slot_size * count, 16);
2548   for (int i = count - 1; i >= 0; i--) {
2549     sve_ldr(as_PRegister(regs[i]), Address(stack, i));
2550   }
2551   add(stack, stack, total_pop_bytes);
2552   return total_pop_bytes / 8;
2553 }
2554 
2555 #ifdef ASSERT
2556 void MacroAssembler::verify_heapbase(const char* msg) {
2557 #if 0
2558   assert (UseCompressedOops || UseCompressedClassPointers, "should be compressed");
2559   assert (Universe::heap() != nullptr, "java heap should be initialized");
2560   if (!UseCompressedOops || Universe::ptr_base() == nullptr) {
2561     // rheapbase is allocated as general register
2562     return;
2563   }
2564   if (CheckCompressedOops) {
2565     Label ok;
2566     push(1 << rscratch1->encoding(), sp); // cmpptr trashes rscratch1
2567     cmpptr(rheapbase, ExternalAddress(CompressedOops::ptrs_base_addr()));
2568     br(Assembler::EQ, ok);
2569     stop(msg);
2570     bind(ok);
2571     pop(1 << rscratch1->encoding(), sp);
2572   }
2573 #endif
2574 }
2575 #endif
2576 
2577 void MacroAssembler::resolve_jobject(Register value, Register tmp1, Register tmp2) {
2578   assert_different_registers(value, tmp1, tmp2);
2579   Label done, tagged, weak_tagged;
2580 
2581   cbz(value, done);           // Use null as-is.
2582   tst(value, JNIHandles::tag_mask); // Test for tag.
2583   br(Assembler::NE, tagged);
2584 
2585   // Resolve local handle
2586   access_load_at(T_OBJECT, IN_NATIVE | AS_RAW, value, Address(value, 0), tmp1, tmp2);
2587   verify_oop(value);
2588   b(done);
2589 
2590   bind(tagged);
2591   STATIC_ASSERT(JNIHandles::TypeTag::weak_global == 0b1);
2592   tbnz(value, 0, weak_tagged);    // Test for weak tag.
2593 
2594   // Resolve global handle
2595   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, -JNIHandles::TypeTag::global), tmp1, tmp2);
2596   verify_oop(value);
2597   b(done);
2598 
2599   bind(weak_tagged);
2600   // Resolve jweak.
2601   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
2602                  value, Address(value, -JNIHandles::TypeTag::weak_global), tmp1, tmp2);
2603   verify_oop(value);
2604 
2605   bind(done);
2606 }
2607 
2608 void MacroAssembler::resolve_global_jobject(Register value, Register tmp1, Register tmp2) {
2609   assert_different_registers(value, tmp1, tmp2);
2610   Label done;
2611 
2612   cbz(value, done);           // Use null as-is.
2613 
2614 #ifdef ASSERT
2615   {
2616     STATIC_ASSERT(JNIHandles::TypeTag::global == 0b10);
2617     Label valid_global_tag;
2618     tbnz(value, 1, valid_global_tag); // Test for global tag
2619     stop("non global jobject using resolve_global_jobject");
2620     bind(valid_global_tag);
2621   }
2622 #endif
2623 
2624   // Resolve global handle
2625   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, -JNIHandles::TypeTag::global), tmp1, tmp2);
2626   verify_oop(value);
2627 
2628   bind(done);
2629 }
2630 
2631 void MacroAssembler::stop(const char* msg) {
2632   BLOCK_COMMENT(msg);
2633   dcps1(0xdeae);
2634   emit_int64((uintptr_t)msg);
2635 }
2636 
2637 void MacroAssembler::unimplemented(const char* what) {
2638   const char* buf = nullptr;
2639   {
2640     ResourceMark rm;
2641     stringStream ss;
2642     ss.print("unimplemented: %s", what);
2643     buf = code_string(ss.as_string());
2644   }
2645   stop(buf);
2646 }
2647 
2648 void MacroAssembler::_assert_asm(Assembler::Condition cc, const char* msg) {
2649 #ifdef ASSERT
2650   Label OK;
2651   br(cc, OK);
2652   stop(msg);
2653   bind(OK);
2654 #endif
2655 }
2656 
2657 // If a constant does not fit in an immediate field, generate some
2658 // number of MOV instructions and then perform the operation.
2659 void MacroAssembler::wrap_add_sub_imm_insn(Register Rd, Register Rn, uint64_t imm,
2660                                            add_sub_imm_insn insn1,
2661                                            add_sub_reg_insn insn2,
2662                                            bool is32) {
2663   assert(Rd != zr, "Rd = zr and not setting flags?");
2664   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
2665   if (fits) {
2666     (this->*insn1)(Rd, Rn, imm);
2667   } else {
2668     if (uabs(imm) < (1 << 24)) {
2669        (this->*insn1)(Rd, Rn, imm & -(1 << 12));
2670        (this->*insn1)(Rd, Rd, imm & ((1 << 12)-1));
2671     } else {
2672        assert_different_registers(Rd, Rn);
2673        mov(Rd, imm);
2674        (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2675     }
2676   }
2677 }
2678 
2679 // Separate vsn which sets the flags. Optimisations are more restricted
2680 // because we must set the flags correctly.
2681 void MacroAssembler::wrap_adds_subs_imm_insn(Register Rd, Register Rn, uint64_t imm,
2682                                              add_sub_imm_insn insn1,
2683                                              add_sub_reg_insn insn2,
2684                                              bool is32) {
2685   bool fits = operand_valid_for_add_sub_immediate(is32 ? (int32_t)imm : imm);
2686   if (fits) {
2687     (this->*insn1)(Rd, Rn, imm);
2688   } else {
2689     assert_different_registers(Rd, Rn);
2690     assert(Rd != zr, "overflow in immediate operand");
2691     mov(Rd, imm);
2692     (this->*insn2)(Rd, Rn, Rd, LSL, 0);
2693   }
2694 }
2695 
2696 
2697 void MacroAssembler::add(Register Rd, Register Rn, RegisterOrConstant increment) {
2698   if (increment.is_register()) {
2699     add(Rd, Rn, increment.as_register());
2700   } else {
2701     add(Rd, Rn, increment.as_constant());
2702   }
2703 }
2704 
2705 void MacroAssembler::addw(Register Rd, Register Rn, RegisterOrConstant increment) {
2706   if (increment.is_register()) {
2707     addw(Rd, Rn, increment.as_register());
2708   } else {
2709     addw(Rd, Rn, increment.as_constant());
2710   }
2711 }
2712 
2713 void MacroAssembler::sub(Register Rd, Register Rn, RegisterOrConstant decrement) {
2714   if (decrement.is_register()) {
2715     sub(Rd, Rn, decrement.as_register());
2716   } else {
2717     sub(Rd, Rn, decrement.as_constant());
2718   }
2719 }
2720 
2721 void MacroAssembler::subw(Register Rd, Register Rn, RegisterOrConstant decrement) {
2722   if (decrement.is_register()) {
2723     subw(Rd, Rn, decrement.as_register());
2724   } else {
2725     subw(Rd, Rn, decrement.as_constant());
2726   }
2727 }
2728 
2729 void MacroAssembler::reinit_heapbase()
2730 {
2731   if (UseCompressedOops) {
2732     if (Universe::is_fully_initialized()) {
2733       mov(rheapbase, CompressedOops::ptrs_base());
2734     } else {
2735       lea(rheapbase, ExternalAddress(CompressedOops::ptrs_base_addr()));
2736       ldr(rheapbase, Address(rheapbase));
2737     }
2738   }
2739 }
2740 
2741 // this simulates the behaviour of the x86 cmpxchg instruction using a
2742 // load linked/store conditional pair. we use the acquire/release
2743 // versions of these instructions so that we flush pending writes as
2744 // per Java semantics.
2745 
2746 // n.b the x86 version assumes the old value to be compared against is
2747 // in rax and updates rax with the value located in memory if the
2748 // cmpxchg fails. we supply a register for the old value explicitly
2749 
2750 // the aarch64 load linked/store conditional instructions do not
2751 // accept an offset. so, unlike x86, we must provide a plain register
2752 // to identify the memory word to be compared/exchanged rather than a
2753 // register+offset Address.
2754 
2755 void MacroAssembler::cmpxchgptr(Register oldv, Register newv, Register addr, Register tmp,
2756                                 Label &succeed, Label *fail) {
2757   // oldv holds comparison value
2758   // newv holds value to write in exchange
2759   // addr identifies memory word to compare against/update
2760   if (UseLSE) {
2761     mov(tmp, oldv);
2762     casal(Assembler::xword, oldv, newv, addr);
2763     cmp(tmp, oldv);
2764     br(Assembler::EQ, succeed);
2765     membar(AnyAny);
2766   } else {
2767     Label retry_load, nope;
2768     prfm(Address(addr), PSTL1STRM);
2769     bind(retry_load);
2770     // flush and load exclusive from the memory location
2771     // and fail if it is not what we expect
2772     ldaxr(tmp, addr);
2773     cmp(tmp, oldv);
2774     br(Assembler::NE, nope);
2775     // if we store+flush with no intervening write tmp will be zero
2776     stlxr(tmp, newv, addr);
2777     cbzw(tmp, succeed);
2778     // retry so we only ever return after a load fails to compare
2779     // ensures we don't return a stale value after a failed write.
2780     b(retry_load);
2781     // if the memory word differs we return it in oldv and signal a fail
2782     bind(nope);
2783     membar(AnyAny);
2784     mov(oldv, tmp);
2785   }
2786   if (fail)
2787     b(*fail);
2788 }
2789 
2790 void MacroAssembler::cmpxchg_obj_header(Register oldv, Register newv, Register obj, Register tmp,
2791                                         Label &succeed, Label *fail) {
2792   assert(oopDesc::mark_offset_in_bytes() == 0, "assumption");
2793   cmpxchgptr(oldv, newv, obj, tmp, succeed, fail);
2794 }
2795 
2796 void MacroAssembler::cmpxchgw(Register oldv, Register newv, Register addr, Register tmp,
2797                                 Label &succeed, Label *fail) {
2798   // oldv holds comparison value
2799   // newv holds value to write in exchange
2800   // addr identifies memory word to compare against/update
2801   // tmp returns 0/1 for success/failure
2802   if (UseLSE) {
2803     mov(tmp, oldv);
2804     casal(Assembler::word, oldv, newv, addr);
2805     cmp(tmp, oldv);
2806     br(Assembler::EQ, succeed);
2807     membar(AnyAny);
2808   } else {
2809     Label retry_load, nope;
2810     prfm(Address(addr), PSTL1STRM);
2811     bind(retry_load);
2812     // flush and load exclusive from the memory location
2813     // and fail if it is not what we expect
2814     ldaxrw(tmp, addr);
2815     cmp(tmp, oldv);
2816     br(Assembler::NE, nope);
2817     // if we store+flush with no intervening write tmp will be zero
2818     stlxrw(tmp, newv, addr);
2819     cbzw(tmp, succeed);
2820     // retry so we only ever return after a load fails to compare
2821     // ensures we don't return a stale value after a failed write.
2822     b(retry_load);
2823     // if the memory word differs we return it in oldv and signal a fail
2824     bind(nope);
2825     membar(AnyAny);
2826     mov(oldv, tmp);
2827   }
2828   if (fail)
2829     b(*fail);
2830 }
2831 
2832 // A generic CAS; success or failure is in the EQ flag.  A weak CAS
2833 // doesn't retry and may fail spuriously.  If the oldval is wanted,
2834 // Pass a register for the result, otherwise pass noreg.
2835 
2836 // Clobbers rscratch1
2837 void MacroAssembler::cmpxchg(Register addr, Register expected,
2838                              Register new_val,
2839                              enum operand_size size,
2840                              bool acquire, bool release,
2841                              bool weak,
2842                              Register result) {
2843   if (result == noreg)  result = rscratch1;
2844   BLOCK_COMMENT("cmpxchg {");
2845   if (UseLSE) {
2846     mov(result, expected);
2847     lse_cas(result, new_val, addr, size, acquire, release, /*not_pair*/ true);
2848     compare_eq(result, expected, size);
2849 #ifdef ASSERT
2850     // Poison rscratch1 which is written on !UseLSE branch
2851     mov(rscratch1, 0x1f1f1f1f1f1f1f1f);
2852 #endif
2853   } else {
2854     Label retry_load, done;
2855     prfm(Address(addr), PSTL1STRM);
2856     bind(retry_load);
2857     load_exclusive(result, addr, size, acquire);
2858     compare_eq(result, expected, size);
2859     br(Assembler::NE, done);
2860     store_exclusive(rscratch1, new_val, addr, size, release);
2861     if (weak) {
2862       cmpw(rscratch1, 0u);  // If the store fails, return NE to our caller.
2863     } else {
2864       cbnzw(rscratch1, retry_load);
2865     }
2866     bind(done);
2867   }
2868   BLOCK_COMMENT("} cmpxchg");
2869 }
2870 
2871 // A generic comparison. Only compares for equality, clobbers rscratch1.
2872 void MacroAssembler::compare_eq(Register rm, Register rn, enum operand_size size) {
2873   if (size == xword) {
2874     cmp(rm, rn);
2875   } else if (size == word) {
2876     cmpw(rm, rn);
2877   } else if (size == halfword) {
2878     eorw(rscratch1, rm, rn);
2879     ands(zr, rscratch1, 0xffff);
2880   } else if (size == byte) {
2881     eorw(rscratch1, rm, rn);
2882     ands(zr, rscratch1, 0xff);
2883   } else {
2884     ShouldNotReachHere();
2885   }
2886 }
2887 
2888 
2889 static bool different(Register a, RegisterOrConstant b, Register c) {
2890   if (b.is_constant())
2891     return a != c;
2892   else
2893     return a != b.as_register() && a != c && b.as_register() != c;
2894 }
2895 
2896 #define ATOMIC_OP(NAME, LDXR, OP, IOP, AOP, STXR, sz)                   \
2897 void MacroAssembler::atomic_##NAME(Register prev, RegisterOrConstant incr, Register addr) { \
2898   if (UseLSE) {                                                         \
2899     prev = prev->is_valid() ? prev : zr;                                \
2900     if (incr.is_register()) {                                           \
2901       AOP(sz, incr.as_register(), prev, addr);                          \
2902     } else {                                                            \
2903       mov(rscratch2, incr.as_constant());                               \
2904       AOP(sz, rscratch2, prev, addr);                                   \
2905     }                                                                   \
2906     return;                                                             \
2907   }                                                                     \
2908   Register result = rscratch2;                                          \
2909   if (prev->is_valid())                                                 \
2910     result = different(prev, incr, addr) ? prev : rscratch2;            \
2911                                                                         \
2912   Label retry_load;                                                     \
2913   prfm(Address(addr), PSTL1STRM);                                       \
2914   bind(retry_load);                                                     \
2915   LDXR(result, addr);                                                   \
2916   OP(rscratch1, result, incr);                                          \
2917   STXR(rscratch2, rscratch1, addr);                                     \
2918   cbnzw(rscratch2, retry_load);                                         \
2919   if (prev->is_valid() && prev != result) {                             \
2920     IOP(prev, rscratch1, incr);                                         \
2921   }                                                                     \
2922 }
2923 
2924 ATOMIC_OP(add, ldxr, add, sub, ldadd, stxr, Assembler::xword)
2925 ATOMIC_OP(addw, ldxrw, addw, subw, ldadd, stxrw, Assembler::word)
2926 ATOMIC_OP(addal, ldaxr, add, sub, ldaddal, stlxr, Assembler::xword)
2927 ATOMIC_OP(addalw, ldaxrw, addw, subw, ldaddal, stlxrw, Assembler::word)
2928 
2929 #undef ATOMIC_OP
2930 
2931 #define ATOMIC_XCHG(OP, AOP, LDXR, STXR, sz)                            \
2932 void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \
2933   if (UseLSE) {                                                         \
2934     prev = prev->is_valid() ? prev : zr;                                \
2935     AOP(sz, newv, prev, addr);                                          \
2936     return;                                                             \
2937   }                                                                     \
2938   Register result = rscratch2;                                          \
2939   if (prev->is_valid())                                                 \
2940     result = different(prev, newv, addr) ? prev : rscratch2;            \
2941                                                                         \
2942   Label retry_load;                                                     \
2943   prfm(Address(addr), PSTL1STRM);                                       \
2944   bind(retry_load);                                                     \
2945   LDXR(result, addr);                                                   \
2946   STXR(rscratch1, newv, addr);                                          \
2947   cbnzw(rscratch1, retry_load);                                         \
2948   if (prev->is_valid() && prev != result)                               \
2949     mov(prev, result);                                                  \
2950 }
2951 
2952 ATOMIC_XCHG(xchg, swp, ldxr, stxr, Assembler::xword)
2953 ATOMIC_XCHG(xchgw, swp, ldxrw, stxrw, Assembler::word)
2954 ATOMIC_XCHG(xchgl, swpl, ldxr, stlxr, Assembler::xword)
2955 ATOMIC_XCHG(xchglw, swpl, ldxrw, stlxrw, Assembler::word)
2956 ATOMIC_XCHG(xchgal, swpal, ldaxr, stlxr, Assembler::xword)
2957 ATOMIC_XCHG(xchgalw, swpal, ldaxrw, stlxrw, Assembler::word)
2958 
2959 #undef ATOMIC_XCHG
2960 
2961 #ifndef PRODUCT
2962 extern "C" void findpc(intptr_t x);
2963 #endif
2964 
2965 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[])
2966 {
2967   // In order to get locks to work, we need to fake a in_VM state
2968   if (ShowMessageBoxOnError ) {
2969     JavaThread* thread = JavaThread::current();
2970     JavaThreadState saved_state = thread->thread_state();
2971     thread->set_thread_state(_thread_in_vm);
2972 #ifndef PRODUCT
2973     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
2974       ttyLocker ttyl;
2975       BytecodeCounter::print();
2976     }
2977 #endif
2978     if (os::message_box(msg, "Execution stopped, print registers?")) {
2979       ttyLocker ttyl;
2980       tty->print_cr(" pc = 0x%016" PRIx64, pc);
2981 #ifndef PRODUCT
2982       tty->cr();
2983       findpc(pc);
2984       tty->cr();
2985 #endif
2986       tty->print_cr(" r0 = 0x%016" PRIx64, regs[0]);
2987       tty->print_cr(" r1 = 0x%016" PRIx64, regs[1]);
2988       tty->print_cr(" r2 = 0x%016" PRIx64, regs[2]);
2989       tty->print_cr(" r3 = 0x%016" PRIx64, regs[3]);
2990       tty->print_cr(" r4 = 0x%016" PRIx64, regs[4]);
2991       tty->print_cr(" r5 = 0x%016" PRIx64, regs[5]);
2992       tty->print_cr(" r6 = 0x%016" PRIx64, regs[6]);
2993       tty->print_cr(" r7 = 0x%016" PRIx64, regs[7]);
2994       tty->print_cr(" r8 = 0x%016" PRIx64, regs[8]);
2995       tty->print_cr(" r9 = 0x%016" PRIx64, regs[9]);
2996       tty->print_cr("r10 = 0x%016" PRIx64, regs[10]);
2997       tty->print_cr("r11 = 0x%016" PRIx64, regs[11]);
2998       tty->print_cr("r12 = 0x%016" PRIx64, regs[12]);
2999       tty->print_cr("r13 = 0x%016" PRIx64, regs[13]);
3000       tty->print_cr("r14 = 0x%016" PRIx64, regs[14]);
3001       tty->print_cr("r15 = 0x%016" PRIx64, regs[15]);
3002       tty->print_cr("r16 = 0x%016" PRIx64, regs[16]);
3003       tty->print_cr("r17 = 0x%016" PRIx64, regs[17]);
3004       tty->print_cr("r18 = 0x%016" PRIx64, regs[18]);
3005       tty->print_cr("r19 = 0x%016" PRIx64, regs[19]);
3006       tty->print_cr("r20 = 0x%016" PRIx64, regs[20]);
3007       tty->print_cr("r21 = 0x%016" PRIx64, regs[21]);
3008       tty->print_cr("r22 = 0x%016" PRIx64, regs[22]);
3009       tty->print_cr("r23 = 0x%016" PRIx64, regs[23]);
3010       tty->print_cr("r24 = 0x%016" PRIx64, regs[24]);
3011       tty->print_cr("r25 = 0x%016" PRIx64, regs[25]);
3012       tty->print_cr("r26 = 0x%016" PRIx64, regs[26]);
3013       tty->print_cr("r27 = 0x%016" PRIx64, regs[27]);
3014       tty->print_cr("r28 = 0x%016" PRIx64, regs[28]);
3015       tty->print_cr("r30 = 0x%016" PRIx64, regs[30]);
3016       tty->print_cr("r31 = 0x%016" PRIx64, regs[31]);
3017       BREAKPOINT;
3018     }
3019   }
3020   fatal("DEBUG MESSAGE: %s", msg);
3021 }
3022 
3023 RegSet MacroAssembler::call_clobbered_gp_registers() {
3024   RegSet regs = RegSet::range(r0, r17) - RegSet::of(rscratch1, rscratch2);
3025 #ifndef R18_RESERVED
3026   regs += r18_tls;
3027 #endif
3028   return regs;
3029 }
3030 
3031 void MacroAssembler::push_call_clobbered_registers_except(RegSet exclude) {
3032   int step = 4 * wordSize;
3033   push(call_clobbered_gp_registers() - exclude, sp);
3034   sub(sp, sp, step);
3035   mov(rscratch1, -step);
3036   // Push v0-v7, v16-v31.
3037   for (int i = 31; i>= 4; i -= 4) {
3038     if (i <= v7->encoding() || i >= v16->encoding())
3039       st1(as_FloatRegister(i-3), as_FloatRegister(i-2), as_FloatRegister(i-1),
3040           as_FloatRegister(i), T1D, Address(post(sp, rscratch1)));
3041   }
3042   st1(as_FloatRegister(0), as_FloatRegister(1), as_FloatRegister(2),
3043       as_FloatRegister(3), T1D, Address(sp));
3044 }
3045 
3046 void MacroAssembler::pop_call_clobbered_registers_except(RegSet exclude) {
3047   for (int i = 0; i < 32; i += 4) {
3048     if (i <= v7->encoding() || i >= v16->encoding())
3049       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3050           as_FloatRegister(i+3), T1D, Address(post(sp, 4 * wordSize)));
3051   }
3052 
3053   reinitialize_ptrue();
3054 
3055   pop(call_clobbered_gp_registers() - exclude, sp);
3056 }
3057 
3058 void MacroAssembler::push_CPU_state(bool save_vectors, bool use_sve,
3059                                     int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
3060   push(RegSet::range(r0, r29), sp); // integer registers except lr & sp
3061   if (save_vectors && use_sve && sve_vector_size_in_bytes > 16) {
3062     sub(sp, sp, sve_vector_size_in_bytes * FloatRegister::number_of_registers);
3063     for (int i = 0; i < FloatRegister::number_of_registers; i++) {
3064       sve_str(as_FloatRegister(i), Address(sp, i));
3065     }
3066   } else {
3067     int step = (save_vectors ? 8 : 4) * wordSize;
3068     mov(rscratch1, -step);
3069     sub(sp, sp, step);
3070     for (int i = 28; i >= 4; i -= 4) {
3071       st1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3072           as_FloatRegister(i+3), save_vectors ? T2D : T1D, Address(post(sp, rscratch1)));
3073     }
3074     st1(v0, v1, v2, v3, save_vectors ? T2D : T1D, sp);
3075   }
3076   if (save_vectors && use_sve && total_predicate_in_bytes > 0) {
3077     sub(sp, sp, total_predicate_in_bytes);
3078     for (int i = 0; i < PRegister::number_of_registers; i++) {
3079       sve_str(as_PRegister(i), Address(sp, i));
3080     }
3081   }
3082 }
3083 
3084 void MacroAssembler::pop_CPU_state(bool restore_vectors, bool use_sve,
3085                                    int sve_vector_size_in_bytes, int total_predicate_in_bytes) {
3086   if (restore_vectors && use_sve && total_predicate_in_bytes > 0) {
3087     for (int i = PRegister::number_of_registers - 1; i >= 0; i--) {
3088       sve_ldr(as_PRegister(i), Address(sp, i));
3089     }
3090     add(sp, sp, total_predicate_in_bytes);
3091   }
3092   if (restore_vectors && use_sve && sve_vector_size_in_bytes > 16) {
3093     for (int i = FloatRegister::number_of_registers - 1; i >= 0; i--) {
3094       sve_ldr(as_FloatRegister(i), Address(sp, i));
3095     }
3096     add(sp, sp, sve_vector_size_in_bytes * FloatRegister::number_of_registers);
3097   } else {
3098     int step = (restore_vectors ? 8 : 4) * wordSize;
3099     for (int i = 0; i <= 28; i += 4)
3100       ld1(as_FloatRegister(i), as_FloatRegister(i+1), as_FloatRegister(i+2),
3101           as_FloatRegister(i+3), restore_vectors ? T2D : T1D, Address(post(sp, step)));
3102   }
3103 
3104   // We may use predicate registers and rely on ptrue with SVE,
3105   // regardless of wide vector (> 8 bytes) used or not.
3106   if (use_sve) {
3107     reinitialize_ptrue();
3108   }
3109 
3110   // integer registers except lr & sp
3111   pop(RegSet::range(r0, r17), sp);
3112 #ifdef R18_RESERVED
3113   ldp(zr, r19, Address(post(sp, 2 * wordSize)));
3114   pop(RegSet::range(r20, r29), sp);
3115 #else
3116   pop(RegSet::range(r18_tls, r29), sp);
3117 #endif
3118 }
3119 
3120 /**
3121  * Helpers for multiply_to_len().
3122  */
3123 void MacroAssembler::add2_with_carry(Register final_dest_hi, Register dest_hi, Register dest_lo,
3124                                      Register src1, Register src2) {
3125   adds(dest_lo, dest_lo, src1);
3126   adc(dest_hi, dest_hi, zr);
3127   adds(dest_lo, dest_lo, src2);
3128   adc(final_dest_hi, dest_hi, zr);
3129 }
3130 
3131 // Generate an address from (r + r1 extend offset).  "size" is the
3132 // size of the operand.  The result may be in rscratch2.
3133 Address MacroAssembler::offsetted_address(Register r, Register r1,
3134                                           Address::extend ext, int offset, int size) {
3135   if (offset || (ext.shift() % size != 0)) {
3136     lea(rscratch2, Address(r, r1, ext));
3137     return Address(rscratch2, offset);
3138   } else {
3139     return Address(r, r1, ext);
3140   }
3141 }
3142 
3143 Address MacroAssembler::spill_address(int size, int offset, Register tmp)
3144 {
3145   assert(offset >= 0, "spill to negative address?");
3146   // Offset reachable ?
3147   //   Not aligned - 9 bits signed offset
3148   //   Aligned - 12 bits unsigned offset shifted
3149   Register base = sp;
3150   if ((offset & (size-1)) && offset >= (1<<8)) {
3151     add(tmp, base, offset & ((1<<12)-1));
3152     base = tmp;
3153     offset &= -1u<<12;
3154   }
3155 
3156   if (offset >= (1<<12) * size) {
3157     add(tmp, base, offset & (((1<<12)-1)<<12));
3158     base = tmp;
3159     offset &= ~(((1<<12)-1)<<12);
3160   }
3161 
3162   return Address(base, offset);
3163 }
3164 
3165 Address MacroAssembler::sve_spill_address(int sve_reg_size_in_bytes, int offset, Register tmp) {
3166   assert(offset >= 0, "spill to negative address?");
3167 
3168   Register base = sp;
3169 
3170   // An immediate offset in the range 0 to 255 which is multiplied
3171   // by the current vector or predicate register size in bytes.
3172   if (offset % sve_reg_size_in_bytes == 0 && offset < ((1<<8)*sve_reg_size_in_bytes)) {
3173     return Address(base, offset / sve_reg_size_in_bytes);
3174   }
3175 
3176   add(tmp, base, offset);
3177   return Address(tmp);
3178 }
3179 
3180 // Checks whether offset is aligned.
3181 // Returns true if it is, else false.
3182 bool MacroAssembler::merge_alignment_check(Register base,
3183                                            size_t size,
3184                                            int64_t cur_offset,
3185                                            int64_t prev_offset) const {
3186   if (AvoidUnalignedAccesses) {
3187     if (base == sp) {
3188       // Checks whether low offset if aligned to pair of registers.
3189       int64_t pair_mask = size * 2 - 1;
3190       int64_t offset = prev_offset > cur_offset ? cur_offset : prev_offset;
3191       return (offset & pair_mask) == 0;
3192     } else { // If base is not sp, we can't guarantee the access is aligned.
3193       return false;
3194     }
3195   } else {
3196     int64_t mask = size - 1;
3197     // Load/store pair instruction only supports element size aligned offset.
3198     return (cur_offset & mask) == 0 && (prev_offset & mask) == 0;
3199   }
3200 }
3201 
3202 // Checks whether current and previous loads/stores can be merged.
3203 // Returns true if it can be merged, else false.
3204 bool MacroAssembler::ldst_can_merge(Register rt,
3205                                     const Address &adr,
3206                                     size_t cur_size_in_bytes,
3207                                     bool is_store) const {
3208   address prev = pc() - NativeInstruction::instruction_size;
3209   address last = code()->last_insn();
3210 
3211   if (last == nullptr || !nativeInstruction_at(last)->is_Imm_LdSt()) {
3212     return false;
3213   }
3214 
3215   if (adr.getMode() != Address::base_plus_offset || prev != last) {
3216     return false;
3217   }
3218 
3219   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
3220   size_t prev_size_in_bytes = prev_ldst->size_in_bytes();
3221 
3222   assert(prev_size_in_bytes == 4 || prev_size_in_bytes == 8, "only supports 64/32bit merging.");
3223   assert(cur_size_in_bytes == 4 || cur_size_in_bytes == 8, "only supports 64/32bit merging.");
3224 
3225   if (cur_size_in_bytes != prev_size_in_bytes || is_store != prev_ldst->is_store()) {
3226     return false;
3227   }
3228 
3229   int64_t max_offset = 63 * prev_size_in_bytes;
3230   int64_t min_offset = -64 * prev_size_in_bytes;
3231 
3232   assert(prev_ldst->is_not_pre_post_index(), "pre-index or post-index is not supported to be merged.");
3233 
3234   // Only same base can be merged.
3235   if (adr.base() != prev_ldst->base()) {
3236     return false;
3237   }
3238 
3239   int64_t cur_offset = adr.offset();
3240   int64_t prev_offset = prev_ldst->offset();
3241   size_t diff = abs(cur_offset - prev_offset);
3242   if (diff != prev_size_in_bytes) {
3243     return false;
3244   }
3245 
3246   // Following cases can not be merged:
3247   // ldr x2, [x2, #8]
3248   // ldr x3, [x2, #16]
3249   // or:
3250   // ldr x2, [x3, #8]
3251   // ldr x2, [x3, #16]
3252   // If t1 and t2 is the same in "ldp t1, t2, [xn, #imm]", we'll get SIGILL.
3253   if (!is_store && (adr.base() == prev_ldst->target() || rt == prev_ldst->target())) {
3254     return false;
3255   }
3256 
3257   int64_t low_offset = prev_offset > cur_offset ? cur_offset : prev_offset;
3258   // Offset range must be in ldp/stp instruction's range.
3259   if (low_offset > max_offset || low_offset < min_offset) {
3260     return false;
3261   }
3262 
3263   if (merge_alignment_check(adr.base(), prev_size_in_bytes, cur_offset, prev_offset)) {
3264     return true;
3265   }
3266 
3267   return false;
3268 }
3269 
3270 // Merge current load/store with previous load/store into ldp/stp.
3271 void MacroAssembler::merge_ldst(Register rt,
3272                                 const Address &adr,
3273                                 size_t cur_size_in_bytes,
3274                                 bool is_store) {
3275 
3276   assert(ldst_can_merge(rt, adr, cur_size_in_bytes, is_store) == true, "cur and prev must be able to be merged.");
3277 
3278   Register rt_low, rt_high;
3279   address prev = pc() - NativeInstruction::instruction_size;
3280   NativeLdSt* prev_ldst = NativeLdSt_at(prev);
3281 
3282   int64_t offset;
3283 
3284   if (adr.offset() < prev_ldst->offset()) {
3285     offset = adr.offset();
3286     rt_low = rt;
3287     rt_high = prev_ldst->target();
3288   } else {
3289     offset = prev_ldst->offset();
3290     rt_low = prev_ldst->target();
3291     rt_high = rt;
3292   }
3293 
3294   Address adr_p = Address(prev_ldst->base(), offset);
3295   // Overwrite previous generated binary.
3296   code_section()->set_end(prev);
3297 
3298   const size_t sz = prev_ldst->size_in_bytes();
3299   assert(sz == 8 || sz == 4, "only supports 64/32bit merging.");
3300   if (!is_store) {
3301     BLOCK_COMMENT("merged ldr pair");
3302     if (sz == 8) {
3303       ldp(rt_low, rt_high, adr_p);
3304     } else {
3305       ldpw(rt_low, rt_high, adr_p);
3306     }
3307   } else {
3308     BLOCK_COMMENT("merged str pair");
3309     if (sz == 8) {
3310       stp(rt_low, rt_high, adr_p);
3311     } else {
3312       stpw(rt_low, rt_high, adr_p);
3313     }
3314   }
3315 }
3316 
3317 /**
3318  * Multiply 64 bit by 64 bit first loop.
3319  */
3320 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
3321                                            Register y, Register y_idx, Register z,
3322                                            Register carry, Register product,
3323                                            Register idx, Register kdx) {
3324   //
3325   //  jlong carry, x[], y[], z[];
3326   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
3327   //    huge_128 product = y[idx] * x[xstart] + carry;
3328   //    z[kdx] = (jlong)product;
3329   //    carry  = (jlong)(product >>> 64);
3330   //  }
3331   //  z[xstart] = carry;
3332   //
3333 
3334   Label L_first_loop, L_first_loop_exit;
3335   Label L_one_x, L_one_y, L_multiply;
3336 
3337   subsw(xstart, xstart, 1);
3338   br(Assembler::MI, L_one_x);
3339 
3340   lea(rscratch1, Address(x, xstart, Address::lsl(LogBytesPerInt)));
3341   ldr(x_xstart, Address(rscratch1));
3342   ror(x_xstart, x_xstart, 32); // convert big-endian to little-endian
3343 
3344   bind(L_first_loop);
3345   subsw(idx, idx, 1);
3346   br(Assembler::MI, L_first_loop_exit);
3347   subsw(idx, idx, 1);
3348   br(Assembler::MI, L_one_y);
3349   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
3350   ldr(y_idx, Address(rscratch1));
3351   ror(y_idx, y_idx, 32); // convert big-endian to little-endian
3352   bind(L_multiply);
3353 
3354   // AArch64 has a multiply-accumulate instruction that we can't use
3355   // here because it has no way to process carries, so we have to use
3356   // separate add and adc instructions.  Bah.
3357   umulh(rscratch1, x_xstart, y_idx); // x_xstart * y_idx -> rscratch1:product
3358   mul(product, x_xstart, y_idx);
3359   adds(product, product, carry);
3360   adc(carry, rscratch1, zr);   // x_xstart * y_idx + carry -> carry:product
3361 
3362   subw(kdx, kdx, 2);
3363   ror(product, product, 32); // back to big-endian
3364   str(product, offsetted_address(z, kdx, Address::uxtw(LogBytesPerInt), 0, BytesPerLong));
3365 
3366   b(L_first_loop);
3367 
3368   bind(L_one_y);
3369   ldrw(y_idx, Address(y,  0));
3370   b(L_multiply);
3371 
3372   bind(L_one_x);
3373   ldrw(x_xstart, Address(x,  0));
3374   b(L_first_loop);
3375 
3376   bind(L_first_loop_exit);
3377 }
3378 
3379 /**
3380  * Multiply 128 bit by 128. Unrolled inner loop.
3381  *
3382  */
3383 void MacroAssembler::multiply_128_x_128_loop(Register y, Register z,
3384                                              Register carry, Register carry2,
3385                                              Register idx, Register jdx,
3386                                              Register yz_idx1, Register yz_idx2,
3387                                              Register tmp, Register tmp3, Register tmp4,
3388                                              Register tmp6, Register product_hi) {
3389 
3390   //   jlong carry, x[], y[], z[];
3391   //   int kdx = ystart+1;
3392   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
3393   //     huge_128 tmp3 = (y[idx+1] * product_hi) + z[kdx+idx+1] + carry;
3394   //     jlong carry2  = (jlong)(tmp3 >>> 64);
3395   //     huge_128 tmp4 = (y[idx]   * product_hi) + z[kdx+idx] + carry2;
3396   //     carry  = (jlong)(tmp4 >>> 64);
3397   //     z[kdx+idx+1] = (jlong)tmp3;
3398   //     z[kdx+idx] = (jlong)tmp4;
3399   //   }
3400   //   idx += 2;
3401   //   if (idx > 0) {
3402   //     yz_idx1 = (y[idx] * product_hi) + z[kdx+idx] + carry;
3403   //     z[kdx+idx] = (jlong)yz_idx1;
3404   //     carry  = (jlong)(yz_idx1 >>> 64);
3405   //   }
3406   //
3407 
3408   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
3409 
3410   lsrw(jdx, idx, 2);
3411 
3412   bind(L_third_loop);
3413 
3414   subsw(jdx, jdx, 1);
3415   br(Assembler::MI, L_third_loop_exit);
3416   subw(idx, idx, 4);
3417 
3418   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
3419 
3420   ldp(yz_idx2, yz_idx1, Address(rscratch1, 0));
3421 
3422   lea(tmp6, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3423 
3424   ror(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
3425   ror(yz_idx2, yz_idx2, 32);
3426 
3427   ldp(rscratch2, rscratch1, Address(tmp6, 0));
3428 
3429   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
3430   umulh(tmp4, product_hi, yz_idx1);
3431 
3432   ror(rscratch1, rscratch1, 32); // convert big-endian to little-endian
3433   ror(rscratch2, rscratch2, 32);
3434 
3435   mul(tmp, product_hi, yz_idx2);   //  yz_idx2 * product_hi -> carry2:tmp
3436   umulh(carry2, product_hi, yz_idx2);
3437 
3438   // propagate sum of both multiplications into carry:tmp4:tmp3
3439   adds(tmp3, tmp3, carry);
3440   adc(tmp4, tmp4, zr);
3441   adds(tmp3, tmp3, rscratch1);
3442   adcs(tmp4, tmp4, tmp);
3443   adc(carry, carry2, zr);
3444   adds(tmp4, tmp4, rscratch2);
3445   adc(carry, carry, zr);
3446 
3447   ror(tmp3, tmp3, 32); // convert little-endian to big-endian
3448   ror(tmp4, tmp4, 32);
3449   stp(tmp4, tmp3, Address(tmp6, 0));
3450 
3451   b(L_third_loop);
3452   bind (L_third_loop_exit);
3453 
3454   andw (idx, idx, 0x3);
3455   cbz(idx, L_post_third_loop_done);
3456 
3457   Label L_check_1;
3458   subsw(idx, idx, 2);
3459   br(Assembler::MI, L_check_1);
3460 
3461   lea(rscratch1, Address(y, idx, Address::uxtw(LogBytesPerInt)));
3462   ldr(yz_idx1, Address(rscratch1, 0));
3463   ror(yz_idx1, yz_idx1, 32);
3464   mul(tmp3, product_hi, yz_idx1);  //  yz_idx1 * product_hi -> tmp4:tmp3
3465   umulh(tmp4, product_hi, yz_idx1);
3466   lea(rscratch1, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3467   ldr(yz_idx2, Address(rscratch1, 0));
3468   ror(yz_idx2, yz_idx2, 32);
3469 
3470   add2_with_carry(carry, tmp4, tmp3, carry, yz_idx2);
3471 
3472   ror(tmp3, tmp3, 32);
3473   str(tmp3, Address(rscratch1, 0));
3474 
3475   bind (L_check_1);
3476 
3477   andw (idx, idx, 0x1);
3478   subsw(idx, idx, 1);
3479   br(Assembler::MI, L_post_third_loop_done);
3480   ldrw(tmp4, Address(y, idx, Address::uxtw(LogBytesPerInt)));
3481   mul(tmp3, tmp4, product_hi);  //  tmp4 * product_hi -> carry2:tmp3
3482   umulh(carry2, tmp4, product_hi);
3483   ldrw(tmp4, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3484 
3485   add2_with_carry(carry2, tmp3, tmp4, carry);
3486 
3487   strw(tmp3, Address(z, idx, Address::uxtw(LogBytesPerInt)));
3488   extr(carry, carry2, tmp3, 32);
3489 
3490   bind(L_post_third_loop_done);
3491 }
3492 
3493 /**
3494  * Code for BigInteger::multiplyToLen() intrinsic.
3495  *
3496  * r0: x
3497  * r1: xlen
3498  * r2: y
3499  * r3: ylen
3500  * r4:  z
3501  * r5: zlen
3502  * r10: tmp1
3503  * r11: tmp2
3504  * r12: tmp3
3505  * r13: tmp4
3506  * r14: tmp5
3507  * r15: tmp6
3508  * r16: tmp7
3509  *
3510  */
3511 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen,
3512                                      Register z, Register zlen,
3513                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4,
3514                                      Register tmp5, Register tmp6, Register product_hi) {
3515 
3516   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6);
3517 
3518   const Register idx = tmp1;
3519   const Register kdx = tmp2;
3520   const Register xstart = tmp3;
3521 
3522   const Register y_idx = tmp4;
3523   const Register carry = tmp5;
3524   const Register product  = xlen;
3525   const Register x_xstart = zlen;  // reuse register
3526 
3527   // First Loop.
3528   //
3529   //  final static long LONG_MASK = 0xffffffffL;
3530   //  int xstart = xlen - 1;
3531   //  int ystart = ylen - 1;
3532   //  long carry = 0;
3533   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
3534   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
3535   //    z[kdx] = (int)product;
3536   //    carry = product >>> 32;
3537   //  }
3538   //  z[xstart] = (int)carry;
3539   //
3540 
3541   movw(idx, ylen);      // idx = ylen;
3542   movw(kdx, zlen);      // kdx = xlen+ylen;
3543   mov(carry, zr);       // carry = 0;
3544 
3545   Label L_done;
3546 
3547   movw(xstart, xlen);
3548   subsw(xstart, xstart, 1);
3549   br(Assembler::MI, L_done);
3550 
3551   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
3552 
3553   Label L_second_loop;
3554   cbzw(kdx, L_second_loop);
3555 
3556   Label L_carry;
3557   subw(kdx, kdx, 1);
3558   cbzw(kdx, L_carry);
3559 
3560   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
3561   lsr(carry, carry, 32);
3562   subw(kdx, kdx, 1);
3563 
3564   bind(L_carry);
3565   strw(carry, Address(z, kdx, Address::uxtw(LogBytesPerInt)));
3566 
3567   // Second and third (nested) loops.
3568   //
3569   // for (int i = xstart-1; i >= 0; i--) { // Second loop
3570   //   carry = 0;
3571   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
3572   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
3573   //                    (z[k] & LONG_MASK) + carry;
3574   //     z[k] = (int)product;
3575   //     carry = product >>> 32;
3576   //   }
3577   //   z[i] = (int)carry;
3578   // }
3579   //
3580   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = product_hi
3581 
3582   const Register jdx = tmp1;
3583 
3584   bind(L_second_loop);
3585   mov(carry, zr);                // carry = 0;
3586   movw(jdx, ylen);               // j = ystart+1
3587 
3588   subsw(xstart, xstart, 1);      // i = xstart-1;
3589   br(Assembler::MI, L_done);
3590 
3591   str(z, Address(pre(sp, -4 * wordSize)));
3592 
3593   Label L_last_x;
3594   lea(z, offsetted_address(z, xstart, Address::uxtw(LogBytesPerInt), 4, BytesPerInt)); // z = z + k - j
3595   subsw(xstart, xstart, 1);       // i = xstart-1;
3596   br(Assembler::MI, L_last_x);
3597 
3598   lea(rscratch1, Address(x, xstart, Address::uxtw(LogBytesPerInt)));
3599   ldr(product_hi, Address(rscratch1));
3600   ror(product_hi, product_hi, 32);  // convert big-endian to little-endian
3601 
3602   Label L_third_loop_prologue;
3603   bind(L_third_loop_prologue);
3604 
3605   str(ylen, Address(sp, wordSize));
3606   stp(x, xstart, Address(sp, 2 * wordSize));
3607   multiply_128_x_128_loop(y, z, carry, x, jdx, ylen, product,
3608                           tmp2, x_xstart, tmp3, tmp4, tmp6, product_hi);
3609   ldp(z, ylen, Address(post(sp, 2 * wordSize)));
3610   ldp(x, xlen, Address(post(sp, 2 * wordSize)));   // copy old xstart -> xlen
3611 
3612   addw(tmp3, xlen, 1);
3613   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
3614   subsw(tmp3, tmp3, 1);
3615   br(Assembler::MI, L_done);
3616 
3617   lsr(carry, carry, 32);
3618   strw(carry, Address(z, tmp3, Address::uxtw(LogBytesPerInt)));
3619   b(L_second_loop);
3620 
3621   // Next infrequent code is moved outside loops.
3622   bind(L_last_x);
3623   ldrw(product_hi, Address(x,  0));
3624   b(L_third_loop_prologue);
3625 
3626   bind(L_done);
3627 }
3628 
3629 // Code for BigInteger::mulAdd intrinsic
3630 // out     = r0
3631 // in      = r1
3632 // offset  = r2  (already out.length-offset)
3633 // len     = r3
3634 // k       = r4
3635 //
3636 // pseudo code from java implementation:
3637 // carry = 0;
3638 // offset = out.length-offset - 1;
3639 // for (int j=len-1; j >= 0; j--) {
3640 //     product = (in[j] & LONG_MASK) * kLong + (out[offset] & LONG_MASK) + carry;
3641 //     out[offset--] = (int)product;
3642 //     carry = product >>> 32;
3643 // }
3644 // return (int)carry;
3645 void MacroAssembler::mul_add(Register out, Register in, Register offset,
3646       Register len, Register k) {
3647     Label LOOP, END;
3648     // pre-loop
3649     cmp(len, zr); // cmp, not cbz/cbnz: to use condition twice => less branches
3650     csel(out, zr, out, Assembler::EQ);
3651     br(Assembler::EQ, END);
3652     add(in, in, len, LSL, 2); // in[j+1] address
3653     add(offset, out, offset, LSL, 2); // out[offset + 1] address
3654     mov(out, zr); // used to keep carry now
3655     BIND(LOOP);
3656     ldrw(rscratch1, Address(pre(in, -4)));
3657     madd(rscratch1, rscratch1, k, out);
3658     ldrw(rscratch2, Address(pre(offset, -4)));
3659     add(rscratch1, rscratch1, rscratch2);
3660     strw(rscratch1, Address(offset));
3661     lsr(out, rscratch1, 32);
3662     subs(len, len, 1);
3663     br(Assembler::NE, LOOP);
3664     BIND(END);
3665 }
3666 
3667 /**
3668  * Emits code to update CRC-32 with a byte value according to constants in table
3669  *
3670  * @param [in,out]crc   Register containing the crc.
3671  * @param [in]val       Register containing the byte to fold into the CRC.
3672  * @param [in]table     Register containing the table of crc constants.
3673  *
3674  * uint32_t crc;
3675  * val = crc_table[(val ^ crc) & 0xFF];
3676  * crc = val ^ (crc >> 8);
3677  *
3678  */
3679 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
3680   eor(val, val, crc);
3681   andr(val, val, 0xff);
3682   ldrw(val, Address(table, val, Address::lsl(2)));
3683   eor(crc, val, crc, Assembler::LSR, 8);
3684 }
3685 
3686 /**
3687  * Emits code to update CRC-32 with a 32-bit value according to tables 0 to 3
3688  *
3689  * @param [in,out]crc   Register containing the crc.
3690  * @param [in]v         Register containing the 32-bit to fold into the CRC.
3691  * @param [in]table0    Register containing table 0 of crc constants.
3692  * @param [in]table1    Register containing table 1 of crc constants.
3693  * @param [in]table2    Register containing table 2 of crc constants.
3694  * @param [in]table3    Register containing table 3 of crc constants.
3695  *
3696  * uint32_t crc;
3697  *   v = crc ^ v
3698  *   crc = table3[v&0xff]^table2[(v>>8)&0xff]^table1[(v>>16)&0xff]^table0[v>>24]
3699  *
3700  */
3701 void MacroAssembler::update_word_crc32(Register crc, Register v, Register tmp,
3702         Register table0, Register table1, Register table2, Register table3,
3703         bool upper) {
3704   eor(v, crc, v, upper ? LSR:LSL, upper ? 32:0);
3705   uxtb(tmp, v);
3706   ldrw(crc, Address(table3, tmp, Address::lsl(2)));
3707   ubfx(tmp, v, 8, 8);
3708   ldrw(tmp, Address(table2, tmp, Address::lsl(2)));
3709   eor(crc, crc, tmp);
3710   ubfx(tmp, v, 16, 8);
3711   ldrw(tmp, Address(table1, tmp, Address::lsl(2)));
3712   eor(crc, crc, tmp);
3713   ubfx(tmp, v, 24, 8);
3714   ldrw(tmp, Address(table0, tmp, Address::lsl(2)));
3715   eor(crc, crc, tmp);
3716 }
3717 
3718 void MacroAssembler::kernel_crc32_using_crypto_pmull(Register crc, Register buf,
3719         Register len, Register tmp0, Register tmp1, Register tmp2, Register tmp3) {
3720     Label CRC_by4_loop, CRC_by1_loop, CRC_less128, CRC_by128_pre, CRC_by32_loop, CRC_less32, L_exit;
3721     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
3722 
3723     subs(tmp0, len, 384);
3724     mvnw(crc, crc);
3725     br(Assembler::GE, CRC_by128_pre);
3726   BIND(CRC_less128);
3727     subs(len, len, 32);
3728     br(Assembler::GE, CRC_by32_loop);
3729   BIND(CRC_less32);
3730     adds(len, len, 32 - 4);
3731     br(Assembler::GE, CRC_by4_loop);
3732     adds(len, len, 4);
3733     br(Assembler::GT, CRC_by1_loop);
3734     b(L_exit);
3735 
3736   BIND(CRC_by32_loop);
3737     ldp(tmp0, tmp1, Address(buf));
3738     crc32x(crc, crc, tmp0);
3739     ldp(tmp2, tmp3, Address(buf, 16));
3740     crc32x(crc, crc, tmp1);
3741     add(buf, buf, 32);
3742     crc32x(crc, crc, tmp2);
3743     subs(len, len, 32);
3744     crc32x(crc, crc, tmp3);
3745     br(Assembler::GE, CRC_by32_loop);
3746     cmn(len, (u1)32);
3747     br(Assembler::NE, CRC_less32);
3748     b(L_exit);
3749 
3750   BIND(CRC_by4_loop);
3751     ldrw(tmp0, Address(post(buf, 4)));
3752     subs(len, len, 4);
3753     crc32w(crc, crc, tmp0);
3754     br(Assembler::GE, CRC_by4_loop);
3755     adds(len, len, 4);
3756     br(Assembler::LE, L_exit);
3757   BIND(CRC_by1_loop);
3758     ldrb(tmp0, Address(post(buf, 1)));
3759     subs(len, len, 1);
3760     crc32b(crc, crc, tmp0);
3761     br(Assembler::GT, CRC_by1_loop);
3762     b(L_exit);
3763 
3764   BIND(CRC_by128_pre);
3765     kernel_crc32_common_fold_using_crypto_pmull(crc, buf, len, tmp0, tmp1, tmp2,
3766       4*256*sizeof(juint) + 8*sizeof(juint));
3767     mov(crc, 0);
3768     crc32x(crc, crc, tmp0);
3769     crc32x(crc, crc, tmp1);
3770 
3771     cbnz(len, CRC_less128);
3772 
3773   BIND(L_exit);
3774     mvnw(crc, crc);
3775 }
3776 
3777 void MacroAssembler::kernel_crc32_using_crc32(Register crc, Register buf,
3778         Register len, Register tmp0, Register tmp1, Register tmp2,
3779         Register tmp3) {
3780     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
3781     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
3782 
3783     mvnw(crc, crc);
3784 
3785     subs(len, len, 128);
3786     br(Assembler::GE, CRC_by64_pre);
3787   BIND(CRC_less64);
3788     adds(len, len, 128-32);
3789     br(Assembler::GE, CRC_by32_loop);
3790   BIND(CRC_less32);
3791     adds(len, len, 32-4);
3792     br(Assembler::GE, CRC_by4_loop);
3793     adds(len, len, 4);
3794     br(Assembler::GT, CRC_by1_loop);
3795     b(L_exit);
3796 
3797   BIND(CRC_by32_loop);
3798     ldp(tmp0, tmp1, Address(post(buf, 16)));
3799     subs(len, len, 32);
3800     crc32x(crc, crc, tmp0);
3801     ldr(tmp2, Address(post(buf, 8)));
3802     crc32x(crc, crc, tmp1);
3803     ldr(tmp3, Address(post(buf, 8)));
3804     crc32x(crc, crc, tmp2);
3805     crc32x(crc, crc, tmp3);
3806     br(Assembler::GE, CRC_by32_loop);
3807     cmn(len, (u1)32);
3808     br(Assembler::NE, CRC_less32);
3809     b(L_exit);
3810 
3811   BIND(CRC_by4_loop);
3812     ldrw(tmp0, Address(post(buf, 4)));
3813     subs(len, len, 4);
3814     crc32w(crc, crc, tmp0);
3815     br(Assembler::GE, CRC_by4_loop);
3816     adds(len, len, 4);
3817     br(Assembler::LE, L_exit);
3818   BIND(CRC_by1_loop);
3819     ldrb(tmp0, Address(post(buf, 1)));
3820     subs(len, len, 1);
3821     crc32b(crc, crc, tmp0);
3822     br(Assembler::GT, CRC_by1_loop);
3823     b(L_exit);
3824 
3825   BIND(CRC_by64_pre);
3826     sub(buf, buf, 8);
3827     ldp(tmp0, tmp1, Address(buf, 8));
3828     crc32x(crc, crc, tmp0);
3829     ldr(tmp2, Address(buf, 24));
3830     crc32x(crc, crc, tmp1);
3831     ldr(tmp3, Address(buf, 32));
3832     crc32x(crc, crc, tmp2);
3833     ldr(tmp0, Address(buf, 40));
3834     crc32x(crc, crc, tmp3);
3835     ldr(tmp1, Address(buf, 48));
3836     crc32x(crc, crc, tmp0);
3837     ldr(tmp2, Address(buf, 56));
3838     crc32x(crc, crc, tmp1);
3839     ldr(tmp3, Address(pre(buf, 64)));
3840 
3841     b(CRC_by64_loop);
3842 
3843     align(CodeEntryAlignment);
3844   BIND(CRC_by64_loop);
3845     subs(len, len, 64);
3846     crc32x(crc, crc, tmp2);
3847     ldr(tmp0, Address(buf, 8));
3848     crc32x(crc, crc, tmp3);
3849     ldr(tmp1, Address(buf, 16));
3850     crc32x(crc, crc, tmp0);
3851     ldr(tmp2, Address(buf, 24));
3852     crc32x(crc, crc, tmp1);
3853     ldr(tmp3, Address(buf, 32));
3854     crc32x(crc, crc, tmp2);
3855     ldr(tmp0, Address(buf, 40));
3856     crc32x(crc, crc, tmp3);
3857     ldr(tmp1, Address(buf, 48));
3858     crc32x(crc, crc, tmp0);
3859     ldr(tmp2, Address(buf, 56));
3860     crc32x(crc, crc, tmp1);
3861     ldr(tmp3, Address(pre(buf, 64)));
3862     br(Assembler::GE, CRC_by64_loop);
3863 
3864     // post-loop
3865     crc32x(crc, crc, tmp2);
3866     crc32x(crc, crc, tmp3);
3867 
3868     sub(len, len, 64);
3869     add(buf, buf, 8);
3870     cmn(len, (u1)128);
3871     br(Assembler::NE, CRC_less64);
3872   BIND(L_exit);
3873     mvnw(crc, crc);
3874 }
3875 
3876 /**
3877  * @param crc   register containing existing CRC (32-bit)
3878  * @param buf   register pointing to input byte buffer (byte*)
3879  * @param len   register containing number of bytes
3880  * @param table register that will contain address of CRC table
3881  * @param tmp   scratch register
3882  */
3883 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len,
3884         Register table0, Register table1, Register table2, Register table3,
3885         Register tmp, Register tmp2, Register tmp3) {
3886   Label L_by16, L_by16_loop, L_by4, L_by4_loop, L_by1, L_by1_loop, L_exit;
3887 
3888   if (UseCryptoPmullForCRC32) {
3889       kernel_crc32_using_crypto_pmull(crc, buf, len, table0, table1, table2, table3);
3890       return;
3891   }
3892 
3893   if (UseCRC32) {
3894       kernel_crc32_using_crc32(crc, buf, len, table0, table1, table2, table3);
3895       return;
3896   }
3897 
3898     mvnw(crc, crc);
3899 
3900     {
3901       uint64_t offset;
3902       adrp(table0, ExternalAddress(StubRoutines::crc_table_addr()), offset);
3903       add(table0, table0, offset);
3904     }
3905     add(table1, table0, 1*256*sizeof(juint));
3906     add(table2, table0, 2*256*sizeof(juint));
3907     add(table3, table0, 3*256*sizeof(juint));
3908 
3909   if (UseNeon) {
3910       cmp(len, (u1)64);
3911       br(Assembler::LT, L_by16);
3912       eor(v16, T16B, v16, v16);
3913 
3914     Label L_fold;
3915 
3916       add(tmp, table0, 4*256*sizeof(juint)); // Point at the Neon constants
3917 
3918       ld1(v0, v1, T2D, post(buf, 32));
3919       ld1r(v4, T2D, post(tmp, 8));
3920       ld1r(v5, T2D, post(tmp, 8));
3921       ld1r(v6, T2D, post(tmp, 8));
3922       ld1r(v7, T2D, post(tmp, 8));
3923       mov(v16, S, 0, crc);
3924 
3925       eor(v0, T16B, v0, v16);
3926       sub(len, len, 64);
3927 
3928     BIND(L_fold);
3929       pmull(v22, T8H, v0, v5, T8B);
3930       pmull(v20, T8H, v0, v7, T8B);
3931       pmull(v23, T8H, v0, v4, T8B);
3932       pmull(v21, T8H, v0, v6, T8B);
3933 
3934       pmull2(v18, T8H, v0, v5, T16B);
3935       pmull2(v16, T8H, v0, v7, T16B);
3936       pmull2(v19, T8H, v0, v4, T16B);
3937       pmull2(v17, T8H, v0, v6, T16B);
3938 
3939       uzp1(v24, T8H, v20, v22);
3940       uzp2(v25, T8H, v20, v22);
3941       eor(v20, T16B, v24, v25);
3942 
3943       uzp1(v26, T8H, v16, v18);
3944       uzp2(v27, T8H, v16, v18);
3945       eor(v16, T16B, v26, v27);
3946 
3947       ushll2(v22, T4S, v20, T8H, 8);
3948       ushll(v20, T4S, v20, T4H, 8);
3949 
3950       ushll2(v18, T4S, v16, T8H, 8);
3951       ushll(v16, T4S, v16, T4H, 8);
3952 
3953       eor(v22, T16B, v23, v22);
3954       eor(v18, T16B, v19, v18);
3955       eor(v20, T16B, v21, v20);
3956       eor(v16, T16B, v17, v16);
3957 
3958       uzp1(v17, T2D, v16, v20);
3959       uzp2(v21, T2D, v16, v20);
3960       eor(v17, T16B, v17, v21);
3961 
3962       ushll2(v20, T2D, v17, T4S, 16);
3963       ushll(v16, T2D, v17, T2S, 16);
3964 
3965       eor(v20, T16B, v20, v22);
3966       eor(v16, T16B, v16, v18);
3967 
3968       uzp1(v17, T2D, v20, v16);
3969       uzp2(v21, T2D, v20, v16);
3970       eor(v28, T16B, v17, v21);
3971 
3972       pmull(v22, T8H, v1, v5, T8B);
3973       pmull(v20, T8H, v1, v7, T8B);
3974       pmull(v23, T8H, v1, v4, T8B);
3975       pmull(v21, T8H, v1, v6, T8B);
3976 
3977       pmull2(v18, T8H, v1, v5, T16B);
3978       pmull2(v16, T8H, v1, v7, T16B);
3979       pmull2(v19, T8H, v1, v4, T16B);
3980       pmull2(v17, T8H, v1, v6, T16B);
3981 
3982       ld1(v0, v1, T2D, post(buf, 32));
3983 
3984       uzp1(v24, T8H, v20, v22);
3985       uzp2(v25, T8H, v20, v22);
3986       eor(v20, T16B, v24, v25);
3987 
3988       uzp1(v26, T8H, v16, v18);
3989       uzp2(v27, T8H, v16, v18);
3990       eor(v16, T16B, v26, v27);
3991 
3992       ushll2(v22, T4S, v20, T8H, 8);
3993       ushll(v20, T4S, v20, T4H, 8);
3994 
3995       ushll2(v18, T4S, v16, T8H, 8);
3996       ushll(v16, T4S, v16, T4H, 8);
3997 
3998       eor(v22, T16B, v23, v22);
3999       eor(v18, T16B, v19, v18);
4000       eor(v20, T16B, v21, v20);
4001       eor(v16, T16B, v17, v16);
4002 
4003       uzp1(v17, T2D, v16, v20);
4004       uzp2(v21, T2D, v16, v20);
4005       eor(v16, T16B, v17, v21);
4006 
4007       ushll2(v20, T2D, v16, T4S, 16);
4008       ushll(v16, T2D, v16, T2S, 16);
4009 
4010       eor(v20, T16B, v22, v20);
4011       eor(v16, T16B, v16, v18);
4012 
4013       uzp1(v17, T2D, v20, v16);
4014       uzp2(v21, T2D, v20, v16);
4015       eor(v20, T16B, v17, v21);
4016 
4017       shl(v16, T2D, v28, 1);
4018       shl(v17, T2D, v20, 1);
4019 
4020       eor(v0, T16B, v0, v16);
4021       eor(v1, T16B, v1, v17);
4022 
4023       subs(len, len, 32);
4024       br(Assembler::GE, L_fold);
4025 
4026       mov(crc, 0);
4027       mov(tmp, v0, D, 0);
4028       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4029       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4030       mov(tmp, v0, D, 1);
4031       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4032       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4033       mov(tmp, v1, D, 0);
4034       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4035       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4036       mov(tmp, v1, D, 1);
4037       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4038       update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4039 
4040       add(len, len, 32);
4041   }
4042 
4043   BIND(L_by16);
4044     subs(len, len, 16);
4045     br(Assembler::GE, L_by16_loop);
4046     adds(len, len, 16-4);
4047     br(Assembler::GE, L_by4_loop);
4048     adds(len, len, 4);
4049     br(Assembler::GT, L_by1_loop);
4050     b(L_exit);
4051 
4052   BIND(L_by4_loop);
4053     ldrw(tmp, Address(post(buf, 4)));
4054     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3);
4055     subs(len, len, 4);
4056     br(Assembler::GE, L_by4_loop);
4057     adds(len, len, 4);
4058     br(Assembler::LE, L_exit);
4059   BIND(L_by1_loop);
4060     subs(len, len, 1);
4061     ldrb(tmp, Address(post(buf, 1)));
4062     update_byte_crc32(crc, tmp, table0);
4063     br(Assembler::GT, L_by1_loop);
4064     b(L_exit);
4065 
4066     align(CodeEntryAlignment);
4067   BIND(L_by16_loop);
4068     subs(len, len, 16);
4069     ldp(tmp, tmp3, Address(post(buf, 16)));
4070     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, false);
4071     update_word_crc32(crc, tmp, tmp2, table0, table1, table2, table3, true);
4072     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, false);
4073     update_word_crc32(crc, tmp3, tmp2, table0, table1, table2, table3, true);
4074     br(Assembler::GE, L_by16_loop);
4075     adds(len, len, 16-4);
4076     br(Assembler::GE, L_by4_loop);
4077     adds(len, len, 4);
4078     br(Assembler::GT, L_by1_loop);
4079   BIND(L_exit);
4080     mvnw(crc, crc);
4081 }
4082 
4083 void MacroAssembler::kernel_crc32c_using_crypto_pmull(Register crc, Register buf,
4084         Register len, Register tmp0, Register tmp1, Register tmp2, Register tmp3) {
4085     Label CRC_by4_loop, CRC_by1_loop, CRC_less128, CRC_by128_pre, CRC_by32_loop, CRC_less32, L_exit;
4086     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
4087 
4088     subs(tmp0, len, 384);
4089     br(Assembler::GE, CRC_by128_pre);
4090   BIND(CRC_less128);
4091     subs(len, len, 32);
4092     br(Assembler::GE, CRC_by32_loop);
4093   BIND(CRC_less32);
4094     adds(len, len, 32 - 4);
4095     br(Assembler::GE, CRC_by4_loop);
4096     adds(len, len, 4);
4097     br(Assembler::GT, CRC_by1_loop);
4098     b(L_exit);
4099 
4100   BIND(CRC_by32_loop);
4101     ldp(tmp0, tmp1, Address(buf));
4102     crc32cx(crc, crc, tmp0);
4103     ldr(tmp2, Address(buf, 16));
4104     crc32cx(crc, crc, tmp1);
4105     ldr(tmp3, Address(buf, 24));
4106     crc32cx(crc, crc, tmp2);
4107     add(buf, buf, 32);
4108     subs(len, len, 32);
4109     crc32cx(crc, crc, tmp3);
4110     br(Assembler::GE, CRC_by32_loop);
4111     cmn(len, (u1)32);
4112     br(Assembler::NE, CRC_less32);
4113     b(L_exit);
4114 
4115   BIND(CRC_by4_loop);
4116     ldrw(tmp0, Address(post(buf, 4)));
4117     subs(len, len, 4);
4118     crc32cw(crc, crc, tmp0);
4119     br(Assembler::GE, CRC_by4_loop);
4120     adds(len, len, 4);
4121     br(Assembler::LE, L_exit);
4122   BIND(CRC_by1_loop);
4123     ldrb(tmp0, Address(post(buf, 1)));
4124     subs(len, len, 1);
4125     crc32cb(crc, crc, tmp0);
4126     br(Assembler::GT, CRC_by1_loop);
4127     b(L_exit);
4128 
4129   BIND(CRC_by128_pre);
4130     kernel_crc32_common_fold_using_crypto_pmull(crc, buf, len, tmp0, tmp1, tmp2,
4131       4*256*sizeof(juint) + 8*sizeof(juint) + 0x50);
4132     mov(crc, 0);
4133     crc32cx(crc, crc, tmp0);
4134     crc32cx(crc, crc, tmp1);
4135 
4136     cbnz(len, CRC_less128);
4137 
4138   BIND(L_exit);
4139 }
4140 
4141 void MacroAssembler::kernel_crc32c_using_crc32c(Register crc, Register buf,
4142         Register len, Register tmp0, Register tmp1, Register tmp2,
4143         Register tmp3) {
4144     Label CRC_by64_loop, CRC_by4_loop, CRC_by1_loop, CRC_less64, CRC_by64_pre, CRC_by32_loop, CRC_less32, L_exit;
4145     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2, tmp3);
4146 
4147     subs(len, len, 128);
4148     br(Assembler::GE, CRC_by64_pre);
4149   BIND(CRC_less64);
4150     adds(len, len, 128-32);
4151     br(Assembler::GE, CRC_by32_loop);
4152   BIND(CRC_less32);
4153     adds(len, len, 32-4);
4154     br(Assembler::GE, CRC_by4_loop);
4155     adds(len, len, 4);
4156     br(Assembler::GT, CRC_by1_loop);
4157     b(L_exit);
4158 
4159   BIND(CRC_by32_loop);
4160     ldp(tmp0, tmp1, Address(post(buf, 16)));
4161     subs(len, len, 32);
4162     crc32cx(crc, crc, tmp0);
4163     ldr(tmp2, Address(post(buf, 8)));
4164     crc32cx(crc, crc, tmp1);
4165     ldr(tmp3, Address(post(buf, 8)));
4166     crc32cx(crc, crc, tmp2);
4167     crc32cx(crc, crc, tmp3);
4168     br(Assembler::GE, CRC_by32_loop);
4169     cmn(len, (u1)32);
4170     br(Assembler::NE, CRC_less32);
4171     b(L_exit);
4172 
4173   BIND(CRC_by4_loop);
4174     ldrw(tmp0, Address(post(buf, 4)));
4175     subs(len, len, 4);
4176     crc32cw(crc, crc, tmp0);
4177     br(Assembler::GE, CRC_by4_loop);
4178     adds(len, len, 4);
4179     br(Assembler::LE, L_exit);
4180   BIND(CRC_by1_loop);
4181     ldrb(tmp0, Address(post(buf, 1)));
4182     subs(len, len, 1);
4183     crc32cb(crc, crc, tmp0);
4184     br(Assembler::GT, CRC_by1_loop);
4185     b(L_exit);
4186 
4187   BIND(CRC_by64_pre);
4188     sub(buf, buf, 8);
4189     ldp(tmp0, tmp1, Address(buf, 8));
4190     crc32cx(crc, crc, tmp0);
4191     ldr(tmp2, Address(buf, 24));
4192     crc32cx(crc, crc, tmp1);
4193     ldr(tmp3, Address(buf, 32));
4194     crc32cx(crc, crc, tmp2);
4195     ldr(tmp0, Address(buf, 40));
4196     crc32cx(crc, crc, tmp3);
4197     ldr(tmp1, Address(buf, 48));
4198     crc32cx(crc, crc, tmp0);
4199     ldr(tmp2, Address(buf, 56));
4200     crc32cx(crc, crc, tmp1);
4201     ldr(tmp3, Address(pre(buf, 64)));
4202 
4203     b(CRC_by64_loop);
4204 
4205     align(CodeEntryAlignment);
4206   BIND(CRC_by64_loop);
4207     subs(len, len, 64);
4208     crc32cx(crc, crc, tmp2);
4209     ldr(tmp0, Address(buf, 8));
4210     crc32cx(crc, crc, tmp3);
4211     ldr(tmp1, Address(buf, 16));
4212     crc32cx(crc, crc, tmp0);
4213     ldr(tmp2, Address(buf, 24));
4214     crc32cx(crc, crc, tmp1);
4215     ldr(tmp3, Address(buf, 32));
4216     crc32cx(crc, crc, tmp2);
4217     ldr(tmp0, Address(buf, 40));
4218     crc32cx(crc, crc, tmp3);
4219     ldr(tmp1, Address(buf, 48));
4220     crc32cx(crc, crc, tmp0);
4221     ldr(tmp2, Address(buf, 56));
4222     crc32cx(crc, crc, tmp1);
4223     ldr(tmp3, Address(pre(buf, 64)));
4224     br(Assembler::GE, CRC_by64_loop);
4225 
4226     // post-loop
4227     crc32cx(crc, crc, tmp2);
4228     crc32cx(crc, crc, tmp3);
4229 
4230     sub(len, len, 64);
4231     add(buf, buf, 8);
4232     cmn(len, (u1)128);
4233     br(Assembler::NE, CRC_less64);
4234   BIND(L_exit);
4235 }
4236 
4237 /**
4238  * @param crc   register containing existing CRC (32-bit)
4239  * @param buf   register pointing to input byte buffer (byte*)
4240  * @param len   register containing number of bytes
4241  * @param table register that will contain address of CRC table
4242  * @param tmp   scratch register
4243  */
4244 void MacroAssembler::kernel_crc32c(Register crc, Register buf, Register len,
4245         Register table0, Register table1, Register table2, Register table3,
4246         Register tmp, Register tmp2, Register tmp3) {
4247   if (UseCryptoPmullForCRC32) {
4248     kernel_crc32c_using_crypto_pmull(crc, buf, len, table0, table1, table2, table3);
4249   } else {
4250     kernel_crc32c_using_crc32c(crc, buf, len, table0, table1, table2, table3);
4251   }
4252 }
4253 
4254 void MacroAssembler::kernel_crc32_common_fold_using_crypto_pmull(Register crc, Register buf,
4255         Register len, Register tmp0, Register tmp1, Register tmp2, size_t table_offset) {
4256     Label CRC_by128_loop;
4257     assert_different_registers(crc, buf, len, tmp0, tmp1, tmp2);
4258 
4259     sub(len, len, 256);
4260     Register table = tmp0;
4261     {
4262       uint64_t offset;
4263       adrp(table, ExternalAddress(StubRoutines::crc_table_addr()), offset);
4264       add(table, table, offset);
4265     }
4266     add(table, table, table_offset);
4267 
4268     // Registers v0..v7 are used as data registers.
4269     // Registers v16..v31 are used as tmp registers.
4270     sub(buf, buf, 0x10);
4271     ldrq(v0, Address(buf, 0x10));
4272     ldrq(v1, Address(buf, 0x20));
4273     ldrq(v2, Address(buf, 0x30));
4274     ldrq(v3, Address(buf, 0x40));
4275     ldrq(v4, Address(buf, 0x50));
4276     ldrq(v5, Address(buf, 0x60));
4277     ldrq(v6, Address(buf, 0x70));
4278     ldrq(v7, Address(pre(buf, 0x80)));
4279 
4280     movi(v31, T4S, 0);
4281     mov(v31, S, 0, crc);
4282     eor(v0, T16B, v0, v31);
4283 
4284     // Register v16 contains constants from the crc table.
4285     ldrq(v16, Address(table));
4286     b(CRC_by128_loop);
4287 
4288     align(OptoLoopAlignment);
4289   BIND(CRC_by128_loop);
4290     pmull (v17,  T1Q, v0, v16, T1D);
4291     pmull2(v18, T1Q, v0, v16, T2D);
4292     ldrq(v0, Address(buf, 0x10));
4293     eor3(v0, T16B, v17,  v18, v0);
4294 
4295     pmull (v19, T1Q, v1, v16, T1D);
4296     pmull2(v20, T1Q, v1, v16, T2D);
4297     ldrq(v1, Address(buf, 0x20));
4298     eor3(v1, T16B, v19, v20, v1);
4299 
4300     pmull (v21, T1Q, v2, v16, T1D);
4301     pmull2(v22, T1Q, v2, v16, T2D);
4302     ldrq(v2, Address(buf, 0x30));
4303     eor3(v2, T16B, v21, v22, v2);
4304 
4305     pmull (v23, T1Q, v3, v16, T1D);
4306     pmull2(v24, T1Q, v3, v16, T2D);
4307     ldrq(v3, Address(buf, 0x40));
4308     eor3(v3, T16B, v23, v24, v3);
4309 
4310     pmull (v25, T1Q, v4, v16, T1D);
4311     pmull2(v26, T1Q, v4, v16, T2D);
4312     ldrq(v4, Address(buf, 0x50));
4313     eor3(v4, T16B, v25, v26, v4);
4314 
4315     pmull (v27, T1Q, v5, v16, T1D);
4316     pmull2(v28, T1Q, v5, v16, T2D);
4317     ldrq(v5, Address(buf, 0x60));
4318     eor3(v5, T16B, v27, v28, v5);
4319 
4320     pmull (v29, T1Q, v6, v16, T1D);
4321     pmull2(v30, T1Q, v6, v16, T2D);
4322     ldrq(v6, Address(buf, 0x70));
4323     eor3(v6, T16B, v29, v30, v6);
4324 
4325     // Reuse registers v23, v24.
4326     // Using them won't block the first instruction of the next iteration.
4327     pmull (v23, T1Q, v7, v16, T1D);
4328     pmull2(v24, T1Q, v7, v16, T2D);
4329     ldrq(v7, Address(pre(buf, 0x80)));
4330     eor3(v7, T16B, v23, v24, v7);
4331 
4332     subs(len, len, 0x80);
4333     br(Assembler::GE, CRC_by128_loop);
4334 
4335     // fold into 512 bits
4336     // Use v31 for constants because v16 can be still in use.
4337     ldrq(v31, Address(table, 0x10));
4338 
4339     pmull (v17,  T1Q, v0, v31, T1D);
4340     pmull2(v18, T1Q, v0, v31, T2D);
4341     eor3(v0, T16B, v17, v18, v4);
4342 
4343     pmull (v19, T1Q, v1, v31, T1D);
4344     pmull2(v20, T1Q, v1, v31, T2D);
4345     eor3(v1, T16B, v19, v20, v5);
4346 
4347     pmull (v21, T1Q, v2, v31, T1D);
4348     pmull2(v22, T1Q, v2, v31, T2D);
4349     eor3(v2, T16B, v21, v22, v6);
4350 
4351     pmull (v23, T1Q, v3, v31, T1D);
4352     pmull2(v24, T1Q, v3, v31, T2D);
4353     eor3(v3, T16B, v23, v24, v7);
4354 
4355     // fold into 128 bits
4356     // Use v17 for constants because v31 can be still in use.
4357     ldrq(v17, Address(table, 0x20));
4358     pmull (v25, T1Q, v0, v17, T1D);
4359     pmull2(v26, T1Q, v0, v17, T2D);
4360     eor3(v3, T16B, v3, v25, v26);
4361 
4362     // Use v18 for constants because v17 can be still in use.
4363     ldrq(v18, Address(table, 0x30));
4364     pmull (v27, T1Q, v1, v18, T1D);
4365     pmull2(v28, T1Q, v1, v18, T2D);
4366     eor3(v3, T16B, v3, v27, v28);
4367 
4368     // Use v19 for constants because v18 can be still in use.
4369     ldrq(v19, Address(table, 0x40));
4370     pmull (v29, T1Q, v2, v19, T1D);
4371     pmull2(v30, T1Q, v2, v19, T2D);
4372     eor3(v0, T16B, v3, v29, v30);
4373 
4374     add(len, len, 0x80);
4375     add(buf, buf, 0x10);
4376 
4377     mov(tmp0, v0, D, 0);
4378     mov(tmp1, v0, D, 1);
4379 }
4380 
4381 SkipIfEqual::SkipIfEqual(
4382     MacroAssembler* masm, const bool* flag_addr, bool value) {
4383   _masm = masm;
4384   uint64_t offset;
4385   _masm->adrp(rscratch1, ExternalAddress((address)flag_addr), offset);
4386   _masm->ldrb(rscratch1, Address(rscratch1, offset));
4387   if (value) {
4388     _masm->cbnzw(rscratch1, _label);
4389   } else {
4390     _masm->cbzw(rscratch1, _label);
4391   }
4392 }
4393 
4394 SkipIfEqual::~SkipIfEqual() {
4395   _masm->bind(_label);
4396 }
4397 
4398 void MacroAssembler::addptr(const Address &dst, int32_t src) {
4399   Address adr;
4400   switch(dst.getMode()) {
4401   case Address::base_plus_offset:
4402     // This is the expected mode, although we allow all the other
4403     // forms below.
4404     adr = form_address(rscratch2, dst.base(), dst.offset(), LogBytesPerWord);
4405     break;
4406   default:
4407     lea(rscratch2, dst);
4408     adr = Address(rscratch2);
4409     break;
4410   }
4411   ldr(rscratch1, adr);
4412   add(rscratch1, rscratch1, src);
4413   str(rscratch1, adr);
4414 }
4415 
4416 void MacroAssembler::cmpptr(Register src1, Address src2) {
4417   uint64_t offset;
4418   adrp(rscratch1, src2, offset);
4419   ldr(rscratch1, Address(rscratch1, offset));
4420   cmp(src1, rscratch1);
4421 }
4422 
4423 void MacroAssembler::cmpoop(Register obj1, Register obj2) {
4424   cmp(obj1, obj2);
4425 }
4426 
4427 void MacroAssembler::load_method_holder_cld(Register rresult, Register rmethod) {
4428   load_method_holder(rresult, rmethod);
4429   ldr(rresult, Address(rresult, InstanceKlass::class_loader_data_offset()));
4430 }
4431 
4432 void MacroAssembler::load_method_holder(Register holder, Register method) {
4433   ldr(holder, Address(method, Method::const_offset()));                      // ConstMethod*
4434   ldr(holder, Address(holder, ConstMethod::constants_offset()));             // ConstantPool*
4435   ldr(holder, Address(holder, ConstantPool::pool_holder_offset()));          // InstanceKlass*
4436 }
4437 








4438 void MacroAssembler::load_klass(Register dst, Register src) {
4439   if (UseCompressedClassPointers) {
4440     ldrw(dst, Address(src, oopDesc::klass_offset_in_bytes()));
4441     decode_klass_not_null(dst);
4442   } else {
4443     ldr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
4444   }
4445 }
4446 
4447 void MacroAssembler::restore_cpu_control_state_after_jni(Register tmp1, Register tmp2) {
4448   if (RestoreMXCSROnJNICalls) {
4449     Label OK;
4450     get_fpcr(tmp1);
4451     mov(tmp2, tmp1);
4452     // Set FPCR to the state we need. We do want Round to Nearest. We
4453     // don't want non-IEEE rounding modes or floating-point traps.
4454     bfi(tmp1, zr, 22, 4); // Clear DN, FZ, and Rmode
4455     bfi(tmp1, zr, 8, 5);  // Clear exception-control bits (8-12)
4456     bfi(tmp1, zr, 0, 2);  // Clear AH:FIZ
4457     eor(tmp2, tmp1, tmp2);
4458     cbz(tmp2, OK);        // Only reset FPCR if it's wrong
4459     set_fpcr(tmp1);
4460     bind(OK);
4461   }
4462 }
4463 
4464 // ((OopHandle)result).resolve();
4465 void MacroAssembler::resolve_oop_handle(Register result, Register tmp1, Register tmp2) {
4466   // OopHandle::resolve is an indirection.
4467   access_load_at(T_OBJECT, IN_NATIVE, result, Address(result, 0), tmp1, tmp2);
4468 }
4469 
4470 // ((WeakHandle)result).resolve();
4471 void MacroAssembler::resolve_weak_handle(Register result, Register tmp1, Register tmp2) {
4472   assert_different_registers(result, tmp1, tmp2);
4473   Label resolved;
4474 
4475   // A null weak handle resolves to null.
4476   cbz(result, resolved);
4477 
4478   // Only 64 bit platforms support GCs that require a tmp register
4479   // WeakHandle::resolve is an indirection like jweak.
4480   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
4481                  result, Address(result), tmp1, tmp2);
4482   bind(resolved);
4483 }
4484 
4485 void MacroAssembler::load_mirror(Register dst, Register method, Register tmp1, Register tmp2) {
4486   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
4487   ldr(dst, Address(rmethod, Method::const_offset()));
4488   ldr(dst, Address(dst, ConstMethod::constants_offset()));
4489   ldr(dst, Address(dst, ConstantPool::pool_holder_offset()));
4490   ldr(dst, Address(dst, mirror_offset));
4491   resolve_oop_handle(dst, tmp1, tmp2);
4492 }
4493 
4494 void MacroAssembler::cmp_klass(Register oop, Register trial_klass, Register tmp) {
4495   if (UseCompressedClassPointers) {
4496     ldrw(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
4497     if (CompressedKlassPointers::base() == nullptr) {
4498       cmp(trial_klass, tmp, LSL, CompressedKlassPointers::shift());
4499       return;
4500     } else if (((uint64_t)CompressedKlassPointers::base() & 0xffffffff) == 0
4501                && CompressedKlassPointers::shift() == 0) {
4502       // Only the bottom 32 bits matter
4503       cmpw(trial_klass, tmp);
4504       return;
4505     }
4506     decode_klass_not_null(tmp);
4507   } else {
4508     ldr(tmp, Address(oop, oopDesc::klass_offset_in_bytes()));
4509   }
4510   cmp(trial_klass, tmp);
4511 }
4512 





4513 void MacroAssembler::store_klass(Register dst, Register src) {
4514   // FIXME: Should this be a store release?  concurrent gcs assumes
4515   // klass length is valid if klass field is not null.
4516   if (UseCompressedClassPointers) {
4517     encode_klass_not_null(src);
4518     strw(src, Address(dst, oopDesc::klass_offset_in_bytes()));
4519   } else {
4520     str(src, Address(dst, oopDesc::klass_offset_in_bytes()));
4521   }
4522 }
4523 
4524 void MacroAssembler::store_klass_gap(Register dst, Register src) {
4525   if (UseCompressedClassPointers) {
4526     // Store to klass gap in destination
4527     strw(src, Address(dst, oopDesc::klass_gap_offset_in_bytes()));
4528   }
4529 }
4530 
4531 // Algorithm must match CompressedOops::encode.
4532 void MacroAssembler::encode_heap_oop(Register d, Register s) {
4533 #ifdef ASSERT
4534   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
4535 #endif
4536   verify_oop_msg(s, "broken oop in encode_heap_oop");
4537   if (CompressedOops::base() == nullptr) {
4538     if (CompressedOops::shift() != 0) {
4539       assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4540       lsr(d, s, LogMinObjAlignmentInBytes);
4541     } else {
4542       mov(d, s);
4543     }
4544   } else {
4545     subs(d, s, rheapbase);
4546     csel(d, d, zr, Assembler::HS);
4547     lsr(d, d, LogMinObjAlignmentInBytes);
4548 
4549     /*  Old algorithm: is this any worse?
4550     Label nonnull;
4551     cbnz(r, nonnull);
4552     sub(r, r, rheapbase);
4553     bind(nonnull);
4554     lsr(r, r, LogMinObjAlignmentInBytes);
4555     */
4556   }
4557 }
4558 
4559 void MacroAssembler::encode_heap_oop_not_null(Register r) {
4560 #ifdef ASSERT
4561   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
4562   if (CheckCompressedOops) {
4563     Label ok;
4564     cbnz(r, ok);
4565     stop("null oop passed to encode_heap_oop_not_null");
4566     bind(ok);
4567   }
4568 #endif
4569   verify_oop_msg(r, "broken oop in encode_heap_oop_not_null");
4570   if (CompressedOops::base() != nullptr) {
4571     sub(r, r, rheapbase);
4572   }
4573   if (CompressedOops::shift() != 0) {
4574     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4575     lsr(r, r, LogMinObjAlignmentInBytes);
4576   }
4577 }
4578 
4579 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
4580 #ifdef ASSERT
4581   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
4582   if (CheckCompressedOops) {
4583     Label ok;
4584     cbnz(src, ok);
4585     stop("null oop passed to encode_heap_oop_not_null2");
4586     bind(ok);
4587   }
4588 #endif
4589   verify_oop_msg(src, "broken oop in encode_heap_oop_not_null2");
4590 
4591   Register data = src;
4592   if (CompressedOops::base() != nullptr) {
4593     sub(dst, src, rheapbase);
4594     data = dst;
4595   }
4596   if (CompressedOops::shift() != 0) {
4597     assert (LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4598     lsr(dst, data, LogMinObjAlignmentInBytes);
4599     data = dst;
4600   }
4601   if (data == src)
4602     mov(dst, src);
4603 }
4604 
4605 void  MacroAssembler::decode_heap_oop(Register d, Register s) {
4606 #ifdef ASSERT
4607   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
4608 #endif
4609   if (CompressedOops::base() == nullptr) {
4610     if (CompressedOops::shift() != 0 || d != s) {
4611       lsl(d, s, CompressedOops::shift());
4612     }
4613   } else {
4614     Label done;
4615     if (d != s)
4616       mov(d, s);
4617     cbz(s, done);
4618     add(d, rheapbase, s, Assembler::LSL, LogMinObjAlignmentInBytes);
4619     bind(done);
4620   }
4621   verify_oop_msg(d, "broken oop in decode_heap_oop");
4622 }
4623 
4624 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
4625   assert (UseCompressedOops, "should only be used for compressed headers");
4626   assert (Universe::heap() != nullptr, "java heap should be initialized");
4627   // Cannot assert, unverified entry point counts instructions (see .ad file)
4628   // vtableStubs also counts instructions in pd_code_size_limit.
4629   // Also do not verify_oop as this is called by verify_oop.
4630   if (CompressedOops::shift() != 0) {
4631     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4632     if (CompressedOops::base() != nullptr) {
4633       add(r, rheapbase, r, Assembler::LSL, LogMinObjAlignmentInBytes);
4634     } else {
4635       add(r, zr, r, Assembler::LSL, LogMinObjAlignmentInBytes);
4636     }
4637   } else {
4638     assert (CompressedOops::base() == nullptr, "sanity");
4639   }
4640 }
4641 
4642 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
4643   assert (UseCompressedOops, "should only be used for compressed headers");
4644   assert (Universe::heap() != nullptr, "java heap should be initialized");
4645   // Cannot assert, unverified entry point counts instructions (see .ad file)
4646   // vtableStubs also counts instructions in pd_code_size_limit.
4647   // Also do not verify_oop as this is called by verify_oop.
4648   if (CompressedOops::shift() != 0) {
4649     assert(LogMinObjAlignmentInBytes == CompressedOops::shift(), "decode alg wrong");
4650     if (CompressedOops::base() != nullptr) {
4651       add(dst, rheapbase, src, Assembler::LSL, LogMinObjAlignmentInBytes);
4652     } else {
4653       add(dst, zr, src, Assembler::LSL, LogMinObjAlignmentInBytes);
4654     }
4655   } else {
4656     assert (CompressedOops::base() == nullptr, "sanity");
4657     if (dst != src) {
4658       mov(dst, src);
4659     }
4660   }
4661 }
4662 
4663 MacroAssembler::KlassDecodeMode MacroAssembler::_klass_decode_mode(KlassDecodeNone);
4664 
4665 MacroAssembler::KlassDecodeMode MacroAssembler::klass_decode_mode() {
4666   assert(UseCompressedClassPointers, "not using compressed class pointers");
4667   assert(Metaspace::initialized(), "metaspace not initialized yet");
4668 
4669   if (_klass_decode_mode != KlassDecodeNone) {
4670     return _klass_decode_mode;
4671   }
4672 
4673   assert(LogKlassAlignmentInBytes == CompressedKlassPointers::shift()
4674          || 0 == CompressedKlassPointers::shift(), "decode alg wrong");
4675 
4676   if (CompressedKlassPointers::base() == nullptr) {
4677     return (_klass_decode_mode = KlassDecodeZero);
4678   }
4679 
4680   if (operand_valid_for_logical_immediate(
4681         /*is32*/false, (uint64_t)CompressedKlassPointers::base())) {
4682     const uint64_t range_mask =
4683       (1ULL << log2i(CompressedKlassPointers::range())) - 1;
4684     if (((uint64_t)CompressedKlassPointers::base() & range_mask) == 0) {
4685       return (_klass_decode_mode = KlassDecodeXor);
4686     }
4687   }
4688 
4689   const uint64_t shifted_base =
4690     (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
4691   guarantee((shifted_base & 0xffff0000ffffffff) == 0,
4692             "compressed class base bad alignment");
4693 
4694   return (_klass_decode_mode = KlassDecodeMovk);
4695 }
4696 
4697 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
4698   switch (klass_decode_mode()) {
4699   case KlassDecodeZero:
4700     if (CompressedKlassPointers::shift() != 0) {
4701       lsr(dst, src, LogKlassAlignmentInBytes);
4702     } else {
4703       if (dst != src) mov(dst, src);
4704     }
4705     break;
4706 
4707   case KlassDecodeXor:
4708     if (CompressedKlassPointers::shift() != 0) {
4709       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
4710       lsr(dst, dst, LogKlassAlignmentInBytes);
4711     } else {
4712       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
4713     }
4714     break;
4715 
4716   case KlassDecodeMovk:
4717     if (CompressedKlassPointers::shift() != 0) {
4718       ubfx(dst, src, LogKlassAlignmentInBytes, 32);
4719     } else {
4720       movw(dst, src);
4721     }
4722     break;
4723 
4724   case KlassDecodeNone:
4725     ShouldNotReachHere();
4726     break;
4727   }
4728 }
4729 
4730 void MacroAssembler::encode_klass_not_null(Register r) {
4731   encode_klass_not_null(r, r);
4732 }
4733 
4734 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
4735   assert (UseCompressedClassPointers, "should only be used for compressed headers");
4736 
4737   switch (klass_decode_mode()) {
4738   case KlassDecodeZero:
4739     if (CompressedKlassPointers::shift() != 0) {
4740       lsl(dst, src, LogKlassAlignmentInBytes);
4741     } else {
4742       if (dst != src) mov(dst, src);
4743     }
4744     break;
4745 
4746   case KlassDecodeXor:
4747     if (CompressedKlassPointers::shift() != 0) {
4748       lsl(dst, src, LogKlassAlignmentInBytes);
4749       eor(dst, dst, (uint64_t)CompressedKlassPointers::base());
4750     } else {
4751       eor(dst, src, (uint64_t)CompressedKlassPointers::base());
4752     }
4753     break;
4754 
4755   case KlassDecodeMovk: {
4756     const uint64_t shifted_base =
4757       (uint64_t)CompressedKlassPointers::base() >> CompressedKlassPointers::shift();
4758 
4759     if (dst != src) movw(dst, src);
4760     movk(dst, shifted_base >> 32, 32);
4761 
4762     if (CompressedKlassPointers::shift() != 0) {
4763       lsl(dst, dst, LogKlassAlignmentInBytes);
4764     }
4765 
4766     break;
4767   }
4768 
4769   case KlassDecodeNone:
4770     ShouldNotReachHere();
4771     break;
4772   }
4773 }
4774 
4775 void  MacroAssembler::decode_klass_not_null(Register r) {
4776   decode_klass_not_null(r, r);
4777 }
4778 
4779 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
4780 #ifdef ASSERT
4781   {
4782     ThreadInVMfromUnknown tiv;
4783     assert (UseCompressedOops, "should only be used for compressed oops");
4784     assert (Universe::heap() != nullptr, "java heap should be initialized");
4785     assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
4786     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
4787   }
4788 #endif
4789   int oop_index = oop_recorder()->find_index(obj);
4790   InstructionMark im(this);
4791   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4792   code_section()->relocate(inst_mark(), rspec);
4793   movz(dst, 0xDEAD, 16);
4794   movk(dst, 0xBEEF);
4795 }
4796 
4797 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
4798   assert (UseCompressedClassPointers, "should only be used for compressed headers");
4799   assert (oop_recorder() != nullptr, "this assembler needs an OopRecorder");
4800   int index = oop_recorder()->find_index(k);
4801   assert(! Universe::heap()->is_in(k), "should not be an oop");
4802 
4803   InstructionMark im(this);
4804   RelocationHolder rspec = metadata_Relocation::spec(index);
4805   code_section()->relocate(inst_mark(), rspec);
4806   narrowKlass nk = CompressedKlassPointers::encode(k);
4807   movz(dst, (nk >> 16), 16);
4808   movk(dst, nk & 0xffff);
4809 }
4810 
4811 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators,
4812                                     Register dst, Address src,
4813                                     Register tmp1, Register tmp2) {
4814   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4815   decorators = AccessInternal::decorator_fixup(decorators, type);
4816   bool as_raw = (decorators & AS_RAW) != 0;
4817   if (as_raw) {
4818     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, tmp2);
4819   } else {
4820     bs->load_at(this, decorators, type, dst, src, tmp1, tmp2);
4821   }
4822 }
4823 
4824 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators,
4825                                      Address dst, Register val,
4826                                      Register tmp1, Register tmp2, Register tmp3) {
4827   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4828   decorators = AccessInternal::decorator_fixup(decorators, type);
4829   bool as_raw = (decorators & AS_RAW) != 0;
4830   if (as_raw) {
4831     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
4832   } else {
4833     bs->store_at(this, decorators, type, dst, val, tmp1, tmp2, tmp3);
4834   }
4835 }
4836 








































4837 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
4838                                    Register tmp2, DecoratorSet decorators) {
4839   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
4840 }
4841 
4842 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
4843                                             Register tmp2, DecoratorSet decorators) {
4844   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, tmp2);
4845 }
4846 
4847 void MacroAssembler::store_heap_oop(Address dst, Register val, Register tmp1,
4848                                     Register tmp2, Register tmp3, DecoratorSet decorators) {
4849   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, val, tmp1, tmp2, tmp3);
4850 }
4851 
4852 // Used for storing nulls.
4853 void MacroAssembler::store_heap_oop_null(Address dst) {
4854   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg, noreg);
4855 }
4856 
4857 Address MacroAssembler::allocate_metadata_address(Metadata* obj) {
4858   assert(oop_recorder() != nullptr, "this assembler needs a Recorder");
4859   int index = oop_recorder()->allocate_metadata_index(obj);
4860   RelocationHolder rspec = metadata_Relocation::spec(index);
4861   return Address((address)obj, rspec);
4862 }
4863 
4864 // Move an oop into a register.
4865 void MacroAssembler::movoop(Register dst, jobject obj) {
4866   int oop_index;
4867   if (obj == nullptr) {
4868     oop_index = oop_recorder()->allocate_oop_index(obj);
4869   } else {
4870 #ifdef ASSERT
4871     {
4872       ThreadInVMfromUnknown tiv;
4873       assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "should be real oop");
4874     }
4875 #endif
4876     oop_index = oop_recorder()->find_index(obj);
4877   }
4878   RelocationHolder rspec = oop_Relocation::spec(oop_index);
4879 
4880   if (BarrierSet::barrier_set()->barrier_set_assembler()->supports_instruction_patching()) {
4881     mov(dst, Address((address)obj, rspec));
4882   } else {
4883     address dummy = address(uintptr_t(pc()) & -wordSize); // A nearby aligned address
4884     ldr_constant(dst, Address(dummy, rspec));
4885   }
4886 
4887 }
4888 
4889 // Move a metadata address into a register.
4890 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
4891   int oop_index;
4892   if (obj == nullptr) {
4893     oop_index = oop_recorder()->allocate_metadata_index(obj);
4894   } else {
4895     oop_index = oop_recorder()->find_index(obj);
4896   }
4897   RelocationHolder rspec = metadata_Relocation::spec(oop_index);
4898   mov(dst, Address((address)obj, rspec));
4899 }
4900 
4901 Address MacroAssembler::constant_oop_address(jobject obj) {
4902 #ifdef ASSERT
4903   {
4904     ThreadInVMfromUnknown tiv;
4905     assert(oop_recorder() != nullptr, "this assembler needs an OopRecorder");
4906     assert(Universe::heap()->is_in(JNIHandles::resolve(obj)), "not an oop");
4907   }
4908 #endif
4909   int oop_index = oop_recorder()->find_index(obj);
4910   return Address((address)obj, oop_Relocation::spec(oop_index));
4911 }
4912 
































































































4913 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
4914 void MacroAssembler::tlab_allocate(Register obj,
4915                                    Register var_size_in_bytes,
4916                                    int con_size_in_bytes,
4917                                    Register t1,
4918                                    Register t2,
4919                                    Label& slow_case) {
4920   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
4921   bs->tlab_allocate(this, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
4922 }
4923 
4924 void MacroAssembler::verify_tlab() {
4925 #ifdef ASSERT
4926   if (UseTLAB && VerifyOops) {
4927     Label next, ok;
4928 
4929     stp(rscratch2, rscratch1, Address(pre(sp, -16)));
4930 
4931     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4932     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_start_offset())));
4933     cmp(rscratch2, rscratch1);
4934     br(Assembler::HS, next);
4935     STOP("assert(top >= start)");
4936     should_not_reach_here();
4937 
4938     bind(next);
4939     ldr(rscratch2, Address(rthread, in_bytes(JavaThread::tlab_end_offset())));
4940     ldr(rscratch1, Address(rthread, in_bytes(JavaThread::tlab_top_offset())));
4941     cmp(rscratch2, rscratch1);
4942     br(Assembler::HS, ok);
4943     STOP("assert(top <= end)");
4944     should_not_reach_here();
4945 
4946     bind(ok);
4947     ldp(rscratch2, rscratch1, Address(post(sp, 16)));
4948   }
4949 #endif
4950 }
4951 














4952 // Writes to stack successive pages until offset reached to check for
4953 // stack overflow + shadow pages.  This clobbers tmp.
4954 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
4955   assert_different_registers(tmp, size, rscratch1);
4956   mov(tmp, sp);
4957   // Bang stack for total size given plus shadow page size.
4958   // Bang one page at a time because large size can bang beyond yellow and
4959   // red zones.
4960   Label loop;
4961   mov(rscratch1, (int)os::vm_page_size());
4962   bind(loop);
4963   lea(tmp, Address(tmp, -(int)os::vm_page_size()));
4964   subsw(size, size, rscratch1);
4965   str(size, Address(tmp));
4966   br(Assembler::GT, loop);
4967 
4968   // Bang down shadow pages too.
4969   // At this point, (tmp-0) is the last address touched, so don't
4970   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
4971   // was post-decremented.)  Skip this address by starting at i=1, and
4972   // touch a few more pages below.  N.B.  It is important to touch all
4973   // the way down to and including i=StackShadowPages.
4974   for (int i = 0; i < (int)(StackOverflow::stack_shadow_zone_size() / (int)os::vm_page_size()) - 1; i++) {
4975     // this could be any sized move but this is can be a debugging crumb
4976     // so the bigger the better.
4977     lea(tmp, Address(tmp, -(int)os::vm_page_size()));
4978     str(size, Address(tmp));
4979   }
4980 }
4981 
4982 // Move the address of the polling page into dest.
4983 void MacroAssembler::get_polling_page(Register dest, relocInfo::relocType rtype) {
4984   ldr(dest, Address(rthread, JavaThread::polling_page_offset()));
4985 }
4986 
4987 // Read the polling page.  The address of the polling page must
4988 // already be in r.
4989 address MacroAssembler::read_polling_page(Register r, relocInfo::relocType rtype) {
4990   address mark;
4991   {
4992     InstructionMark im(this);
4993     code_section()->relocate(inst_mark(), rtype);
4994     ldrw(zr, Address(r, 0));
4995     mark = inst_mark();
4996   }
4997   verify_cross_modify_fence_not_required();
4998   return mark;
4999 }
5000 
5001 void MacroAssembler::adrp(Register reg1, const Address &dest, uint64_t &byte_offset) {
5002   relocInfo::relocType rtype = dest.rspec().reloc()->type();
5003   uint64_t low_page = (uint64_t)CodeCache::low_bound() >> 12;
5004   uint64_t high_page = (uint64_t)(CodeCache::high_bound()-1) >> 12;
5005   uint64_t dest_page = (uint64_t)dest.target() >> 12;
5006   int64_t offset_low = dest_page - low_page;
5007   int64_t offset_high = dest_page - high_page;
5008 
5009   assert(is_valid_AArch64_address(dest.target()), "bad address");
5010   assert(dest.getMode() == Address::literal, "ADRP must be applied to a literal address");
5011 
5012   InstructionMark im(this);
5013   code_section()->relocate(inst_mark(), dest.rspec());
5014   // 8143067: Ensure that the adrp can reach the dest from anywhere within
5015   // the code cache so that if it is relocated we know it will still reach
5016   if (offset_high >= -(1<<20) && offset_low < (1<<20)) {
5017     _adrp(reg1, dest.target());
5018   } else {
5019     uint64_t target = (uint64_t)dest.target();
5020     uint64_t adrp_target
5021       = (target & 0xffffffffULL) | ((uint64_t)pc() & 0xffff00000000ULL);
5022 
5023     _adrp(reg1, (address)adrp_target);
5024     movk(reg1, target >> 32, 32);
5025   }
5026   byte_offset = (uint64_t)dest.target() & 0xfff;
5027 }
5028 
5029 void MacroAssembler::load_byte_map_base(Register reg) {
5030   CardTable::CardValue* byte_map_base =
5031     ((CardTableBarrierSet*)(BarrierSet::barrier_set()))->card_table()->byte_map_base();
5032 
5033   // Strictly speaking the byte_map_base isn't an address at all, and it might
5034   // even be negative. It is thus materialised as a constant.
5035   mov(reg, (uint64_t)byte_map_base);
5036 }
5037 
5038 void MacroAssembler::build_frame(int framesize) {
5039   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
5040   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
5041   protect_return_address();
5042   if (framesize < ((1 << 9) + 2 * wordSize)) {
5043     sub(sp, sp, framesize);
5044     stp(rfp, lr, Address(sp, framesize - 2 * wordSize));
5045     if (PreserveFramePointer) add(rfp, sp, framesize - 2 * wordSize);
5046   } else {
5047     stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
5048     if (PreserveFramePointer) mov(rfp, sp);
5049     if (framesize < ((1 << 12) + 2 * wordSize))
5050       sub(sp, sp, framesize - 2 * wordSize);
5051     else {
5052       mov(rscratch1, framesize - 2 * wordSize);
5053       sub(sp, sp, rscratch1);
5054     }
5055   }
5056   verify_cross_modify_fence_not_required();
5057 }
5058 
5059 void MacroAssembler::remove_frame(int framesize) {
5060   assert(framesize >= 2 * wordSize, "framesize must include space for FP/LR");
5061   assert(framesize % (2*wordSize) == 0, "must preserve 2*wordSize alignment");
5062   if (framesize < ((1 << 9) + 2 * wordSize)) {
5063     ldp(rfp, lr, Address(sp, framesize - 2 * wordSize));
5064     add(sp, sp, framesize);
5065   } else {
5066     if (framesize < ((1 << 12) + 2 * wordSize))
5067       add(sp, sp, framesize - 2 * wordSize);
5068     else {
5069       mov(rscratch1, framesize - 2 * wordSize);
5070       add(sp, sp, rscratch1);
5071     }
5072     ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
5073   }
5074   authenticate_return_address();
5075 }
5076 



















































5077 
5078 // This method counts leading positive bytes (highest bit not set) in provided byte array
5079 address MacroAssembler::count_positives(Register ary1, Register len, Register result) {
5080     // Simple and most common case of aligned small array which is not at the
5081     // end of memory page is placed here. All other cases are in stub.
5082     Label LOOP, END, STUB, STUB_LONG, SET_RESULT, DONE;
5083     const uint64_t UPPER_BIT_MASK=0x8080808080808080;
5084     assert_different_registers(ary1, len, result);
5085 
5086     mov(result, len);
5087     cmpw(len, 0);
5088     br(LE, DONE);
5089     cmpw(len, 4 * wordSize);
5090     br(GE, STUB_LONG); // size > 32 then go to stub
5091 
5092     int shift = 64 - exact_log2(os::vm_page_size());
5093     lsl(rscratch1, ary1, shift);
5094     mov(rscratch2, (size_t)(4 * wordSize) << shift);
5095     adds(rscratch2, rscratch1, rscratch2);  // At end of page?
5096     br(CS, STUB); // at the end of page then go to stub
5097     subs(len, len, wordSize);
5098     br(LT, END);
5099 
5100   BIND(LOOP);
5101     ldr(rscratch1, Address(post(ary1, wordSize)));
5102     tst(rscratch1, UPPER_BIT_MASK);
5103     br(NE, SET_RESULT);
5104     subs(len, len, wordSize);
5105     br(GE, LOOP);
5106     cmpw(len, -wordSize);
5107     br(EQ, DONE);
5108 
5109   BIND(END);
5110     ldr(rscratch1, Address(ary1));
5111     sub(rscratch2, zr, len, LSL, 3); // LSL 3 is to get bits from bytes
5112     lslv(rscratch1, rscratch1, rscratch2);
5113     tst(rscratch1, UPPER_BIT_MASK);
5114     br(NE, SET_RESULT);
5115     b(DONE);
5116 
5117   BIND(STUB);
5118     RuntimeAddress count_pos = RuntimeAddress(StubRoutines::aarch64::count_positives());
5119     assert(count_pos.target() != nullptr, "count_positives stub has not been generated");
5120     address tpc1 = trampoline_call(count_pos);
5121     if (tpc1 == nullptr) {
5122       DEBUG_ONLY(reset_labels(STUB_LONG, SET_RESULT, DONE));
5123       postcond(pc() == badAddress);
5124       return nullptr;
5125     }
5126     b(DONE);
5127 
5128   BIND(STUB_LONG);
5129     RuntimeAddress count_pos_long = RuntimeAddress(StubRoutines::aarch64::count_positives_long());
5130     assert(count_pos_long.target() != nullptr, "count_positives_long stub has not been generated");
5131     address tpc2 = trampoline_call(count_pos_long);
5132     if (tpc2 == nullptr) {
5133       DEBUG_ONLY(reset_labels(SET_RESULT, DONE));
5134       postcond(pc() == badAddress);
5135       return nullptr;
5136     }
5137     b(DONE);
5138 
5139   BIND(SET_RESULT);
5140 
5141     add(len, len, wordSize);
5142     sub(result, result, len);
5143 
5144   BIND(DONE);
5145   postcond(pc() != badAddress);
5146   return pc();
5147 }
5148 
5149 // Clobbers: rscratch1, rscratch2, rflags
5150 // May also clobber v0-v7 when (!UseSimpleArrayEquals && UseSIMDForArrayEquals)
5151 address MacroAssembler::arrays_equals(Register a1, Register a2, Register tmp3,
5152                                       Register tmp4, Register tmp5, Register result,
5153                                       Register cnt1, int elem_size) {
5154   Label DONE, SAME;
5155   Register tmp1 = rscratch1;
5156   Register tmp2 = rscratch2;
5157   Register cnt2 = tmp2;  // cnt2 only used in array length compare
5158   int elem_per_word = wordSize/elem_size;
5159   int log_elem_size = exact_log2(elem_size);
5160   int length_offset = arrayOopDesc::length_offset_in_bytes();
5161   int base_offset
5162     = arrayOopDesc::base_offset_in_bytes(elem_size == 2 ? T_CHAR : T_BYTE);
5163   int stubBytesThreshold = 3 * 64 + (UseSIMDForArrayEquals ? 0 : 16);
5164 
5165   assert(elem_size == 1 || elem_size == 2, "must be char or byte");
5166   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
5167 
5168 #ifndef PRODUCT
5169   {
5170     const char kind = (elem_size == 2) ? 'U' : 'L';
5171     char comment[64];
5172     snprintf(comment, sizeof comment, "array_equals%c{", kind);
5173     BLOCK_COMMENT(comment);
5174   }
5175 #endif
5176 
5177   // if (a1 == a2)
5178   //     return true;
5179   cmpoop(a1, a2); // May have read barriers for a1 and a2.
5180   br(EQ, SAME);
5181 
5182   if (UseSimpleArrayEquals) {
5183     Label NEXT_WORD, SHORT, TAIL03, TAIL01, A_MIGHT_BE_NULL, A_IS_NOT_NULL;
5184     // if (a1 == nullptr || a2 == nullptr)
5185     //     return false;
5186     // a1 & a2 == 0 means (some-pointer is null) or
5187     // (very-rare-or-even-probably-impossible-pointer-values)
5188     // so, we can save one branch in most cases
5189     tst(a1, a2);
5190     mov(result, false);
5191     br(EQ, A_MIGHT_BE_NULL);
5192     // if (a1.length != a2.length)
5193     //      return false;
5194     bind(A_IS_NOT_NULL);
5195     ldrw(cnt1, Address(a1, length_offset));
5196     ldrw(cnt2, Address(a2, length_offset));
5197     eorw(tmp5, cnt1, cnt2);
5198     cbnzw(tmp5, DONE);
5199     lea(a1, Address(a1, base_offset));
5200     lea(a2, Address(a2, base_offset));
5201     // Check for short strings, i.e. smaller than wordSize.
5202     subs(cnt1, cnt1, elem_per_word);
5203     br(Assembler::LT, SHORT);
5204     // Main 8 byte comparison loop.
5205     bind(NEXT_WORD); {
5206       ldr(tmp1, Address(post(a1, wordSize)));
5207       ldr(tmp2, Address(post(a2, wordSize)));
5208       subs(cnt1, cnt1, elem_per_word);
5209       eor(tmp5, tmp1, tmp2);
5210       cbnz(tmp5, DONE);
5211     } br(GT, NEXT_WORD);
5212     // Last longword.  In the case where length == 4 we compare the
5213     // same longword twice, but that's still faster than another
5214     // conditional branch.
5215     // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
5216     // length == 4.
5217     if (log_elem_size > 0)
5218       lsl(cnt1, cnt1, log_elem_size);
5219     ldr(tmp3, Address(a1, cnt1));
5220     ldr(tmp4, Address(a2, cnt1));
5221     eor(tmp5, tmp3, tmp4);
5222     cbnz(tmp5, DONE);
5223     b(SAME);
5224     bind(A_MIGHT_BE_NULL);
5225     // in case both a1 and a2 are not-null, proceed with loads
5226     cbz(a1, DONE);
5227     cbz(a2, DONE);
5228     b(A_IS_NOT_NULL);
5229     bind(SHORT);
5230 
5231     tbz(cnt1, 2 - log_elem_size, TAIL03); // 0-7 bytes left.
5232     {
5233       ldrw(tmp1, Address(post(a1, 4)));
5234       ldrw(tmp2, Address(post(a2, 4)));
5235       eorw(tmp5, tmp1, tmp2);
5236       cbnzw(tmp5, DONE);
5237     }
5238     bind(TAIL03);
5239     tbz(cnt1, 1 - log_elem_size, TAIL01); // 0-3 bytes left.
5240     {
5241       ldrh(tmp3, Address(post(a1, 2)));
5242       ldrh(tmp4, Address(post(a2, 2)));
5243       eorw(tmp5, tmp3, tmp4);
5244       cbnzw(tmp5, DONE);
5245     }
5246     bind(TAIL01);
5247     if (elem_size == 1) { // Only needed when comparing byte arrays.
5248       tbz(cnt1, 0, SAME); // 0-1 bytes left.
5249       {
5250         ldrb(tmp1, a1);
5251         ldrb(tmp2, a2);
5252         eorw(tmp5, tmp1, tmp2);
5253         cbnzw(tmp5, DONE);
5254       }
5255     }
5256   } else {
5257     Label NEXT_DWORD, SHORT, TAIL, TAIL2, STUB,
5258         CSET_EQ, LAST_CHECK;
5259     mov(result, false);
5260     cbz(a1, DONE);
5261     ldrw(cnt1, Address(a1, length_offset));
5262     cbz(a2, DONE);
5263     ldrw(cnt2, Address(a2, length_offset));
5264     // on most CPUs a2 is still "locked"(surprisingly) in ldrw and it's
5265     // faster to perform another branch before comparing a1 and a2
5266     cmp(cnt1, (u1)elem_per_word);
5267     br(LE, SHORT); // short or same
5268     ldr(tmp3, Address(pre(a1, base_offset)));
5269     subs(zr, cnt1, stubBytesThreshold);
5270     br(GE, STUB);
5271     ldr(tmp4, Address(pre(a2, base_offset)));
5272     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
5273     cmp(cnt2, cnt1);
5274     br(NE, DONE);
5275 
5276     // Main 16 byte comparison loop with 2 exits
5277     bind(NEXT_DWORD); {
5278       ldr(tmp1, Address(pre(a1, wordSize)));
5279       ldr(tmp2, Address(pre(a2, wordSize)));
5280       subs(cnt1, cnt1, 2 * elem_per_word);
5281       br(LE, TAIL);
5282       eor(tmp4, tmp3, tmp4);
5283       cbnz(tmp4, DONE);
5284       ldr(tmp3, Address(pre(a1, wordSize)));
5285       ldr(tmp4, Address(pre(a2, wordSize)));
5286       cmp(cnt1, (u1)elem_per_word);
5287       br(LE, TAIL2);
5288       cmp(tmp1, tmp2);
5289     } br(EQ, NEXT_DWORD);
5290     b(DONE);
5291 
5292     bind(TAIL);
5293     eor(tmp4, tmp3, tmp4);
5294     eor(tmp2, tmp1, tmp2);
5295     lslv(tmp2, tmp2, tmp5);
5296     orr(tmp5, tmp4, tmp2);
5297     cmp(tmp5, zr);
5298     b(CSET_EQ);
5299 
5300     bind(TAIL2);
5301     eor(tmp2, tmp1, tmp2);
5302     cbnz(tmp2, DONE);
5303     b(LAST_CHECK);
5304 
5305     bind(STUB);
5306     ldr(tmp4, Address(pre(a2, base_offset)));
5307     cmp(cnt2, cnt1);
5308     br(NE, DONE);
5309     if (elem_size == 2) { // convert to byte counter
5310       lsl(cnt1, cnt1, 1);
5311     }
5312     eor(tmp5, tmp3, tmp4);
5313     cbnz(tmp5, DONE);
5314     RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_array_equals());
5315     assert(stub.target() != nullptr, "array_equals_long stub has not been generated");
5316     address tpc = trampoline_call(stub);
5317     if (tpc == nullptr) {
5318       DEBUG_ONLY(reset_labels(SHORT, LAST_CHECK, CSET_EQ, SAME, DONE));
5319       postcond(pc() == badAddress);
5320       return nullptr;
5321     }
5322     b(DONE);
5323 
5324     // (a1 != null && a2 == null) || (a1 != null && a2 != null && a1 == a2)
5325     // so, if a2 == null => return false(0), else return true, so we can return a2
5326     mov(result, a2);
5327     b(DONE);
5328     bind(SHORT);
5329     cmp(cnt2, cnt1);
5330     br(NE, DONE);
5331     cbz(cnt1, SAME);
5332     sub(tmp5, zr, cnt1, LSL, 3 + log_elem_size);
5333     ldr(tmp3, Address(a1, base_offset));
5334     ldr(tmp4, Address(a2, base_offset));
5335     bind(LAST_CHECK);
5336     eor(tmp4, tmp3, tmp4);
5337     lslv(tmp5, tmp4, tmp5);
5338     cmp(tmp5, zr);
5339     bind(CSET_EQ);
5340     cset(result, EQ);
5341     b(DONE);
5342   }
5343 
5344   bind(SAME);
5345   mov(result, true);
5346   // That's it.
5347   bind(DONE);
5348 
5349   BLOCK_COMMENT("} array_equals");
5350   postcond(pc() != badAddress);
5351   return pc();
5352 }
5353 
5354 // Compare Strings
5355 
5356 // For Strings we're passed the address of the first characters in a1
5357 // and a2 and the length in cnt1.
5358 // There are two implementations.  For arrays >= 8 bytes, all
5359 // comparisons (including the final one, which may overlap) are
5360 // performed 8 bytes at a time.  For strings < 8 bytes, we compare a
5361 // halfword, then a short, and then a byte.
5362 
5363 void MacroAssembler::string_equals(Register a1, Register a2,
5364                                    Register result, Register cnt1)
5365 {
5366   Label SAME, DONE, SHORT, NEXT_WORD;
5367   Register tmp1 = rscratch1;
5368   Register tmp2 = rscratch2;
5369   Register cnt2 = tmp2;  // cnt2 only used in array length compare
5370 
5371   assert_different_registers(a1, a2, result, cnt1, rscratch1, rscratch2);
5372 
5373 #ifndef PRODUCT
5374   {
5375     char comment[64];
5376     snprintf(comment, sizeof comment, "{string_equalsL");
5377     BLOCK_COMMENT(comment);
5378   }
5379 #endif
5380 
5381   mov(result, false);
5382 
5383   // Check for short strings, i.e. smaller than wordSize.
5384   subs(cnt1, cnt1, wordSize);
5385   br(Assembler::LT, SHORT);
5386   // Main 8 byte comparison loop.
5387   bind(NEXT_WORD); {
5388     ldr(tmp1, Address(post(a1, wordSize)));
5389     ldr(tmp2, Address(post(a2, wordSize)));
5390     subs(cnt1, cnt1, wordSize);
5391     eor(tmp1, tmp1, tmp2);
5392     cbnz(tmp1, DONE);
5393   } br(GT, NEXT_WORD);
5394   // Last longword.  In the case where length == 4 we compare the
5395   // same longword twice, but that's still faster than another
5396   // conditional branch.
5397   // cnt1 could be 0, -1, -2, -3, -4 for chars; -4 only happens when
5398   // length == 4.
5399   ldr(tmp1, Address(a1, cnt1));
5400   ldr(tmp2, Address(a2, cnt1));
5401   eor(tmp2, tmp1, tmp2);
5402   cbnz(tmp2, DONE);
5403   b(SAME);
5404 
5405   bind(SHORT);
5406   Label TAIL03, TAIL01;
5407 
5408   tbz(cnt1, 2, TAIL03); // 0-7 bytes left.
5409   {
5410     ldrw(tmp1, Address(post(a1, 4)));
5411     ldrw(tmp2, Address(post(a2, 4)));
5412     eorw(tmp1, tmp1, tmp2);
5413     cbnzw(tmp1, DONE);
5414   }
5415   bind(TAIL03);
5416   tbz(cnt1, 1, TAIL01); // 0-3 bytes left.
5417   {
5418     ldrh(tmp1, Address(post(a1, 2)));
5419     ldrh(tmp2, Address(post(a2, 2)));
5420     eorw(tmp1, tmp1, tmp2);
5421     cbnzw(tmp1, DONE);
5422   }
5423   bind(TAIL01);
5424   tbz(cnt1, 0, SAME); // 0-1 bytes left.
5425     {
5426     ldrb(tmp1, a1);
5427     ldrb(tmp2, a2);
5428     eorw(tmp1, tmp1, tmp2);
5429     cbnzw(tmp1, DONE);
5430   }
5431   // Arrays are equal.
5432   bind(SAME);
5433   mov(result, true);
5434 
5435   // That's it.
5436   bind(DONE);
5437   BLOCK_COMMENT("} string_equals");
5438 }
5439 
5440 
5441 // The size of the blocks erased by the zero_blocks stub.  We must
5442 // handle anything smaller than this ourselves in zero_words().
5443 const int MacroAssembler::zero_words_block_size = 8;
5444 
5445 // zero_words() is used by C2 ClearArray patterns and by
5446 // C1_MacroAssembler.  It is as small as possible, handling small word
5447 // counts locally and delegating anything larger to the zero_blocks
5448 // stub.  It is expanded many times in compiled code, so it is
5449 // important to keep it short.
5450 
5451 // ptr:   Address of a buffer to be zeroed.
5452 // cnt:   Count in HeapWords.
5453 //
5454 // ptr, cnt, rscratch1, and rscratch2 are clobbered.
5455 address MacroAssembler::zero_words(Register ptr, Register cnt)
5456 {
5457   assert(is_power_of_2(zero_words_block_size), "adjust this");
5458 
5459   BLOCK_COMMENT("zero_words {");
5460   assert(ptr == r10 && cnt == r11, "mismatch in register usage");
5461   RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
5462   assert(zero_blocks.target() != nullptr, "zero_blocks stub has not been generated");
5463 
5464   subs(rscratch1, cnt, zero_words_block_size);
5465   Label around;
5466   br(LO, around);
5467   {
5468     RuntimeAddress zero_blocks = RuntimeAddress(StubRoutines::aarch64::zero_blocks());
5469     assert(zero_blocks.target() != nullptr, "zero_blocks stub has not been generated");
5470     // Make sure this is a C2 compilation. C1 allocates space only for
5471     // trampoline stubs generated by Call LIR ops, and in any case it
5472     // makes sense for a C1 compilation task to proceed as quickly as
5473     // possible.
5474     CompileTask* task;
5475     if (StubRoutines::aarch64::complete()
5476         && Thread::current()->is_Compiler_thread()
5477         && (task = ciEnv::current()->task())
5478         && is_c2_compile(task->comp_level())) {
5479       address tpc = trampoline_call(zero_blocks);
5480       if (tpc == nullptr) {
5481         DEBUG_ONLY(reset_labels(around));
5482         return nullptr;
5483       }
5484     } else {
5485       far_call(zero_blocks);
5486     }
5487   }
5488   bind(around);
5489 
5490   // We have a few words left to do. zero_blocks has adjusted r10 and r11
5491   // for us.
5492   for (int i = zero_words_block_size >> 1; i > 1; i >>= 1) {
5493     Label l;
5494     tbz(cnt, exact_log2(i), l);
5495     for (int j = 0; j < i; j += 2) {
5496       stp(zr, zr, post(ptr, 2 * BytesPerWord));
5497     }
5498     bind(l);
5499   }
5500   {
5501     Label l;
5502     tbz(cnt, 0, l);
5503     str(zr, Address(ptr));
5504     bind(l);
5505   }
5506 
5507   BLOCK_COMMENT("} zero_words");
5508   return pc();
5509 }
5510 
5511 // base:         Address of a buffer to be zeroed, 8 bytes aligned.
5512 // cnt:          Immediate count in HeapWords.
5513 //
5514 // r10, r11, rscratch1, and rscratch2 are clobbered.
5515 address MacroAssembler::zero_words(Register base, uint64_t cnt)
5516 {
5517   assert(wordSize <= BlockZeroingLowLimit,
5518             "increase BlockZeroingLowLimit");
5519   address result = nullptr;
5520   if (cnt <= (uint64_t)BlockZeroingLowLimit / BytesPerWord) {
5521 #ifndef PRODUCT
5522     {
5523       char buf[64];
5524       snprintf(buf, sizeof buf, "zero_words (count = %" PRIu64 ") {", cnt);
5525       BLOCK_COMMENT(buf);
5526     }
5527 #endif
5528     if (cnt >= 16) {
5529       uint64_t loops = cnt/16;
5530       if (loops > 1) {
5531         mov(rscratch2, loops - 1);
5532       }
5533       {
5534         Label loop;
5535         bind(loop);
5536         for (int i = 0; i < 16; i += 2) {
5537           stp(zr, zr, Address(base, i * BytesPerWord));
5538         }
5539         add(base, base, 16 * BytesPerWord);
5540         if (loops > 1) {
5541           subs(rscratch2, rscratch2, 1);
5542           br(GE, loop);
5543         }
5544       }
5545     }
5546     cnt %= 16;
5547     int i = cnt & 1;  // store any odd word to start
5548     if (i) str(zr, Address(base));
5549     for (; i < (int)cnt; i += 2) {
5550       stp(zr, zr, Address(base, i * wordSize));
5551     }
5552     BLOCK_COMMENT("} zero_words");
5553     result = pc();
5554   } else {
5555     mov(r10, base); mov(r11, cnt);
5556     result = zero_words(r10, r11);
5557   }
5558   return result;
5559 }
5560 
5561 // Zero blocks of memory by using DC ZVA.
5562 //
5563 // Aligns the base address first sufficiently for DC ZVA, then uses
5564 // DC ZVA repeatedly for every full block.  cnt is the size to be
5565 // zeroed in HeapWords.  Returns the count of words left to be zeroed
5566 // in cnt.
5567 //
5568 // NOTE: This is intended to be used in the zero_blocks() stub.  If
5569 // you want to use it elsewhere, note that cnt must be >= 2*zva_length.
5570 void MacroAssembler::zero_dcache_blocks(Register base, Register cnt) {
5571   Register tmp = rscratch1;
5572   Register tmp2 = rscratch2;
5573   int zva_length = VM_Version::zva_length();
5574   Label initial_table_end, loop_zva;
5575   Label fini;
5576 
5577   // Base must be 16 byte aligned. If not just return and let caller handle it
5578   tst(base, 0x0f);
5579   br(Assembler::NE, fini);
5580   // Align base with ZVA length.
5581   neg(tmp, base);
5582   andr(tmp, tmp, zva_length - 1);
5583 
5584   // tmp: the number of bytes to be filled to align the base with ZVA length.
5585   add(base, base, tmp);
5586   sub(cnt, cnt, tmp, Assembler::ASR, 3);
5587   adr(tmp2, initial_table_end);
5588   sub(tmp2, tmp2, tmp, Assembler::LSR, 2);
5589   br(tmp2);
5590 
5591   for (int i = -zva_length + 16; i < 0; i += 16)
5592     stp(zr, zr, Address(base, i));
5593   bind(initial_table_end);
5594 
5595   sub(cnt, cnt, zva_length >> 3);
5596   bind(loop_zva);
5597   dc(Assembler::ZVA, base);
5598   subs(cnt, cnt, zva_length >> 3);
5599   add(base, base, zva_length);
5600   br(Assembler::GE, loop_zva);
5601   add(cnt, cnt, zva_length >> 3); // count not zeroed by DC ZVA
5602   bind(fini);
5603 }
5604 
5605 // base:   Address of a buffer to be filled, 8 bytes aligned.
5606 // cnt:    Count in 8-byte unit.
5607 // value:  Value to be filled with.
5608 // base will point to the end of the buffer after filling.
5609 void MacroAssembler::fill_words(Register base, Register cnt, Register value)
5610 {
5611 //  Algorithm:
5612 //
5613 //    if (cnt == 0) {
5614 //      return;
5615 //    }
5616 //    if ((p & 8) != 0) {
5617 //      *p++ = v;
5618 //    }
5619 //
5620 //    scratch1 = cnt & 14;
5621 //    cnt -= scratch1;
5622 //    p += scratch1;
5623 //    switch (scratch1 / 2) {
5624 //      do {
5625 //        cnt -= 16;
5626 //          p[-16] = v;
5627 //          p[-15] = v;
5628 //        case 7:
5629 //          p[-14] = v;
5630 //          p[-13] = v;
5631 //        case 6:
5632 //          p[-12] = v;
5633 //          p[-11] = v;
5634 //          // ...
5635 //        case 1:
5636 //          p[-2] = v;
5637 //          p[-1] = v;
5638 //        case 0:
5639 //          p += 16;
5640 //      } while (cnt);
5641 //    }
5642 //    if ((cnt & 1) == 1) {
5643 //      *p++ = v;
5644 //    }
5645 
5646   assert_different_registers(base, cnt, value, rscratch1, rscratch2);
5647 
5648   Label fini, skip, entry, loop;
5649   const int unroll = 8; // Number of stp instructions we'll unroll
5650 
5651   cbz(cnt, fini);
5652   tbz(base, 3, skip);
5653   str(value, Address(post(base, 8)));
5654   sub(cnt, cnt, 1);
5655   bind(skip);
5656 
5657   andr(rscratch1, cnt, (unroll-1) * 2);
5658   sub(cnt, cnt, rscratch1);
5659   add(base, base, rscratch1, Assembler::LSL, 3);
5660   adr(rscratch2, entry);
5661   sub(rscratch2, rscratch2, rscratch1, Assembler::LSL, 1);
5662   br(rscratch2);
5663 
5664   bind(loop);
5665   add(base, base, unroll * 16);
5666   for (int i = -unroll; i < 0; i++)
5667     stp(value, value, Address(base, i * 16));
5668   bind(entry);
5669   subs(cnt, cnt, unroll * 2);
5670   br(Assembler::GE, loop);
5671 
5672   tbz(cnt, 0, fini);
5673   str(value, Address(post(base, 8)));
5674   bind(fini);
5675 }
5676 
5677 // Intrinsic for
5678 //
5679 // - sun/nio/cs/ISO_8859_1$Encoder.implEncodeISOArray
5680 //     return the number of characters copied.
5681 // - java/lang/StringUTF16.compress
5682 //     return index of non-latin1 character if copy fails, otherwise 'len'.
5683 //
5684 // This version always returns the number of characters copied, and does not
5685 // clobber the 'len' register. A successful copy will complete with the post-
5686 // condition: 'res' == 'len', while an unsuccessful copy will exit with the
5687 // post-condition: 0 <= 'res' < 'len'.
5688 //
5689 // NOTE: Attempts to use 'ld2' (and 'umaxv' in the ISO part) has proven to
5690 //       degrade performance (on Ampere Altra - Neoverse N1), to an extent
5691 //       beyond the acceptable, even though the footprint would be smaller.
5692 //       Using 'umaxv' in the ASCII-case comes with a small penalty but does
5693 //       avoid additional bloat.
5694 //
5695 // Clobbers: src, dst, res, rscratch1, rscratch2, rflags
5696 void MacroAssembler::encode_iso_array(Register src, Register dst,
5697                                       Register len, Register res, bool ascii,
5698                                       FloatRegister vtmp0, FloatRegister vtmp1,
5699                                       FloatRegister vtmp2, FloatRegister vtmp3,
5700                                       FloatRegister vtmp4, FloatRegister vtmp5)
5701 {
5702   Register cnt = res;
5703   Register max = rscratch1;
5704   Register chk = rscratch2;
5705 
5706   prfm(Address(src), PLDL1STRM);
5707   movw(cnt, len);
5708 
5709 #define ASCII(insn) do { if (ascii) { insn; } } while (0)
5710 
5711   Label LOOP_32, DONE_32, FAIL_32;
5712 
5713   BIND(LOOP_32);
5714   {
5715     cmpw(cnt, 32);
5716     br(LT, DONE_32);
5717     ld1(vtmp0, vtmp1, vtmp2, vtmp3, T8H, Address(post(src, 64)));
5718     // Extract lower bytes.
5719     FloatRegister vlo0 = vtmp4;
5720     FloatRegister vlo1 = vtmp5;
5721     uzp1(vlo0, T16B, vtmp0, vtmp1);
5722     uzp1(vlo1, T16B, vtmp2, vtmp3);
5723     // Merge bits...
5724     orr(vtmp0, T16B, vtmp0, vtmp1);
5725     orr(vtmp2, T16B, vtmp2, vtmp3);
5726     // Extract merged upper bytes.
5727     FloatRegister vhix = vtmp0;
5728     uzp2(vhix, T16B, vtmp0, vtmp2);
5729     // ISO-check on hi-parts (all zero).
5730     //                          ASCII-check on lo-parts (no sign).
5731     FloatRegister vlox = vtmp1; // Merge lower bytes.
5732                                 ASCII(orr(vlox, T16B, vlo0, vlo1));
5733     umov(chk, vhix, D, 1);      ASCII(cm(LT, vlox, T16B, vlox));
5734     fmovd(max, vhix);           ASCII(umaxv(vlox, T16B, vlox));
5735     orr(chk, chk, max);         ASCII(umov(max, vlox, B, 0));
5736                                 ASCII(orr(chk, chk, max));
5737     cbnz(chk, FAIL_32);
5738     subw(cnt, cnt, 32);
5739     st1(vlo0, vlo1, T16B, Address(post(dst, 32)));
5740     b(LOOP_32);
5741   }
5742   BIND(FAIL_32);
5743   sub(src, src, 64);
5744   BIND(DONE_32);
5745 
5746   Label LOOP_8, SKIP_8;
5747 
5748   BIND(LOOP_8);
5749   {
5750     cmpw(cnt, 8);
5751     br(LT, SKIP_8);
5752     FloatRegister vhi = vtmp0;
5753     FloatRegister vlo = vtmp1;
5754     ld1(vtmp3, T8H, src);
5755     uzp1(vlo, T16B, vtmp3, vtmp3);
5756     uzp2(vhi, T16B, vtmp3, vtmp3);
5757     // ISO-check on hi-parts (all zero).
5758     //                          ASCII-check on lo-parts (no sign).
5759                                 ASCII(cm(LT, vtmp2, T16B, vlo));
5760     fmovd(chk, vhi);            ASCII(umaxv(vtmp2, T16B, vtmp2));
5761                                 ASCII(umov(max, vtmp2, B, 0));
5762                                 ASCII(orr(chk, chk, max));
5763     cbnz(chk, SKIP_8);
5764 
5765     strd(vlo, Address(post(dst, 8)));
5766     subw(cnt, cnt, 8);
5767     add(src, src, 16);
5768     b(LOOP_8);
5769   }
5770   BIND(SKIP_8);
5771 
5772 #undef ASCII
5773 
5774   Label LOOP, DONE;
5775 
5776   cbz(cnt, DONE);
5777   BIND(LOOP);
5778   {
5779     Register chr = rscratch1;
5780     ldrh(chr, Address(post(src, 2)));
5781     tst(chr, ascii ? 0xff80 : 0xff00);
5782     br(NE, DONE);
5783     strb(chr, Address(post(dst, 1)));
5784     subs(cnt, cnt, 1);
5785     br(GT, LOOP);
5786   }
5787   BIND(DONE);
5788   // Return index where we stopped.
5789   subw(res, len, cnt);
5790 }
5791 
5792 // Inflate byte[] array to char[].
5793 // Clobbers: src, dst, len, rflags, rscratch1, v0-v6
5794 address MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
5795                                            FloatRegister vtmp1, FloatRegister vtmp2,
5796                                            FloatRegister vtmp3, Register tmp4) {
5797   Label big, done, after_init, to_stub;
5798 
5799   assert_different_registers(src, dst, len, tmp4, rscratch1);
5800 
5801   fmovd(vtmp1, 0.0);
5802   lsrw(tmp4, len, 3);
5803   bind(after_init);
5804   cbnzw(tmp4, big);
5805   // Short string: less than 8 bytes.
5806   {
5807     Label loop, tiny;
5808 
5809     cmpw(len, 4);
5810     br(LT, tiny);
5811     // Use SIMD to do 4 bytes.
5812     ldrs(vtmp2, post(src, 4));
5813     zip1(vtmp3, T8B, vtmp2, vtmp1);
5814     subw(len, len, 4);
5815     strd(vtmp3, post(dst, 8));
5816 
5817     cbzw(len, done);
5818 
5819     // Do the remaining bytes by steam.
5820     bind(loop);
5821     ldrb(tmp4, post(src, 1));
5822     strh(tmp4, post(dst, 2));
5823     subw(len, len, 1);
5824 
5825     bind(tiny);
5826     cbnz(len, loop);
5827 
5828     b(done);
5829   }
5830 
5831   if (SoftwarePrefetchHintDistance >= 0) {
5832     bind(to_stub);
5833       RuntimeAddress stub = RuntimeAddress(StubRoutines::aarch64::large_byte_array_inflate());
5834       assert(stub.target() != nullptr, "large_byte_array_inflate stub has not been generated");
5835       address tpc = trampoline_call(stub);
5836       if (tpc == nullptr) {
5837         DEBUG_ONLY(reset_labels(big, done));
5838         postcond(pc() == badAddress);
5839         return nullptr;
5840       }
5841       b(after_init);
5842   }
5843 
5844   // Unpack the bytes 8 at a time.
5845   bind(big);
5846   {
5847     Label loop, around, loop_last, loop_start;
5848 
5849     if (SoftwarePrefetchHintDistance >= 0) {
5850       const int large_loop_threshold = (64 + 16)/8;
5851       ldrd(vtmp2, post(src, 8));
5852       andw(len, len, 7);
5853       cmp(tmp4, (u1)large_loop_threshold);
5854       br(GE, to_stub);
5855       b(loop_start);
5856 
5857       bind(loop);
5858       ldrd(vtmp2, post(src, 8));
5859       bind(loop_start);
5860       subs(tmp4, tmp4, 1);
5861       br(EQ, loop_last);
5862       zip1(vtmp2, T16B, vtmp2, vtmp1);
5863       ldrd(vtmp3, post(src, 8));
5864       st1(vtmp2, T8H, post(dst, 16));
5865       subs(tmp4, tmp4, 1);
5866       zip1(vtmp3, T16B, vtmp3, vtmp1);
5867       st1(vtmp3, T8H, post(dst, 16));
5868       br(NE, loop);
5869       b(around);
5870       bind(loop_last);
5871       zip1(vtmp2, T16B, vtmp2, vtmp1);
5872       st1(vtmp2, T8H, post(dst, 16));
5873       bind(around);
5874       cbz(len, done);
5875     } else {
5876       andw(len, len, 7);
5877       bind(loop);
5878       ldrd(vtmp2, post(src, 8));
5879       sub(tmp4, tmp4, 1);
5880       zip1(vtmp3, T16B, vtmp2, vtmp1);
5881       st1(vtmp3, T8H, post(dst, 16));
5882       cbnz(tmp4, loop);
5883     }
5884   }
5885 
5886   // Do the tail of up to 8 bytes.
5887   add(src, src, len);
5888   ldrd(vtmp3, Address(src, -8));
5889   add(dst, dst, len, ext::uxtw, 1);
5890   zip1(vtmp3, T16B, vtmp3, vtmp1);
5891   strq(vtmp3, Address(dst, -16));
5892 
5893   bind(done);
5894   postcond(pc() != badAddress);
5895   return pc();
5896 }
5897 
5898 // Compress char[] array to byte[].
5899 // Intrinsic for java.lang.StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
5900 // Return the array length if every element in array can be encoded,
5901 // otherwise, the index of first non-latin1 (> 0xff) character.
5902 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
5903                                          Register res,
5904                                          FloatRegister tmp0, FloatRegister tmp1,
5905                                          FloatRegister tmp2, FloatRegister tmp3,
5906                                          FloatRegister tmp4, FloatRegister tmp5) {
5907   encode_iso_array(src, dst, len, res, false, tmp0, tmp1, tmp2, tmp3, tmp4, tmp5);
5908 }
5909 
5910 // java.math.round(double a)
5911 // Returns the closest long to the argument, with ties rounding to
5912 // positive infinity.  This requires some fiddling for corner
5913 // cases. We take care to avoid double rounding in e.g. (jlong)(a + 0.5).
5914 void MacroAssembler::java_round_double(Register dst, FloatRegister src,
5915                                        FloatRegister ftmp) {
5916   Label DONE;
5917   BLOCK_COMMENT("java_round_double: { ");
5918   fmovd(rscratch1, src);
5919   // Use RoundToNearestTiesAway unless src small and -ve.
5920   fcvtasd(dst, src);
5921   // Test if src >= 0 || abs(src) >= 0x1.0p52
5922   eor(rscratch1, rscratch1, UCONST64(1) << 63); // flip sign bit
5923   mov(rscratch2, julong_cast(0x1.0p52));
5924   cmp(rscratch1, rscratch2);
5925   br(HS, DONE); {
5926     // src < 0 && abs(src) < 0x1.0p52
5927     // src may have a fractional part, so add 0.5
5928     fmovd(ftmp, 0.5);
5929     faddd(ftmp, src, ftmp);
5930     // Convert double to jlong, use RoundTowardsNegative
5931     fcvtmsd(dst, ftmp);
5932   }
5933   bind(DONE);
5934   BLOCK_COMMENT("} java_round_double");
5935 }
5936 
5937 void MacroAssembler::java_round_float(Register dst, FloatRegister src,
5938                                       FloatRegister ftmp) {
5939   Label DONE;
5940   BLOCK_COMMENT("java_round_float: { ");
5941   fmovs(rscratch1, src);
5942   // Use RoundToNearestTiesAway unless src small and -ve.
5943   fcvtassw(dst, src);
5944   // Test if src >= 0 || abs(src) >= 0x1.0p23
5945   eor(rscratch1, rscratch1, 0x80000000); // flip sign bit
5946   mov(rscratch2, jint_cast(0x1.0p23f));
5947   cmp(rscratch1, rscratch2);
5948   br(HS, DONE); {
5949     // src < 0 && |src| < 0x1.0p23
5950     // src may have a fractional part, so add 0.5
5951     fmovs(ftmp, 0.5f);
5952     fadds(ftmp, src, ftmp);
5953     // Convert float to jint, use RoundTowardsNegative
5954     fcvtmssw(dst, ftmp);
5955   }
5956   bind(DONE);
5957   BLOCK_COMMENT("} java_round_float");
5958 }
5959 
5960 // get_thread() can be called anywhere inside generated code so we
5961 // need to save whatever non-callee save context might get clobbered
5962 // by the call to JavaThread::aarch64_get_thread_helper() or, indeed,
5963 // the call setup code.
5964 //
5965 // On Linux, aarch64_get_thread_helper() clobbers only r0, r1, and flags.
5966 // On other systems, the helper is a usual C function.
5967 //
5968 void MacroAssembler::get_thread(Register dst) {
5969   RegSet saved_regs =
5970     LINUX_ONLY(RegSet::range(r0, r1)  + lr - dst)
5971     NOT_LINUX (RegSet::range(r0, r17) + lr - dst);
5972 
5973   protect_return_address();
5974   push(saved_regs, sp);
5975 
5976   mov(lr, CAST_FROM_FN_PTR(address, JavaThread::aarch64_get_thread_helper));
5977   blr(lr);
5978   if (dst != c_rarg0) {
5979     mov(dst, c_rarg0);
5980   }
5981 
5982   pop(saved_regs, sp);
5983   authenticate_return_address();
5984 }
5985 

























































































































































































































































































































































































































































5986 void MacroAssembler::cache_wb(Address line) {
5987   assert(line.getMode() == Address::base_plus_offset, "mode should be base_plus_offset");
5988   assert(line.index() == noreg, "index should be noreg");
5989   assert(line.offset() == 0, "offset should be 0");
5990   // would like to assert this
5991   // assert(line._ext.shift == 0, "shift should be zero");
5992   if (VM_Version::supports_dcpop()) {
5993     // writeback using clear virtual address to point of persistence
5994     dc(Assembler::CVAP, line.base());
5995   } else {
5996     // no need to generate anything as Unsafe.writebackMemory should
5997     // never invoke this stub
5998   }
5999 }
6000 
6001 void MacroAssembler::cache_wbsync(bool is_pre) {
6002   // we only need a barrier post sync
6003   if (!is_pre) {
6004     membar(Assembler::AnyAny);
6005   }
6006 }
6007 
6008 void MacroAssembler::verify_sve_vector_length(Register tmp) {
6009   // Make sure that native code does not change SVE vector length.
6010   if (!UseSVE) return;
6011   Label verify_ok;
6012   movw(tmp, zr);
6013   sve_inc(tmp, B);
6014   subsw(zr, tmp, VM_Version::get_initial_sve_vector_length());
6015   br(EQ, verify_ok);
6016   stop("Error: SVE vector length has changed since jvm startup");
6017   bind(verify_ok);
6018 }
6019 
6020 void MacroAssembler::verify_ptrue() {
6021   Label verify_ok;
6022   if (!UseSVE) {
6023     return;
6024   }
6025   sve_cntp(rscratch1, B, ptrue, ptrue); // get true elements count.
6026   sve_dec(rscratch1, B);
6027   cbz(rscratch1, verify_ok);
6028   stop("Error: the preserved predicate register (p7) elements are not all true");
6029   bind(verify_ok);
6030 }
6031 
6032 void MacroAssembler::safepoint_isb() {
6033   isb();
6034 #ifndef PRODUCT
6035   if (VerifyCrossModifyFence) {
6036     // Clear the thread state.
6037     strb(zr, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
6038   }
6039 #endif
6040 }
6041 
6042 #ifndef PRODUCT
6043 void MacroAssembler::verify_cross_modify_fence_not_required() {
6044   if (VerifyCrossModifyFence) {
6045     // Check if thread needs a cross modify fence.
6046     ldrb(rscratch1, Address(rthread, in_bytes(JavaThread::requires_cross_modify_fence_offset())));
6047     Label fence_not_required;
6048     cbz(rscratch1, fence_not_required);
6049     // If it does then fail.
6050     lea(rscratch1, CAST_FROM_FN_PTR(address, JavaThread::verify_cross_modify_fence_failure));
6051     mov(c_rarg0, rthread);
6052     blr(rscratch1);
6053     bind(fence_not_required);
6054   }
6055 }
6056 #endif
6057 
6058 void MacroAssembler::spin_wait() {
6059   for (int i = 0; i < VM_Version::spin_wait_desc().inst_count(); ++i) {
6060     switch (VM_Version::spin_wait_desc().inst()) {
6061       case SpinWait::NOP:
6062         nop();
6063         break;
6064       case SpinWait::ISB:
6065         isb();
6066         break;
6067       case SpinWait::YIELD:
6068         yield();
6069         break;
6070       default:
6071         ShouldNotReachHere();
6072     }
6073   }
6074 }
6075 
6076 // Stack frame creation/removal
6077 
6078 void MacroAssembler::enter(bool strip_ret_addr) {
6079   if (strip_ret_addr) {
6080     // Addresses can only be signed once. If there are multiple nested frames being created
6081     // in the same function, then the return address needs stripping first.
6082     strip_return_address();
6083   }
6084   protect_return_address();
6085   stp(rfp, lr, Address(pre(sp, -2 * wordSize)));
6086   mov(rfp, sp);
6087 }
6088 
6089 void MacroAssembler::leave() {
6090   mov(sp, rfp);
6091   ldp(rfp, lr, Address(post(sp, 2 * wordSize)));
6092   authenticate_return_address();
6093 }
6094 
6095 // ROP Protection
6096 // Use the AArch64 PAC feature to add ROP protection for generated code. Use whenever creating/
6097 // destroying stack frames or whenever directly loading/storing the LR to memory.
6098 // If ROP protection is not set then these functions are no-ops.
6099 // For more details on PAC see pauth_aarch64.hpp.
6100 
6101 // Sign the LR. Use during construction of a stack frame, before storing the LR to memory.
6102 // Uses value zero as the modifier.
6103 //
6104 void MacroAssembler::protect_return_address() {
6105   if (VM_Version::use_rop_protection()) {
6106     check_return_address();
6107     paciaz();
6108   }
6109 }
6110 
6111 // Sign the return value in the given register. Use before updating the LR in the existing stack
6112 // frame for the current function.
6113 // Uses value zero as the modifier.
6114 //
6115 void MacroAssembler::protect_return_address(Register return_reg) {
6116   if (VM_Version::use_rop_protection()) {
6117     check_return_address(return_reg);
6118     paciza(return_reg);
6119   }
6120 }
6121 
6122 // Authenticate the LR. Use before function return, after restoring FP and loading LR from memory.
6123 // Uses value zero as the modifier.
6124 //
6125 void MacroAssembler::authenticate_return_address() {
6126   if (VM_Version::use_rop_protection()) {
6127     autiaz();
6128     check_return_address();
6129   }
6130 }
6131 
6132 // Authenticate the return value in the given register. Use before updating the LR in the existing
6133 // stack frame for the current function.
6134 // Uses value zero as the modifier.
6135 //
6136 void MacroAssembler::authenticate_return_address(Register return_reg) {
6137   if (VM_Version::use_rop_protection()) {
6138     autiza(return_reg);
6139     check_return_address(return_reg);
6140   }
6141 }
6142 
6143 // Strip any PAC data from LR without performing any authentication. Use with caution - only if
6144 // there is no guaranteed way of authenticating the LR.
6145 //
6146 void MacroAssembler::strip_return_address() {
6147   if (VM_Version::use_rop_protection()) {
6148     xpaclri();
6149   }
6150 }
6151 
6152 #ifndef PRODUCT
6153 // PAC failures can be difficult to debug. After an authentication failure, a segfault will only
6154 // occur when the pointer is used - ie when the program returns to the invalid LR. At this point
6155 // it is difficult to debug back to the callee function.
6156 // This function simply loads from the address in the given register.
6157 // Use directly after authentication to catch authentication failures.
6158 // Also use before signing to check that the pointer is valid and hasn't already been signed.
6159 //
6160 void MacroAssembler::check_return_address(Register return_reg) {
6161   if (VM_Version::use_rop_protection()) {
6162     ldr(zr, Address(return_reg));
6163   }
6164 }
6165 #endif
6166 
6167 // The java_calling_convention describes stack locations as ideal slots on
6168 // a frame with no abi restrictions. Since we must observe abi restrictions
6169 // (like the placement of the register window) the slots must be biased by
6170 // the following value.
6171 static int reg2offset_in(VMReg r) {
6172   // Account for saved rfp and lr
6173   // This should really be in_preserve_stack_slots
6174   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
6175 }
6176 
6177 static int reg2offset_out(VMReg r) {
6178   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
6179 }
6180 
6181 // On 64bit we will store integer like items to the stack as
6182 // 64bits items (AArch64 ABI) even though java would only store
6183 // 32bits for a parameter. On 32bit it will simply be 32bits
6184 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
6185 void MacroAssembler::move32_64(VMRegPair src, VMRegPair dst, Register tmp) {
6186   if (src.first()->is_stack()) {
6187     if (dst.first()->is_stack()) {
6188       // stack to stack
6189       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
6190       str(tmp, Address(sp, reg2offset_out(dst.first())));
6191     } else {
6192       // stack to reg
6193       ldrsw(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
6194     }
6195   } else if (dst.first()->is_stack()) {
6196     // reg to stack
6197     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
6198   } else {
6199     if (dst.first() != src.first()) {
6200       sxtw(dst.first()->as_Register(), src.first()->as_Register());
6201     }
6202   }
6203 }
6204 
6205 // An oop arg. Must pass a handle not the oop itself
6206 void MacroAssembler::object_move(
6207                         OopMap* map,
6208                         int oop_handle_offset,
6209                         int framesize_in_slots,
6210                         VMRegPair src,
6211                         VMRegPair dst,
6212                         bool is_receiver,
6213                         int* receiver_offset) {
6214 
6215   // must pass a handle. First figure out the location we use as a handle
6216 
6217   Register rHandle = dst.first()->is_stack() ? rscratch2 : dst.first()->as_Register();
6218 
6219   // See if oop is null if it is we need no handle
6220 
6221   if (src.first()->is_stack()) {
6222 
6223     // Oop is already on the stack as an argument
6224     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
6225     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
6226     if (is_receiver) {
6227       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
6228     }
6229 
6230     ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
6231     lea(rHandle, Address(rfp, reg2offset_in(src.first())));
6232     // conditionally move a null
6233     cmp(rscratch1, zr);
6234     csel(rHandle, zr, rHandle, Assembler::EQ);
6235   } else {
6236 
6237     // Oop is in an a register we must store it to the space we reserve
6238     // on the stack for oop_handles and pass a handle if oop is non-null
6239 
6240     const Register rOop = src.first()->as_Register();
6241     int oop_slot;
6242     if (rOop == j_rarg0)
6243       oop_slot = 0;
6244     else if (rOop == j_rarg1)
6245       oop_slot = 1;
6246     else if (rOop == j_rarg2)
6247       oop_slot = 2;
6248     else if (rOop == j_rarg3)
6249       oop_slot = 3;
6250     else if (rOop == j_rarg4)
6251       oop_slot = 4;
6252     else if (rOop == j_rarg5)
6253       oop_slot = 5;
6254     else if (rOop == j_rarg6)
6255       oop_slot = 6;
6256     else {
6257       assert(rOop == j_rarg7, "wrong register");
6258       oop_slot = 7;
6259     }
6260 
6261     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
6262     int offset = oop_slot*VMRegImpl::stack_slot_size;
6263 
6264     map->set_oop(VMRegImpl::stack2reg(oop_slot));
6265     // Store oop in handle area, may be null
6266     str(rOop, Address(sp, offset));
6267     if (is_receiver) {
6268       *receiver_offset = offset;
6269     }
6270 
6271     cmp(rOop, zr);
6272     lea(rHandle, Address(sp, offset));
6273     // conditionally move a null
6274     csel(rHandle, zr, rHandle, Assembler::EQ);
6275   }
6276 
6277   // If arg is on the stack then place it otherwise it is already in correct reg.
6278   if (dst.first()->is_stack()) {
6279     str(rHandle, Address(sp, reg2offset_out(dst.first())));
6280   }
6281 }
6282 
6283 // A float arg may have to do float reg int reg conversion
6284 void MacroAssembler::float_move(VMRegPair src, VMRegPair dst, Register tmp) {
6285  if (src.first()->is_stack()) {
6286     if (dst.first()->is_stack()) {
6287       ldrw(tmp, Address(rfp, reg2offset_in(src.first())));
6288       strw(tmp, Address(sp, reg2offset_out(dst.first())));
6289     } else {
6290       ldrs(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
6291     }
6292   } else if (src.first() != dst.first()) {
6293     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
6294       fmovs(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
6295     else
6296       strs(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
6297   }
6298 }
6299 
6300 // A long move
6301 void MacroAssembler::long_move(VMRegPair src, VMRegPair dst, Register tmp) {
6302   if (src.first()->is_stack()) {
6303     if (dst.first()->is_stack()) {
6304       // stack to stack
6305       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
6306       str(tmp, Address(sp, reg2offset_out(dst.first())));
6307     } else {
6308       // stack to reg
6309       ldr(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
6310     }
6311   } else if (dst.first()->is_stack()) {
6312     // reg to stack
6313     // Do we really have to sign extend???
6314     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
6315     str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
6316   } else {
6317     if (dst.first() != src.first()) {
6318       mov(dst.first()->as_Register(), src.first()->as_Register());
6319     }
6320   }
6321 }
6322 
6323 
6324 // A double move
6325 void MacroAssembler::double_move(VMRegPair src, VMRegPair dst, Register tmp) {
6326  if (src.first()->is_stack()) {
6327     if (dst.first()->is_stack()) {
6328       ldr(tmp, Address(rfp, reg2offset_in(src.first())));
6329       str(tmp, Address(sp, reg2offset_out(dst.first())));
6330     } else {
6331       ldrd(dst.first()->as_FloatRegister(), Address(rfp, reg2offset_in(src.first())));
6332     }
6333   } else if (src.first() != dst.first()) {
6334     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
6335       fmovd(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
6336     else
6337       strd(src.first()->as_FloatRegister(), Address(sp, reg2offset_out(dst.first())));
6338   }
6339 }
6340 
6341 // Implements lightweight-locking.
6342 // Branches to slow upon failure to lock the object, with ZF cleared.
6343 // Falls through upon success with ZF set.
6344 //
6345 //  - obj: the object to be locked
6346 //  - hdr: the header, already loaded from obj, will be destroyed
6347 //  - t1, t2: temporary registers, will be destroyed
6348 void MacroAssembler::lightweight_lock(Register obj, Register hdr, Register t1, Register t2, Label& slow) {
6349   assert(LockingMode == LM_LIGHTWEIGHT, "only used with new lightweight locking");
6350   assert_different_registers(obj, hdr, t1, t2, rscratch1);
6351 
6352   // Check if we would have space on lock-stack for the object.
6353   ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
6354   cmpw(t1, (unsigned)LockStack::end_offset() - 1);
6355   br(Assembler::GT, slow);
6356 
6357   // Load (object->mark() | 1) into hdr
6358   orr(hdr, hdr, markWord::unlocked_value);





6359   // Clear lock-bits, into t2
6360   eor(t2, hdr, markWord::unlocked_value);
6361   // Try to swing header from unlocked to locked
6362   // Clobbers rscratch1 when UseLSE is false
6363   cmpxchg(/*addr*/ obj, /*expected*/ hdr, /*new*/ t2, Assembler::xword,
6364           /*acquire*/ true, /*release*/ true, /*weak*/ false, t1);
6365   br(Assembler::NE, slow);
6366 
6367   // After successful lock, push object on lock-stack
6368   ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
6369   str(obj, Address(rthread, t1));
6370   addw(t1, t1, oopSize);
6371   strw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
6372 }
6373 
6374 // Implements lightweight-unlocking.
6375 // Branches to slow upon failure, with ZF cleared.
6376 // Falls through upon success, with ZF set.
6377 //
6378 // - obj: the object to be unlocked
6379 // - hdr: the (pre-loaded) header of the object
6380 // - t1, t2: temporary registers
6381 void MacroAssembler::lightweight_unlock(Register obj, Register hdr, Register t1, Register t2, Label& slow) {
6382   assert(LockingMode == LM_LIGHTWEIGHT, "only used with new lightweight locking");
6383   assert_different_registers(obj, hdr, t1, t2, rscratch1);
6384 
6385 #ifdef ASSERT
6386   {
6387     // The following checks rely on the fact that LockStack is only ever modified by
6388     // its owning thread, even if the lock got inflated concurrently; removal of LockStack
6389     // entries after inflation will happen delayed in that case.
6390 
6391     // Check for lock-stack underflow.
6392     Label stack_ok;
6393     ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
6394     cmpw(t1, (unsigned)LockStack::start_offset());
6395     br(Assembler::GT, stack_ok);
6396     STOP("Lock-stack underflow");
6397     bind(stack_ok);
6398   }
6399   {
6400     // Check if the top of the lock-stack matches the unlocked object.
6401     Label tos_ok;
6402     subw(t1, t1, oopSize);
6403     ldr(t1, Address(rthread, t1));
6404     cmpoop(t1, obj);
6405     br(Assembler::EQ, tos_ok);
6406     STOP("Top of lock-stack does not match the unlocked object");
6407     bind(tos_ok);
6408   }
6409   {
6410     // Check that hdr is fast-locked.
6411     Label hdr_ok;
6412     tst(hdr, markWord::lock_mask_in_place);
6413     br(Assembler::EQ, hdr_ok);
6414     STOP("Header is not fast-locked");
6415     bind(hdr_ok);
6416   }
6417 #endif
6418 
6419   // Load the new header (unlocked) into t1
6420   orr(t1, hdr, markWord::unlocked_value);
6421 
6422   // Try to swing header from locked to unlocked
6423   // Clobbers rscratch1 when UseLSE is false
6424   cmpxchg(obj, hdr, t1, Assembler::xword,
6425           /*acquire*/ true, /*release*/ true, /*weak*/ false, t2);
6426   br(Assembler::NE, slow);
6427 
6428   // After successful unlock, pop object from lock-stack
6429   ldrw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
6430   subw(t1, t1, oopSize);
6431 #ifdef ASSERT
6432   str(zr, Address(rthread, t1));
6433 #endif
6434   strw(t1, Address(rthread, JavaThread::lock_stack_top_offset()));
6435 }
--- EOF ---