1 /*
   2  * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "asm/macroAssembler.hpp"
  27 #include "asm/macroAssembler.inline.hpp"
  28 #include "gc/shared/barrierSet.hpp"
  29 #include "gc/shared/barrierSetAssembler.hpp"
  30 #include "gc/shared/barrierSetNMethod.hpp"
  31 #include "interpreter/interpreter.hpp"
  32 #include "memory/universe.hpp"
  33 #include "nativeInst_x86.hpp"
  34 #include "oops/instanceOop.hpp"
  35 #include "oops/method.hpp"
  36 #include "oops/objArrayKlass.hpp"
  37 #include "oops/oop.inline.hpp"
  38 #include "prims/methodHandles.hpp"
  39 #include "runtime/frame.inline.hpp"
  40 #include "runtime/handles.inline.hpp"
  41 #include "runtime/sharedRuntime.hpp"
  42 #include "runtime/stubCodeGenerator.hpp"
  43 #include "runtime/stubRoutines.hpp"
  44 #include "runtime/thread.inline.hpp"
  45 #ifdef COMPILER2
  46 #include "opto/runtime.hpp"
  47 #endif
  48 
  49 // Declaration and definition of StubGenerator (no .hpp file).
  50 // For a more detailed description of the stub routine structure
  51 // see the comment in stubRoutines.hpp
  52 
  53 #define __ _masm->
  54 #define a__ ((Assembler*)_masm)->
  55 
  56 #ifdef PRODUCT
  57 #define BLOCK_COMMENT(str) /* nothing */
  58 #else
  59 #define BLOCK_COMMENT(str) __ block_comment(str)
  60 #endif
  61 
  62 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  63 
  64 const int MXCSR_MASK  = 0xFFC0;  // Mask out any pending exceptions
  65 const int FPU_CNTRL_WRD_MASK = 0xFFFF;
  66 
  67 // -------------------------------------------------------------------------------------------------------------------------
  68 // Stub Code definitions
  69 
  70 class StubGenerator: public StubCodeGenerator {
  71  private:
  72 
  73 #ifdef PRODUCT
  74 #define inc_counter_np(counter) ((void)0)
  75 #else
  76   void inc_counter_np_(int& counter) {
  77     __ incrementl(ExternalAddress((address)&counter));
  78   }
  79 #define inc_counter_np(counter) \
  80   BLOCK_COMMENT("inc_counter " #counter); \
  81   inc_counter_np_(counter);
  82 #endif //PRODUCT
  83 
  84   void inc_copy_counter_np(BasicType t) {
  85 #ifndef PRODUCT
  86     switch (t) {
  87     case T_BYTE:    inc_counter_np(SharedRuntime::_jbyte_array_copy_ctr); return;
  88     case T_SHORT:   inc_counter_np(SharedRuntime::_jshort_array_copy_ctr); return;
  89     case T_INT:     inc_counter_np(SharedRuntime::_jint_array_copy_ctr); return;
  90     case T_LONG:    inc_counter_np(SharedRuntime::_jlong_array_copy_ctr); return;
  91     case T_OBJECT:  inc_counter_np(SharedRuntime::_oop_array_copy_ctr); return;
  92     default:        ShouldNotReachHere();
  93     }
  94 #endif //PRODUCT
  95   }
  96 
  97   //------------------------------------------------------------------------------------------------------------------------
  98   // Call stubs are used to call Java from C
  99   //
 100   //    [ return_from_Java     ] <--- rsp
 101   //    [ argument word n      ]
 102   //      ...
 103   // -N [ argument word 1      ]
 104   // -7 [ Possible padding for stack alignment ]
 105   // -6 [ Possible padding for stack alignment ]
 106   // -5 [ Possible padding for stack alignment ]
 107   // -4 [ mxcsr save           ] <--- rsp_after_call
 108   // -3 [ saved rbx,            ]
 109   // -2 [ saved rsi            ]
 110   // -1 [ saved rdi            ]
 111   //  0 [ saved rbp,            ] <--- rbp,
 112   //  1 [ return address       ]
 113   //  2 [ ptr. to call wrapper ]
 114   //  3 [ result               ]
 115   //  4 [ result_type          ]
 116   //  5 [ method               ]
 117   //  6 [ entry_point          ]
 118   //  7 [ parameters           ]
 119   //  8 [ parameter_size       ]
 120   //  9 [ thread               ]
 121 
 122 
 123   address generate_call_stub(address& return_address) {
 124     StubCodeMark mark(this, "StubRoutines", "call_stub");
 125     address start = __ pc();
 126 
 127     // stub code parameters / addresses
 128     assert(frame::entry_frame_call_wrapper_offset == 2, "adjust this code");
 129     bool  sse_save = false;
 130     const Address rsp_after_call(rbp, -4 * wordSize); // same as in generate_catch_exception()!
 131     const int     locals_count_in_bytes  (4*wordSize);
 132     const Address mxcsr_save    (rbp, -4 * wordSize);
 133     const Address saved_rbx     (rbp, -3 * wordSize);
 134     const Address saved_rsi     (rbp, -2 * wordSize);
 135     const Address saved_rdi     (rbp, -1 * wordSize);
 136     const Address result        (rbp,  3 * wordSize);
 137     const Address result_type   (rbp,  4 * wordSize);
 138     const Address method        (rbp,  5 * wordSize);
 139     const Address entry_point   (rbp,  6 * wordSize);
 140     const Address parameters    (rbp,  7 * wordSize);
 141     const Address parameter_size(rbp,  8 * wordSize);
 142     const Address thread        (rbp,  9 * wordSize); // same as in generate_catch_exception()!
 143     sse_save =  UseSSE > 0;
 144 
 145     // stub code
 146     __ enter();
 147     __ movptr(rcx, parameter_size);              // parameter counter
 148     __ shlptr(rcx, Interpreter::logStackElementSize); // convert parameter count to bytes
 149     __ addptr(rcx, locals_count_in_bytes);       // reserve space for register saves
 150     __ subptr(rsp, rcx);
 151     __ andptr(rsp, -(StackAlignmentInBytes));    // Align stack
 152 
 153     // save rdi, rsi, & rbx, according to C calling conventions
 154     __ movptr(saved_rdi, rdi);
 155     __ movptr(saved_rsi, rsi);
 156     __ movptr(saved_rbx, rbx);
 157 
 158     // save and initialize %mxcsr
 159     if (sse_save) {
 160       Label skip_ldmx;
 161       __ stmxcsr(mxcsr_save);
 162       __ movl(rax, mxcsr_save);
 163       __ andl(rax, MXCSR_MASK);    // Only check control and mask bits
 164       ExternalAddress mxcsr_std(StubRoutines::addr_mxcsr_std());
 165       __ cmp32(rax, mxcsr_std);
 166       __ jcc(Assembler::equal, skip_ldmx);
 167       __ ldmxcsr(mxcsr_std);
 168       __ bind(skip_ldmx);
 169     }
 170 
 171     // make sure the control word is correct.
 172     __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
 173 
 174 #ifdef ASSERT
 175     // make sure we have no pending exceptions
 176     { Label L;
 177       __ movptr(rcx, thread);
 178       __ cmpptr(Address(rcx, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
 179       __ jcc(Assembler::equal, L);
 180       __ stop("StubRoutines::call_stub: entered with pending exception");
 181       __ bind(L);
 182     }
 183 #endif
 184 
 185     // pass parameters if any
 186     BLOCK_COMMENT("pass parameters if any");
 187     Label parameters_done;
 188     __ movl(rcx, parameter_size);  // parameter counter
 189     __ testl(rcx, rcx);
 190     __ jcc(Assembler::zero, parameters_done);
 191 
 192     // parameter passing loop
 193 
 194     Label loop;
 195     // Copy Java parameters in reverse order (receiver last)
 196     // Note that the argument order is inverted in the process
 197     // source is rdx[rcx: N-1..0]
 198     // dest   is rsp[rbx: 0..N-1]
 199 
 200     __ movptr(rdx, parameters);          // parameter pointer
 201     __ xorptr(rbx, rbx);
 202 
 203     __ BIND(loop);
 204 
 205     // get parameter
 206     __ movptr(rax, Address(rdx, rcx, Interpreter::stackElementScale(), -wordSize));
 207     __ movptr(Address(rsp, rbx, Interpreter::stackElementScale(),
 208                     Interpreter::expr_offset_in_bytes(0)), rax);          // store parameter
 209     __ increment(rbx);
 210     __ decrement(rcx);
 211     __ jcc(Assembler::notZero, loop);
 212 
 213     // call Java function
 214     __ BIND(parameters_done);
 215     __ movptr(rbx, method);           // get Method*
 216     __ movptr(rax, entry_point);      // get entry_point
 217     __ mov(rsi, rsp);                 // set sender sp
 218     BLOCK_COMMENT("call Java function");
 219     __ call(rax);
 220 
 221     BLOCK_COMMENT("call_stub_return_address:");
 222     return_address = __ pc();
 223 
 224 #ifdef COMPILER2
 225     {
 226       Label L_skip;
 227       if (UseSSE >= 2) {
 228         __ verify_FPU(0, "call_stub_return");
 229       } else {
 230         for (int i = 1; i < 8; i++) {
 231           __ ffree(i);
 232         }
 233 
 234         // UseSSE <= 1 so double result should be left on TOS
 235         __ movl(rsi, result_type);
 236         __ cmpl(rsi, T_DOUBLE);
 237         __ jcc(Assembler::equal, L_skip);
 238         if (UseSSE == 0) {
 239           // UseSSE == 0 so float result should be left on TOS
 240           __ cmpl(rsi, T_FLOAT);
 241           __ jcc(Assembler::equal, L_skip);
 242         }
 243         __ ffree(0);
 244       }
 245       __ BIND(L_skip);
 246     }
 247 #endif // COMPILER2
 248 
 249     // store result depending on type
 250     // (everything that is not T_LONG, T_FLOAT or T_DOUBLE is treated as T_INT)
 251     __ movptr(rdi, result);
 252     Label is_long, is_float, is_double, exit;
 253     __ movl(rsi, result_type);
 254     __ cmpl(rsi, T_LONG);
 255     __ jcc(Assembler::equal, is_long);
 256     __ cmpl(rsi, T_FLOAT);
 257     __ jcc(Assembler::equal, is_float);
 258     __ cmpl(rsi, T_DOUBLE);
 259     __ jcc(Assembler::equal, is_double);
 260 
 261     // handle T_INT case
 262     __ movl(Address(rdi, 0), rax);
 263     __ BIND(exit);
 264 
 265     // check that FPU stack is empty
 266     __ verify_FPU(0, "generate_call_stub");
 267 
 268     // pop parameters
 269     __ lea(rsp, rsp_after_call);
 270 
 271     // restore %mxcsr
 272     if (sse_save) {
 273       __ ldmxcsr(mxcsr_save);
 274     }
 275 
 276     // restore rdi, rsi and rbx,
 277     __ movptr(rbx, saved_rbx);
 278     __ movptr(rsi, saved_rsi);
 279     __ movptr(rdi, saved_rdi);
 280     __ addptr(rsp, 4*wordSize);
 281 
 282     // return
 283     __ pop(rbp);
 284     __ ret(0);
 285 
 286     // handle return types different from T_INT
 287     __ BIND(is_long);
 288     __ movl(Address(rdi, 0 * wordSize), rax);
 289     __ movl(Address(rdi, 1 * wordSize), rdx);
 290     __ jmp(exit);
 291 
 292     __ BIND(is_float);
 293     // interpreter uses xmm0 for return values
 294     if (UseSSE >= 1) {
 295       __ movflt(Address(rdi, 0), xmm0);
 296     } else {
 297       __ fstp_s(Address(rdi, 0));
 298     }
 299     __ jmp(exit);
 300 
 301     __ BIND(is_double);
 302     // interpreter uses xmm0 for return values
 303     if (UseSSE >= 2) {
 304       __ movdbl(Address(rdi, 0), xmm0);
 305     } else {
 306       __ fstp_d(Address(rdi, 0));
 307     }
 308     __ jmp(exit);
 309 
 310     return start;
 311   }
 312 
 313 
 314   //------------------------------------------------------------------------------------------------------------------------
 315   // Return point for a Java call if there's an exception thrown in Java code.
 316   // The exception is caught and transformed into a pending exception stored in
 317   // JavaThread that can be tested from within the VM.
 318   //
 319   // Note: Usually the parameters are removed by the callee. In case of an exception
 320   //       crossing an activation frame boundary, that is not the case if the callee
 321   //       is compiled code => need to setup the rsp.
 322   //
 323   // rax,: exception oop
 324 
 325   address generate_catch_exception() {
 326     StubCodeMark mark(this, "StubRoutines", "catch_exception");
 327     const Address rsp_after_call(rbp, -4 * wordSize); // same as in generate_call_stub()!
 328     const Address thread        (rbp,  9 * wordSize); // same as in generate_call_stub()!
 329     address start = __ pc();
 330 
 331     // get thread directly
 332     __ movptr(rcx, thread);
 333 #ifdef ASSERT
 334     // verify that threads correspond
 335     { Label L;
 336       __ get_thread(rbx);
 337       __ cmpptr(rbx, rcx);
 338       __ jcc(Assembler::equal, L);
 339       __ stop("StubRoutines::catch_exception: threads must correspond");
 340       __ bind(L);
 341     }
 342 #endif
 343     // set pending exception
 344     __ verify_oop(rax);
 345     __ movptr(Address(rcx, Thread::pending_exception_offset()), rax          );
 346     __ lea(Address(rcx, Thread::exception_file_offset   ()),
 347            ExternalAddress((address)__FILE__));
 348     __ movl(Address(rcx, Thread::exception_line_offset   ()), __LINE__ );
 349     // complete return to VM
 350     assert(StubRoutines::_call_stub_return_address != NULL, "_call_stub_return_address must have been generated before");
 351     __ jump(RuntimeAddress(StubRoutines::_call_stub_return_address));
 352 
 353     return start;
 354   }
 355 
 356 
 357   //------------------------------------------------------------------------------------------------------------------------
 358   // Continuation point for runtime calls returning with a pending exception.
 359   // The pending exception check happened in the runtime or native call stub.
 360   // The pending exception in Thread is converted into a Java-level exception.
 361   //
 362   // Contract with Java-level exception handlers:
 363   // rax: exception
 364   // rdx: throwing pc
 365   //
 366   // NOTE: At entry of this stub, exception-pc must be on stack !!
 367 
 368   address generate_forward_exception() {
 369     StubCodeMark mark(this, "StubRoutines", "forward exception");
 370     address start = __ pc();
 371     const Register thread = rcx;
 372 
 373     // other registers used in this stub
 374     const Register exception_oop = rax;
 375     const Register handler_addr  = rbx;
 376     const Register exception_pc  = rdx;
 377 
 378     // Upon entry, the sp points to the return address returning into Java
 379     // (interpreted or compiled) code; i.e., the return address becomes the
 380     // throwing pc.
 381     //
 382     // Arguments pushed before the runtime call are still on the stack but
 383     // the exception handler will reset the stack pointer -> ignore them.
 384     // A potential result in registers can be ignored as well.
 385 
 386 #ifdef ASSERT
 387     // make sure this code is only executed if there is a pending exception
 388     { Label L;
 389       __ get_thread(thread);
 390       __ cmpptr(Address(thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
 391       __ jcc(Assembler::notEqual, L);
 392       __ stop("StubRoutines::forward exception: no pending exception (1)");
 393       __ bind(L);
 394     }
 395 #endif
 396 
 397     // compute exception handler into rbx,
 398     __ get_thread(thread);
 399     __ movptr(exception_pc, Address(rsp, 0));
 400     BLOCK_COMMENT("call exception_handler_for_return_address");
 401     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address), thread, exception_pc);
 402     __ mov(handler_addr, rax);
 403 
 404     // setup rax & rdx, remove return address & clear pending exception
 405     __ get_thread(thread);
 406     __ pop(exception_pc);
 407     __ movptr(exception_oop, Address(thread, Thread::pending_exception_offset()));
 408     __ movptr(Address(thread, Thread::pending_exception_offset()), NULL_WORD);
 409 
 410 #ifdef ASSERT
 411     // make sure exception is set
 412     { Label L;
 413       __ testptr(exception_oop, exception_oop);
 414       __ jcc(Assembler::notEqual, L);
 415       __ stop("StubRoutines::forward exception: no pending exception (2)");
 416       __ bind(L);
 417     }
 418 #endif
 419 
 420     // Verify that there is really a valid exception in RAX.
 421     __ verify_oop(exception_oop);
 422 
 423     // continue at exception handler (return address removed)
 424     // rax: exception
 425     // rbx: exception handler
 426     // rdx: throwing pc
 427     __ jmp(handler_addr);
 428 
 429     return start;
 430   }
 431 
 432 
 433   //----------------------------------------------------------------------------------------------------
 434   // Implementation of int32_t atomic_xchg(int32_t exchange_value, volatile int32_t* dest)
 435   // used by Atomic::xchg(volatile int32_t* dest, int32_t exchange_value)
 436   //
 437   // xchg exists as far back as 8086, lock needed for MP only
 438   // Stack layout immediately after call:
 439   //
 440   // 0 [ret addr ] <--- rsp
 441   // 1 [  ex     ]
 442   // 2 [  dest   ]
 443   //
 444   // Result:   *dest <- ex, return (old *dest)
 445   //
 446   // Note: win32 does not currently use this code
 447 
 448   address generate_atomic_xchg() {
 449     StubCodeMark mark(this, "StubRoutines", "atomic_xchg");
 450     address start = __ pc();
 451 
 452     __ push(rdx);
 453     Address exchange(rsp, 2 * wordSize);
 454     Address dest_addr(rsp, 3 * wordSize);
 455     __ movl(rax, exchange);
 456     __ movptr(rdx, dest_addr);
 457     __ xchgl(rax, Address(rdx, 0));
 458     __ pop(rdx);
 459     __ ret(0);
 460 
 461     return start;
 462   }
 463 
 464   //----------------------------------------------------------------------------------------------------
 465   // Support for void verify_mxcsr()
 466   //
 467   // This routine is used with -Xcheck:jni to verify that native
 468   // JNI code does not return to Java code without restoring the
 469   // MXCSR register to our expected state.
 470 
 471 
 472   address generate_verify_mxcsr() {
 473     StubCodeMark mark(this, "StubRoutines", "verify_mxcsr");
 474     address start = __ pc();
 475 
 476     const Address mxcsr_save(rsp, 0);
 477 
 478     if (CheckJNICalls && UseSSE > 0 ) {
 479       Label ok_ret;
 480       ExternalAddress mxcsr_std(StubRoutines::addr_mxcsr_std());
 481       __ push(rax);
 482       __ subptr(rsp, wordSize);      // allocate a temp location
 483       __ stmxcsr(mxcsr_save);
 484       __ movl(rax, mxcsr_save);
 485       __ andl(rax, MXCSR_MASK);
 486       __ cmp32(rax, mxcsr_std);
 487       __ jcc(Assembler::equal, ok_ret);
 488 
 489       __ warn("MXCSR changed by native JNI code.");
 490 
 491       __ ldmxcsr(mxcsr_std);
 492 
 493       __ bind(ok_ret);
 494       __ addptr(rsp, wordSize);
 495       __ pop(rax);
 496     }
 497 
 498     __ ret(0);
 499 
 500     return start;
 501   }
 502 
 503 
 504   //---------------------------------------------------------------------------
 505   // Support for void verify_fpu_cntrl_wrd()
 506   //
 507   // This routine is used with -Xcheck:jni to verify that native
 508   // JNI code does not return to Java code without restoring the
 509   // FP control word to our expected state.
 510 
 511   address generate_verify_fpu_cntrl_wrd() {
 512     StubCodeMark mark(this, "StubRoutines", "verify_spcw");
 513     address start = __ pc();
 514 
 515     const Address fpu_cntrl_wrd_save(rsp, 0);
 516 
 517     if (CheckJNICalls) {
 518       Label ok_ret;
 519       __ push(rax);
 520       __ subptr(rsp, wordSize);      // allocate a temp location
 521       __ fnstcw(fpu_cntrl_wrd_save);
 522       __ movl(rax, fpu_cntrl_wrd_save);
 523       __ andl(rax, FPU_CNTRL_WRD_MASK);
 524       ExternalAddress fpu_std(StubRoutines::addr_fpu_cntrl_wrd_std());
 525       __ cmp32(rax, fpu_std);
 526       __ jcc(Assembler::equal, ok_ret);
 527 
 528       __ warn("Floating point control word changed by native JNI code.");
 529 
 530       __ fldcw(fpu_std);
 531 
 532       __ bind(ok_ret);
 533       __ addptr(rsp, wordSize);
 534       __ pop(rax);
 535     }
 536 
 537     __ ret(0);
 538 
 539     return start;
 540   }
 541 
 542   //---------------------------------------------------------------------------
 543   // Wrapper for slow-case handling of double-to-integer conversion
 544   // d2i or f2i fast case failed either because it is nan or because
 545   // of under/overflow.
 546   // Input:  FPU TOS: float value
 547   // Output: rax, (rdx): integer (long) result
 548 
 549   address generate_d2i_wrapper(BasicType t, address fcn) {
 550     StubCodeMark mark(this, "StubRoutines", "d2i_wrapper");
 551     address start = __ pc();
 552 
 553   // Capture info about frame layout
 554   enum layout { FPUState_off         = 0,
 555                 rbp_off              = FPUStateSizeInWords,
 556                 rdi_off,
 557                 rsi_off,
 558                 rcx_off,
 559                 rbx_off,
 560                 saved_argument_off,
 561                 saved_argument_off2, // 2nd half of double
 562                 framesize
 563   };
 564 
 565   assert(FPUStateSizeInWords == 27, "update stack layout");
 566 
 567     // Save outgoing argument to stack across push_FPU_state()
 568     __ subptr(rsp, wordSize * 2);
 569     __ fstp_d(Address(rsp, 0));
 570 
 571     // Save CPU & FPU state
 572     __ push(rbx);
 573     __ push(rcx);
 574     __ push(rsi);
 575     __ push(rdi);
 576     __ push(rbp);
 577     __ push_FPU_state();
 578 
 579     // push_FPU_state() resets the FP top of stack
 580     // Load original double into FP top of stack
 581     __ fld_d(Address(rsp, saved_argument_off * wordSize));
 582     // Store double into stack as outgoing argument
 583     __ subptr(rsp, wordSize*2);
 584     __ fst_d(Address(rsp, 0));
 585 
 586     // Prepare FPU for doing math in C-land
 587     __ empty_FPU_stack();
 588     // Call the C code to massage the double.  Result in EAX
 589     if (t == T_INT)
 590       { BLOCK_COMMENT("SharedRuntime::d2i"); }
 591     else if (t == T_LONG)
 592       { BLOCK_COMMENT("SharedRuntime::d2l"); }
 593     __ call_VM_leaf( fcn, 2 );
 594 
 595     // Restore CPU & FPU state
 596     __ pop_FPU_state();
 597     __ pop(rbp);
 598     __ pop(rdi);
 599     __ pop(rsi);
 600     __ pop(rcx);
 601     __ pop(rbx);
 602     __ addptr(rsp, wordSize * 2);
 603 
 604     __ ret(0);
 605 
 606     return start;
 607   }
 608   //---------------------------------------------------------------------------------------------------
 609 
 610   address generate_vector_mask(const char *stub_name, int32_t mask) {
 611     __ align(CodeEntryAlignment);
 612     StubCodeMark mark(this, "StubRoutines", stub_name);
 613     address start = __ pc();
 614 
 615     for (int i = 0; i < 16; i++) {
 616       __ emit_data(mask, relocInfo::none, 0);
 617     }
 618 
 619     return start;
 620   }
 621 
 622   address generate_vector_mask_long_double(const char *stub_name, int32_t maskhi, int32_t masklo) {
 623     __ align(CodeEntryAlignment);
 624     StubCodeMark mark(this, "StubRoutines", stub_name);
 625     address start = __ pc();
 626 
 627     for (int i = 0; i < 8; i++) {
 628       __ emit_data(masklo, relocInfo::none, 0);
 629       __ emit_data(maskhi, relocInfo::none, 0);
 630     }
 631 
 632     return start;
 633   }
 634 
 635   //----------------------------------------------------------------------------------------------------
 636 
 637   address generate_vector_byte_perm_mask(const char *stub_name) {
 638     __ align(CodeEntryAlignment);
 639     StubCodeMark mark(this, "StubRoutines", stub_name);
 640     address start = __ pc();
 641 
 642     __ emit_data(0x00000001, relocInfo::none, 0);
 643     __ emit_data(0x00000000, relocInfo::none, 0);
 644     __ emit_data(0x00000003, relocInfo::none, 0);
 645     __ emit_data(0x00000000, relocInfo::none, 0);
 646     __ emit_data(0x00000005, relocInfo::none, 0);
 647     __ emit_data(0x00000000, relocInfo::none, 0);
 648     __ emit_data(0x00000007, relocInfo::none, 0);
 649     __ emit_data(0x00000000, relocInfo::none, 0);
 650     __ emit_data(0x00000000, relocInfo::none, 0);
 651     __ emit_data(0x00000000, relocInfo::none, 0);
 652     __ emit_data(0x00000002, relocInfo::none, 0);
 653     __ emit_data(0x00000000, relocInfo::none, 0);
 654     __ emit_data(0x00000004, relocInfo::none, 0);
 655     __ emit_data(0x00000000, relocInfo::none, 0);
 656     __ emit_data(0x00000006, relocInfo::none, 0);
 657     __ emit_data(0x00000000, relocInfo::none, 0);
 658 
 659     return start;
 660   }
 661 
 662   //----------------------------------------------------------------------------------------------------
 663   // Non-destructive plausibility checks for oops
 664 
 665   address generate_verify_oop() {
 666     StubCodeMark mark(this, "StubRoutines", "verify_oop");
 667     address start = __ pc();
 668 
 669     // Incoming arguments on stack after saving rax,:
 670     //
 671     // [tos    ]: saved rdx
 672     // [tos + 1]: saved EFLAGS
 673     // [tos + 2]: return address
 674     // [tos + 3]: char* error message
 675     // [tos + 4]: oop   object to verify
 676     // [tos + 5]: saved rax, - saved by caller and bashed
 677 
 678     Label exit, error;
 679     __ pushf();
 680     __ incrementl(ExternalAddress((address) StubRoutines::verify_oop_count_addr()));
 681     __ push(rdx);                                // save rdx
 682     // make sure object is 'reasonable'
 683     __ movptr(rax, Address(rsp, 4 * wordSize));    // get object
 684     __ testptr(rax, rax);
 685     __ jcc(Assembler::zero, exit);               // if obj is NULL it is ok
 686 
 687     // Check if the oop is in the right area of memory
 688     const int oop_mask = Universe::verify_oop_mask();
 689     const int oop_bits = Universe::verify_oop_bits();
 690     __ mov(rdx, rax);
 691     __ andptr(rdx, oop_mask);
 692     __ cmpptr(rdx, oop_bits);
 693     __ jcc(Assembler::notZero, error);
 694 
 695     // make sure klass is 'reasonable', which is not zero.
 696     __ movptr(rax, Address(rax, oopDesc::klass_offset_in_bytes())); // get klass
 697     __ testptr(rax, rax);
 698     __ jcc(Assembler::zero, error);              // if klass is NULL it is broken
 699 
 700     // return if everything seems ok
 701     __ bind(exit);
 702     __ movptr(rax, Address(rsp, 5 * wordSize));  // get saved rax, back
 703     __ pop(rdx);                                 // restore rdx
 704     __ popf();                                   // restore EFLAGS
 705     __ ret(3 * wordSize);                        // pop arguments
 706 
 707     // handle errors
 708     __ bind(error);
 709     __ movptr(rax, Address(rsp, 5 * wordSize));  // get saved rax, back
 710     __ pop(rdx);                                 // get saved rdx back
 711     __ popf();                                   // get saved EFLAGS off stack -- will be ignored
 712     __ pusha();                                  // push registers (eip = return address & msg are already pushed)
 713     BLOCK_COMMENT("call MacroAssembler::debug");
 714     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 715     __ hlt();
 716     return start;
 717   }
 718 
 719 
 720   // Copy 64 bytes chunks
 721   //
 722   // Inputs:
 723   //   from        - source array address
 724   //   to_from     - destination array address - from
 725   //   qword_count - 8-bytes element count, negative
 726   //
 727   void xmm_copy_forward(Register from, Register to_from, Register qword_count) {
 728     assert( UseSSE >= 2, "supported cpu only" );
 729     Label L_copy_64_bytes_loop, L_copy_64_bytes, L_copy_8_bytes, L_exit;
 730 
 731     // Copy 64-byte chunks
 732     __ jmpb(L_copy_64_bytes);
 733     __ align(OptoLoopAlignment);
 734   __ BIND(L_copy_64_bytes_loop);
 735 
 736     if (UseUnalignedLoadStores) {
 737       if (UseAVX > 2) {
 738         __ evmovdqul(xmm0, Address(from, 0), Assembler::AVX_512bit);
 739         __ evmovdqul(Address(from, to_from, Address::times_1, 0), xmm0, Assembler::AVX_512bit);
 740       } else if (UseAVX == 2) {
 741         __ vmovdqu(xmm0, Address(from,  0));
 742         __ vmovdqu(Address(from, to_from, Address::times_1,  0), xmm0);
 743         __ vmovdqu(xmm1, Address(from, 32));
 744         __ vmovdqu(Address(from, to_from, Address::times_1, 32), xmm1);
 745       } else {
 746         __ movdqu(xmm0, Address(from, 0));
 747         __ movdqu(Address(from, to_from, Address::times_1, 0), xmm0);
 748         __ movdqu(xmm1, Address(from, 16));
 749         __ movdqu(Address(from, to_from, Address::times_1, 16), xmm1);
 750         __ movdqu(xmm2, Address(from, 32));
 751         __ movdqu(Address(from, to_from, Address::times_1, 32), xmm2);
 752         __ movdqu(xmm3, Address(from, 48));
 753         __ movdqu(Address(from, to_from, Address::times_1, 48), xmm3);
 754       }
 755     } else {
 756       __ movq(xmm0, Address(from, 0));
 757       __ movq(Address(from, to_from, Address::times_1, 0), xmm0);
 758       __ movq(xmm1, Address(from, 8));
 759       __ movq(Address(from, to_from, Address::times_1, 8), xmm1);
 760       __ movq(xmm2, Address(from, 16));
 761       __ movq(Address(from, to_from, Address::times_1, 16), xmm2);
 762       __ movq(xmm3, Address(from, 24));
 763       __ movq(Address(from, to_from, Address::times_1, 24), xmm3);
 764       __ movq(xmm4, Address(from, 32));
 765       __ movq(Address(from, to_from, Address::times_1, 32), xmm4);
 766       __ movq(xmm5, Address(from, 40));
 767       __ movq(Address(from, to_from, Address::times_1, 40), xmm5);
 768       __ movq(xmm6, Address(from, 48));
 769       __ movq(Address(from, to_from, Address::times_1, 48), xmm6);
 770       __ movq(xmm7, Address(from, 56));
 771       __ movq(Address(from, to_from, Address::times_1, 56), xmm7);
 772     }
 773 
 774     __ addl(from, 64);
 775   __ BIND(L_copy_64_bytes);
 776     __ subl(qword_count, 8);
 777     __ jcc(Assembler::greaterEqual, L_copy_64_bytes_loop);
 778 
 779     if (UseUnalignedLoadStores && (UseAVX == 2)) {
 780       // clean upper bits of YMM registers
 781       __ vpxor(xmm0, xmm0);
 782       __ vpxor(xmm1, xmm1);
 783     }
 784     __ addl(qword_count, 8);
 785     __ jccb(Assembler::zero, L_exit);
 786     //
 787     // length is too short, just copy qwords
 788     //
 789   __ BIND(L_copy_8_bytes);
 790     __ movq(xmm0, Address(from, 0));
 791     __ movq(Address(from, to_from, Address::times_1), xmm0);
 792     __ addl(from, 8);
 793     __ decrement(qword_count);
 794     __ jcc(Assembler::greater, L_copy_8_bytes);
 795   __ BIND(L_exit);
 796   }
 797 
 798   // Copy 64 bytes chunks
 799   //
 800   // Inputs:
 801   //   from        - source array address
 802   //   to_from     - destination array address - from
 803   //   qword_count - 8-bytes element count, negative
 804   //
 805   void mmx_copy_forward(Register from, Register to_from, Register qword_count) {
 806     assert( VM_Version::supports_mmx(), "supported cpu only" );
 807     Label L_copy_64_bytes_loop, L_copy_64_bytes, L_copy_8_bytes, L_exit;
 808     // Copy 64-byte chunks
 809     __ jmpb(L_copy_64_bytes);
 810     __ align(OptoLoopAlignment);
 811   __ BIND(L_copy_64_bytes_loop);
 812     __ movq(mmx0, Address(from, 0));
 813     __ movq(mmx1, Address(from, 8));
 814     __ movq(mmx2, Address(from, 16));
 815     __ movq(Address(from, to_from, Address::times_1, 0), mmx0);
 816     __ movq(mmx3, Address(from, 24));
 817     __ movq(Address(from, to_from, Address::times_1, 8), mmx1);
 818     __ movq(mmx4, Address(from, 32));
 819     __ movq(Address(from, to_from, Address::times_1, 16), mmx2);
 820     __ movq(mmx5, Address(from, 40));
 821     __ movq(Address(from, to_from, Address::times_1, 24), mmx3);
 822     __ movq(mmx6, Address(from, 48));
 823     __ movq(Address(from, to_from, Address::times_1, 32), mmx4);
 824     __ movq(mmx7, Address(from, 56));
 825     __ movq(Address(from, to_from, Address::times_1, 40), mmx5);
 826     __ movq(Address(from, to_from, Address::times_1, 48), mmx6);
 827     __ movq(Address(from, to_from, Address::times_1, 56), mmx7);
 828     __ addptr(from, 64);
 829   __ BIND(L_copy_64_bytes);
 830     __ subl(qword_count, 8);
 831     __ jcc(Assembler::greaterEqual, L_copy_64_bytes_loop);
 832     __ addl(qword_count, 8);
 833     __ jccb(Assembler::zero, L_exit);
 834     //
 835     // length is too short, just copy qwords
 836     //
 837   __ BIND(L_copy_8_bytes);
 838     __ movq(mmx0, Address(from, 0));
 839     __ movq(Address(from, to_from, Address::times_1), mmx0);
 840     __ addptr(from, 8);
 841     __ decrement(qword_count);
 842     __ jcc(Assembler::greater, L_copy_8_bytes);
 843   __ BIND(L_exit);
 844     __ emms();
 845   }
 846 
 847   address generate_disjoint_copy(BasicType t, bool aligned,
 848                                  Address::ScaleFactor sf,
 849                                  address* entry, const char *name,
 850                                  bool dest_uninitialized = false) {
 851     __ align(CodeEntryAlignment);
 852     StubCodeMark mark(this, "StubRoutines", name);
 853     address start = __ pc();
 854 
 855     Label L_0_count, L_exit, L_skip_align1, L_skip_align2, L_copy_byte;
 856     Label L_copy_2_bytes, L_copy_4_bytes, L_copy_64_bytes;
 857 
 858     int shift = Address::times_ptr - sf;
 859 
 860     const Register from     = rsi;  // source array address
 861     const Register to       = rdi;  // destination array address
 862     const Register count    = rcx;  // elements count
 863     const Register to_from  = to;   // (to - from)
 864     const Register saved_to = rdx;  // saved destination array address
 865 
 866     __ enter(); // required for proper stackwalking of RuntimeStub frame
 867     __ push(rsi);
 868     __ push(rdi);
 869     __ movptr(from , Address(rsp, 12+ 4));
 870     __ movptr(to   , Address(rsp, 12+ 8));
 871     __ movl(count, Address(rsp, 12+ 12));
 872 
 873     if (entry != NULL) {
 874       *entry = __ pc(); // Entry point from conjoint arraycopy stub.
 875       BLOCK_COMMENT("Entry:");
 876     }
 877 
 878     if (t == T_OBJECT) {
 879       __ testl(count, count);
 880       __ jcc(Assembler::zero, L_0_count);
 881     }
 882 
 883     DecoratorSet decorators = IN_HEAP | IS_ARRAY | ARRAYCOPY_DISJOINT;
 884     if (dest_uninitialized) {
 885       decorators |= IS_DEST_UNINITIALIZED;
 886     }
 887     if (aligned) {
 888       decorators |= ARRAYCOPY_ALIGNED;
 889     }
 890 
 891     BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
 892     bs->arraycopy_prologue(_masm, decorators, t, from, to, count);
 893     {
 894       bool add_entry = (t != T_OBJECT && (!aligned || t == T_INT));
 895       // UnsafeCopyMemory page error: continue after ucm
 896       UnsafeCopyMemoryMark ucmm(this, add_entry, true);
 897       __ subptr(to, from); // to --> to_from
 898       __ cmpl(count, 2<<shift); // Short arrays (< 8 bytes) copy by element
 899       __ jcc(Assembler::below, L_copy_4_bytes); // use unsigned cmp
 900       if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
 901         // align source address at 4 bytes address boundary
 902         if (t == T_BYTE) {
 903           // One byte misalignment happens only for byte arrays
 904           __ testl(from, 1);
 905           __ jccb(Assembler::zero, L_skip_align1);
 906           __ movb(rax, Address(from, 0));
 907           __ movb(Address(from, to_from, Address::times_1, 0), rax);
 908           __ increment(from);
 909           __ decrement(count);
 910         __ BIND(L_skip_align1);
 911         }
 912         // Two bytes misalignment happens only for byte and short (char) arrays
 913         __ testl(from, 2);
 914         __ jccb(Assembler::zero, L_skip_align2);
 915         __ movw(rax, Address(from, 0));
 916         __ movw(Address(from, to_from, Address::times_1, 0), rax);
 917         __ addptr(from, 2);
 918         __ subl(count, 1<<(shift-1));
 919       __ BIND(L_skip_align2);
 920       }
 921       if (!VM_Version::supports_mmx()) {
 922         __ mov(rax, count);      // save 'count'
 923         __ shrl(count, shift); // bytes count
 924         __ addptr(to_from, from);// restore 'to'
 925         __ rep_mov();
 926         __ subptr(to_from, from);// restore 'to_from'
 927         __ mov(count, rax);      // restore 'count'
 928         __ jmpb(L_copy_2_bytes); // all dwords were copied
 929       } else {
 930         if (!UseUnalignedLoadStores) {
 931           // align to 8 bytes, we know we are 4 byte aligned to start
 932           __ testptr(from, 4);
 933           __ jccb(Assembler::zero, L_copy_64_bytes);
 934           __ movl(rax, Address(from, 0));
 935           __ movl(Address(from, to_from, Address::times_1, 0), rax);
 936           __ addptr(from, 4);
 937           __ subl(count, 1<<shift);
 938          }
 939       __ BIND(L_copy_64_bytes);
 940         __ mov(rax, count);
 941         __ shrl(rax, shift+1);  // 8 bytes chunk count
 942         //
 943         // Copy 8-byte chunks through MMX registers, 8 per iteration of the loop
 944         //
 945         if (UseXMMForArrayCopy) {
 946           xmm_copy_forward(from, to_from, rax);
 947         } else {
 948           mmx_copy_forward(from, to_from, rax);
 949         }
 950       }
 951       // copy tailing dword
 952     __ BIND(L_copy_4_bytes);
 953       __ testl(count, 1<<shift);
 954       __ jccb(Assembler::zero, L_copy_2_bytes);
 955       __ movl(rax, Address(from, 0));
 956       __ movl(Address(from, to_from, Address::times_1, 0), rax);
 957       if (t == T_BYTE || t == T_SHORT) {
 958         __ addptr(from, 4);
 959       __ BIND(L_copy_2_bytes);
 960         // copy tailing word
 961         __ testl(count, 1<<(shift-1));
 962         __ jccb(Assembler::zero, L_copy_byte);
 963         __ movw(rax, Address(from, 0));
 964         __ movw(Address(from, to_from, Address::times_1, 0), rax);
 965         if (t == T_BYTE) {
 966           __ addptr(from, 2);
 967         __ BIND(L_copy_byte);
 968           // copy tailing byte
 969           __ testl(count, 1);
 970           __ jccb(Assembler::zero, L_exit);
 971           __ movb(rax, Address(from, 0));
 972           __ movb(Address(from, to_from, Address::times_1, 0), rax);
 973         __ BIND(L_exit);
 974         } else {
 975         __ BIND(L_copy_byte);
 976         }
 977       } else {
 978       __ BIND(L_copy_2_bytes);
 979       }
 980     }
 981 
 982     if (VM_Version::supports_mmx() && !UseXMMForArrayCopy) {
 983       __ emms();
 984     }
 985     __ movl(count, Address(rsp, 12+12)); // reread 'count'
 986     bs->arraycopy_epilogue(_masm, decorators, t, from, to, count);
 987 
 988     if (t == T_OBJECT) {
 989     __ BIND(L_0_count);
 990     }
 991     inc_copy_counter_np(t);
 992     __ pop(rdi);
 993     __ pop(rsi);
 994     __ leave(); // required for proper stackwalking of RuntimeStub frame
 995     __ vzeroupper();
 996     __ xorptr(rax, rax); // return 0
 997     __ ret(0);
 998     return start;
 999   }
1000 
1001 
1002   address generate_fill(BasicType t, bool aligned, const char *name) {
1003     __ align(CodeEntryAlignment);
1004     StubCodeMark mark(this, "StubRoutines", name);
1005     address start = __ pc();
1006 
1007     BLOCK_COMMENT("Entry:");
1008 
1009     const Register to       = rdi;  // source array address
1010     const Register value    = rdx;  // value
1011     const Register count    = rsi;  // elements count
1012 
1013     __ enter(); // required for proper stackwalking of RuntimeStub frame
1014     __ push(rsi);
1015     __ push(rdi);
1016     __ movptr(to   , Address(rsp, 12+ 4));
1017     __ movl(value, Address(rsp, 12+ 8));
1018     __ movl(count, Address(rsp, 12+ 12));
1019 
1020     __ generate_fill(t, aligned, to, value, count, rax, xmm0);
1021 
1022     __ pop(rdi);
1023     __ pop(rsi);
1024     __ leave(); // required for proper stackwalking of RuntimeStub frame
1025     __ ret(0);
1026     return start;
1027   }
1028 
1029   address generate_conjoint_copy(BasicType t, bool aligned,
1030                                  Address::ScaleFactor sf,
1031                                  address nooverlap_target,
1032                                  address* entry, const char *name,
1033                                  bool dest_uninitialized = false) {
1034     __ align(CodeEntryAlignment);
1035     StubCodeMark mark(this, "StubRoutines", name);
1036     address start = __ pc();
1037 
1038     Label L_0_count, L_exit, L_skip_align1, L_skip_align2, L_copy_byte;
1039     Label L_copy_2_bytes, L_copy_4_bytes, L_copy_8_bytes, L_copy_8_bytes_loop;
1040 
1041     int shift = Address::times_ptr - sf;
1042 
1043     const Register src   = rax;  // source array address
1044     const Register dst   = rdx;  // destination array address
1045     const Register from  = rsi;  // source array address
1046     const Register to    = rdi;  // destination array address
1047     const Register count = rcx;  // elements count
1048     const Register end   = rax;  // array end address
1049 
1050     __ enter(); // required for proper stackwalking of RuntimeStub frame
1051     __ push(rsi);
1052     __ push(rdi);
1053     __ movptr(src  , Address(rsp, 12+ 4));   // from
1054     __ movptr(dst  , Address(rsp, 12+ 8));   // to
1055     __ movl2ptr(count, Address(rsp, 12+12)); // count
1056 
1057     if (entry != NULL) {
1058       *entry = __ pc(); // Entry point from generic arraycopy stub.
1059       BLOCK_COMMENT("Entry:");
1060     }
1061 
1062     // nooverlap_target expects arguments in rsi and rdi.
1063     __ mov(from, src);
1064     __ mov(to  , dst);
1065 
1066     // arrays overlap test: dispatch to disjoint stub if necessary.
1067     RuntimeAddress nooverlap(nooverlap_target);
1068     __ cmpptr(dst, src);
1069     __ lea(end, Address(src, count, sf, 0)); // src + count * elem_size
1070     __ jump_cc(Assembler::belowEqual, nooverlap);
1071     __ cmpptr(dst, end);
1072     __ jump_cc(Assembler::aboveEqual, nooverlap);
1073 
1074     if (t == T_OBJECT) {
1075       __ testl(count, count);
1076       __ jcc(Assembler::zero, L_0_count);
1077     }
1078 
1079     DecoratorSet decorators = IN_HEAP | IS_ARRAY;
1080     if (dest_uninitialized) {
1081       decorators |= IS_DEST_UNINITIALIZED;
1082     }
1083     if (aligned) {
1084       decorators |= ARRAYCOPY_ALIGNED;
1085     }
1086 
1087     BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
1088     bs->arraycopy_prologue(_masm, decorators, t, from, to, count);
1089 
1090     {
1091       bool add_entry = (t != T_OBJECT && (!aligned || t == T_INT));
1092       // UnsafeCopyMemory page error: continue after ucm
1093       UnsafeCopyMemoryMark ucmm(this, add_entry, true);
1094       // copy from high to low
1095       __ cmpl(count, 2<<shift); // Short arrays (< 8 bytes) copy by element
1096       __ jcc(Assembler::below, L_copy_4_bytes); // use unsigned cmp
1097       if (t == T_BYTE || t == T_SHORT) {
1098         // Align the end of destination array at 4 bytes address boundary
1099         __ lea(end, Address(dst, count, sf, 0));
1100         if (t == T_BYTE) {
1101           // One byte misalignment happens only for byte arrays
1102           __ testl(end, 1);
1103           __ jccb(Assembler::zero, L_skip_align1);
1104           __ decrement(count);
1105           __ movb(rdx, Address(from, count, sf, 0));
1106           __ movb(Address(to, count, sf, 0), rdx);
1107         __ BIND(L_skip_align1);
1108         }
1109         // Two bytes misalignment happens only for byte and short (char) arrays
1110         __ testl(end, 2);
1111         __ jccb(Assembler::zero, L_skip_align2);
1112         __ subptr(count, 1<<(shift-1));
1113         __ movw(rdx, Address(from, count, sf, 0));
1114         __ movw(Address(to, count, sf, 0), rdx);
1115       __ BIND(L_skip_align2);
1116         __ cmpl(count, 2<<shift); // Short arrays (< 8 bytes) copy by element
1117         __ jcc(Assembler::below, L_copy_4_bytes);
1118       }
1119 
1120       if (!VM_Version::supports_mmx()) {
1121         __ std();
1122         __ mov(rax, count); // Save 'count'
1123         __ mov(rdx, to);    // Save 'to'
1124         __ lea(rsi, Address(from, count, sf, -4));
1125         __ lea(rdi, Address(to  , count, sf, -4));
1126         __ shrptr(count, shift); // bytes count
1127         __ rep_mov();
1128         __ cld();
1129         __ mov(count, rax); // restore 'count'
1130         __ andl(count, (1<<shift)-1);      // mask the number of rest elements
1131         __ movptr(from, Address(rsp, 12+4)); // reread 'from'
1132         __ mov(to, rdx);   // restore 'to'
1133         __ jmpb(L_copy_2_bytes); // all dword were copied
1134       } else {
1135         // Align to 8 bytes the end of array. It is aligned to 4 bytes already.
1136         __ testptr(end, 4);
1137         __ jccb(Assembler::zero, L_copy_8_bytes);
1138         __ subl(count, 1<<shift);
1139         __ movl(rdx, Address(from, count, sf, 0));
1140         __ movl(Address(to, count, sf, 0), rdx);
1141         __ jmpb(L_copy_8_bytes);
1142 
1143         __ align(OptoLoopAlignment);
1144         // Move 8 bytes
1145       __ BIND(L_copy_8_bytes_loop);
1146         if (UseXMMForArrayCopy) {
1147           __ movq(xmm0, Address(from, count, sf, 0));
1148           __ movq(Address(to, count, sf, 0), xmm0);
1149         } else {
1150           __ movq(mmx0, Address(from, count, sf, 0));
1151           __ movq(Address(to, count, sf, 0), mmx0);
1152         }
1153       __ BIND(L_copy_8_bytes);
1154         __ subl(count, 2<<shift);
1155         __ jcc(Assembler::greaterEqual, L_copy_8_bytes_loop);
1156         __ addl(count, 2<<shift);
1157         if (!UseXMMForArrayCopy) {
1158           __ emms();
1159         }
1160       }
1161     __ BIND(L_copy_4_bytes);
1162       // copy prefix qword
1163       __ testl(count, 1<<shift);
1164       __ jccb(Assembler::zero, L_copy_2_bytes);
1165       __ movl(rdx, Address(from, count, sf, -4));
1166       __ movl(Address(to, count, sf, -4), rdx);
1167 
1168       if (t == T_BYTE || t == T_SHORT) {
1169           __ subl(count, (1<<shift));
1170         __ BIND(L_copy_2_bytes);
1171           // copy prefix dword
1172           __ testl(count, 1<<(shift-1));
1173           __ jccb(Assembler::zero, L_copy_byte);
1174           __ movw(rdx, Address(from, count, sf, -2));
1175           __ movw(Address(to, count, sf, -2), rdx);
1176           if (t == T_BYTE) {
1177             __ subl(count, 1<<(shift-1));
1178           __ BIND(L_copy_byte);
1179             // copy prefix byte
1180             __ testl(count, 1);
1181             __ jccb(Assembler::zero, L_exit);
1182             __ movb(rdx, Address(from, 0));
1183             __ movb(Address(to, 0), rdx);
1184           __ BIND(L_exit);
1185           } else {
1186           __ BIND(L_copy_byte);
1187           }
1188       } else {
1189       __ BIND(L_copy_2_bytes);
1190       }
1191     }
1192 
1193     if (VM_Version::supports_mmx() && !UseXMMForArrayCopy) {
1194       __ emms();
1195     }
1196     __ movl2ptr(count, Address(rsp, 12+12)); // reread count
1197     bs->arraycopy_epilogue(_masm, decorators, t, from, to, count);
1198 
1199     if (t == T_OBJECT) {
1200     __ BIND(L_0_count);
1201     }
1202     inc_copy_counter_np(t);
1203     __ pop(rdi);
1204     __ pop(rsi);
1205     __ leave(); // required for proper stackwalking of RuntimeStub frame
1206     __ xorptr(rax, rax); // return 0
1207     __ ret(0);
1208     return start;
1209   }
1210 
1211 
1212   address generate_disjoint_long_copy(address* entry, const char *name) {
1213     __ align(CodeEntryAlignment);
1214     StubCodeMark mark(this, "StubRoutines", name);
1215     address start = __ pc();
1216 
1217     Label L_copy_8_bytes, L_copy_8_bytes_loop;
1218     const Register from       = rax;  // source array address
1219     const Register to         = rdx;  // destination array address
1220     const Register count      = rcx;  // elements count
1221     const Register to_from    = rdx;  // (to - from)
1222 
1223     __ enter(); // required for proper stackwalking of RuntimeStub frame
1224     __ movptr(from , Address(rsp, 8+0));       // from
1225     __ movptr(to   , Address(rsp, 8+4));       // to
1226     __ movl2ptr(count, Address(rsp, 8+8));     // count
1227 
1228     *entry = __ pc(); // Entry point from conjoint arraycopy stub.
1229     BLOCK_COMMENT("Entry:");
1230 
1231     {
1232       // UnsafeCopyMemory page error: continue after ucm
1233       UnsafeCopyMemoryMark ucmm(this, true, true);
1234       __ subptr(to, from); // to --> to_from
1235       if (VM_Version::supports_mmx()) {
1236         if (UseXMMForArrayCopy) {
1237           xmm_copy_forward(from, to_from, count);
1238         } else {
1239           mmx_copy_forward(from, to_from, count);
1240         }
1241       } else {
1242         __ jmpb(L_copy_8_bytes);
1243         __ align(OptoLoopAlignment);
1244       __ BIND(L_copy_8_bytes_loop);
1245         __ fild_d(Address(from, 0));
1246         __ fistp_d(Address(from, to_from, Address::times_1));
1247         __ addptr(from, 8);
1248       __ BIND(L_copy_8_bytes);
1249         __ decrement(count);
1250         __ jcc(Assembler::greaterEqual, L_copy_8_bytes_loop);
1251       }
1252     }
1253     if (VM_Version::supports_mmx() && !UseXMMForArrayCopy) {
1254       __ emms();
1255     }
1256     inc_copy_counter_np(T_LONG);
1257     __ leave(); // required for proper stackwalking of RuntimeStub frame
1258     __ vzeroupper();
1259     __ xorptr(rax, rax); // return 0
1260     __ ret(0);
1261     return start;
1262   }
1263 
1264   address generate_conjoint_long_copy(address nooverlap_target,
1265                                       address* entry, const char *name) {
1266     __ align(CodeEntryAlignment);
1267     StubCodeMark mark(this, "StubRoutines", name);
1268     address start = __ pc();
1269 
1270     Label L_copy_8_bytes, L_copy_8_bytes_loop;
1271     const Register from       = rax;  // source array address
1272     const Register to         = rdx;  // destination array address
1273     const Register count      = rcx;  // elements count
1274     const Register end_from   = rax;  // source array end address
1275 
1276     __ enter(); // required for proper stackwalking of RuntimeStub frame
1277     __ movptr(from , Address(rsp, 8+0));       // from
1278     __ movptr(to   , Address(rsp, 8+4));       // to
1279     __ movl2ptr(count, Address(rsp, 8+8));     // count
1280 
1281     *entry = __ pc(); // Entry point from generic arraycopy stub.
1282     BLOCK_COMMENT("Entry:");
1283 
1284     // arrays overlap test
1285     __ cmpptr(to, from);
1286     RuntimeAddress nooverlap(nooverlap_target);
1287     __ jump_cc(Assembler::belowEqual, nooverlap);
1288     __ lea(end_from, Address(from, count, Address::times_8, 0));
1289     __ cmpptr(to, end_from);
1290     __ movptr(from, Address(rsp, 8));  // from
1291     __ jump_cc(Assembler::aboveEqual, nooverlap);
1292 
1293     {
1294       // UnsafeCopyMemory page error: continue after ucm
1295       UnsafeCopyMemoryMark ucmm(this, true, true);
1296 
1297       __ jmpb(L_copy_8_bytes);
1298 
1299       __ align(OptoLoopAlignment);
1300     __ BIND(L_copy_8_bytes_loop);
1301       if (VM_Version::supports_mmx()) {
1302         if (UseXMMForArrayCopy) {
1303           __ movq(xmm0, Address(from, count, Address::times_8));
1304           __ movq(Address(to, count, Address::times_8), xmm0);
1305         } else {
1306           __ movq(mmx0, Address(from, count, Address::times_8));
1307           __ movq(Address(to, count, Address::times_8), mmx0);
1308         }
1309       } else {
1310         __ fild_d(Address(from, count, Address::times_8));
1311         __ fistp_d(Address(to, count, Address::times_8));
1312       }
1313     __ BIND(L_copy_8_bytes);
1314       __ decrement(count);
1315       __ jcc(Assembler::greaterEqual, L_copy_8_bytes_loop);
1316 
1317     }
1318     if (VM_Version::supports_mmx() && !UseXMMForArrayCopy) {
1319       __ emms();
1320     }
1321     inc_copy_counter_np(T_LONG);
1322     __ leave(); // required for proper stackwalking of RuntimeStub frame
1323     __ xorptr(rax, rax); // return 0
1324     __ ret(0);
1325     return start;
1326   }
1327 
1328 
1329   // Helper for generating a dynamic type check.
1330   // The sub_klass must be one of {rbx, rdx, rsi}.
1331   // The temp is killed.
1332   void generate_type_check(Register sub_klass,
1333                            Address& super_check_offset_addr,
1334                            Address& super_klass_addr,
1335                            Register temp,
1336                            Label* L_success, Label* L_failure) {
1337     BLOCK_COMMENT("type_check:");
1338 
1339     Label L_fallthrough;
1340 #define LOCAL_JCC(assembler_con, label_ptr)                             \
1341     if (label_ptr != NULL)  __ jcc(assembler_con, *(label_ptr));        \
1342     else                    __ jcc(assembler_con, L_fallthrough) /*omit semi*/
1343 
1344     // The following is a strange variation of the fast path which requires
1345     // one less register, because needed values are on the argument stack.
1346     // __ check_klass_subtype_fast_path(sub_klass, *super_klass*, temp,
1347     //                                  L_success, L_failure, NULL);
1348     assert_different_registers(sub_klass, temp);
1349 
1350     int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1351 
1352     // if the pointers are equal, we are done (e.g., String[] elements)
1353     __ cmpptr(sub_klass, super_klass_addr);
1354     LOCAL_JCC(Assembler::equal, L_success);
1355 
1356     // check the supertype display:
1357     __ movl2ptr(temp, super_check_offset_addr);
1358     Address super_check_addr(sub_klass, temp, Address::times_1, 0);
1359     __ movptr(temp, super_check_addr); // load displayed supertype
1360     __ cmpptr(temp, super_klass_addr); // test the super type
1361     LOCAL_JCC(Assembler::equal, L_success);
1362 
1363     // if it was a primary super, we can just fail immediately
1364     __ cmpl(super_check_offset_addr, sc_offset);
1365     LOCAL_JCC(Assembler::notEqual, L_failure);
1366 
1367     // The repne_scan instruction uses fixed registers, which will get spilled.
1368     // We happen to know this works best when super_klass is in rax.
1369     Register super_klass = temp;
1370     __ movptr(super_klass, super_klass_addr);
1371     __ check_klass_subtype_slow_path(sub_klass, super_klass, noreg, noreg,
1372                                      L_success, L_failure);
1373 
1374     __ bind(L_fallthrough);
1375 
1376     if (L_success == NULL) { BLOCK_COMMENT("L_success:"); }
1377     if (L_failure == NULL) { BLOCK_COMMENT("L_failure:"); }
1378 
1379 #undef LOCAL_JCC
1380   }
1381 
1382   //
1383   //  Generate checkcasting array copy stub
1384   //
1385   //  Input:
1386   //    4(rsp)   - source array address
1387   //    8(rsp)   - destination array address
1388   //   12(rsp)   - element count, can be zero
1389   //   16(rsp)   - size_t ckoff (super_check_offset)
1390   //   20(rsp)   - oop ckval (super_klass)
1391   //
1392   //  Output:
1393   //    rax, ==  0  -  success
1394   //    rax, == -1^K - failure, where K is partial transfer count
1395   //
1396   address generate_checkcast_copy(const char *name, address* entry, bool dest_uninitialized = false) {
1397     __ align(CodeEntryAlignment);
1398     StubCodeMark mark(this, "StubRoutines", name);
1399     address start = __ pc();
1400 
1401     Label L_load_element, L_store_element, L_do_card_marks, L_done;
1402 
1403     // register use:
1404     //  rax, rdx, rcx -- loop control (end_from, end_to, count)
1405     //  rdi, rsi      -- element access (oop, klass)
1406     //  rbx,           -- temp
1407     const Register from       = rax;    // source array address
1408     const Register to         = rdx;    // destination array address
1409     const Register length     = rcx;    // elements count
1410     const Register elem       = rdi;    // each oop copied
1411     const Register elem_klass = rsi;    // each elem._klass (sub_klass)
1412     const Register temp       = rbx;    // lone remaining temp
1413 
1414     __ enter(); // required for proper stackwalking of RuntimeStub frame
1415 
1416     __ push(rsi);
1417     __ push(rdi);
1418     __ push(rbx);
1419 
1420     Address   from_arg(rsp, 16+ 4);     // from
1421     Address     to_arg(rsp, 16+ 8);     // to
1422     Address length_arg(rsp, 16+12);     // elements count
1423     Address  ckoff_arg(rsp, 16+16);     // super_check_offset
1424     Address  ckval_arg(rsp, 16+20);     // super_klass
1425 
1426     // Load up:
1427     __ movptr(from,     from_arg);
1428     __ movptr(to,         to_arg);
1429     __ movl2ptr(length, length_arg);
1430 
1431     if (entry != NULL) {
1432       *entry = __ pc(); // Entry point from generic arraycopy stub.
1433       BLOCK_COMMENT("Entry:");
1434     }
1435 
1436     //---------------------------------------------------------------
1437     // Assembler stub will be used for this call to arraycopy
1438     // if the two arrays are subtypes of Object[] but the
1439     // destination array type is not equal to or a supertype
1440     // of the source type.  Each element must be separately
1441     // checked.
1442 
1443     // Loop-invariant addresses.  They are exclusive end pointers.
1444     Address end_from_addr(from, length, Address::times_ptr, 0);
1445     Address   end_to_addr(to,   length, Address::times_ptr, 0);
1446 
1447     Register end_from = from;           // re-use
1448     Register end_to   = to;             // re-use
1449     Register count    = length;         // re-use
1450 
1451     // Loop-variant addresses.  They assume post-incremented count < 0.
1452     Address from_element_addr(end_from, count, Address::times_ptr, 0);
1453     Address   to_element_addr(end_to,   count, Address::times_ptr, 0);
1454     Address elem_klass_addr(elem, oopDesc::klass_offset_in_bytes());
1455 
1456     DecoratorSet decorators = IN_HEAP | IS_ARRAY | ARRAYCOPY_CHECKCAST;
1457     if (dest_uninitialized) {
1458       decorators |= IS_DEST_UNINITIALIZED;
1459     }
1460 
1461     BasicType type = T_OBJECT;
1462     BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
1463     bs->arraycopy_prologue(_masm, decorators, type, from, to, count);
1464 
1465     // Copy from low to high addresses, indexed from the end of each array.
1466     __ lea(end_from, end_from_addr);
1467     __ lea(end_to,   end_to_addr);
1468     assert(length == count, "");        // else fix next line:
1469     __ negptr(count);                   // negate and test the length
1470     __ jccb(Assembler::notZero, L_load_element);
1471 
1472     // Empty array:  Nothing to do.
1473     __ xorptr(rax, rax);                  // return 0 on (trivial) success
1474     __ jmp(L_done);
1475 
1476     // ======== begin loop ========
1477     // (Loop is rotated; its entry is L_load_element.)
1478     // Loop control:
1479     //   for (count = -count; count != 0; count++)
1480     // Base pointers src, dst are biased by 8*count,to last element.
1481     __ align(OptoLoopAlignment);
1482 
1483     __ BIND(L_store_element);
1484     __ movptr(to_element_addr, elem);     // store the oop
1485     __ increment(count);                // increment the count toward zero
1486     __ jccb(Assembler::zero, L_do_card_marks);
1487 
1488     // ======== loop entry is here ========
1489     __ BIND(L_load_element);
1490     __ movptr(elem, from_element_addr);   // load the oop
1491     __ testptr(elem, elem);
1492     __ jccb(Assembler::zero, L_store_element);
1493 
1494     // (Could do a trick here:  Remember last successful non-null
1495     // element stored and make a quick oop equality check on it.)
1496 
1497     __ movptr(elem_klass, elem_klass_addr); // query the object klass
1498     generate_type_check(elem_klass, ckoff_arg, ckval_arg, temp,
1499                         &L_store_element, NULL);
1500     // (On fall-through, we have failed the element type check.)
1501     // ======== end loop ========
1502 
1503     // It was a real error; we must depend on the caller to finish the job.
1504     // Register "count" = -1 * number of *remaining* oops, length_arg = *total* oops.
1505     // Emit GC store barriers for the oops we have copied (length_arg + count),
1506     // and report their number to the caller.
1507     assert_different_registers(to, count, rax);
1508     Label L_post_barrier;
1509     __ addl(count, length_arg);         // transfers = (length - remaining)
1510     __ movl2ptr(rax, count);            // save the value
1511     __ notptr(rax);                     // report (-1^K) to caller (does not affect flags)
1512     __ jccb(Assembler::notZero, L_post_barrier);
1513     __ jmp(L_done); // K == 0, nothing was copied, skip post barrier
1514 
1515     // Come here on success only.
1516     __ BIND(L_do_card_marks);
1517     __ xorptr(rax, rax);                // return 0 on success
1518     __ movl2ptr(count, length_arg);
1519 
1520     __ BIND(L_post_barrier);
1521     __ movptr(to, to_arg);              // reload
1522     bs->arraycopy_epilogue(_masm, decorators, type, from, to, count);
1523 
1524     // Common exit point (success or failure).
1525     __ BIND(L_done);
1526     __ pop(rbx);
1527     __ pop(rdi);
1528     __ pop(rsi);
1529     inc_counter_np(SharedRuntime::_checkcast_array_copy_ctr);
1530     __ leave(); // required for proper stackwalking of RuntimeStub frame
1531     __ ret(0);
1532 
1533     return start;
1534   }
1535 
1536   //
1537   //  Generate 'unsafe' array copy stub
1538   //  Though just as safe as the other stubs, it takes an unscaled
1539   //  size_t argument instead of an element count.
1540   //
1541   //  Input:
1542   //    4(rsp)   - source array address
1543   //    8(rsp)   - destination array address
1544   //   12(rsp)   - byte count, can be zero
1545   //
1546   //  Output:
1547   //    rax, ==  0  -  success
1548   //    rax, == -1  -  need to call System.arraycopy
1549   //
1550   // Examines the alignment of the operands and dispatches
1551   // to a long, int, short, or byte copy loop.
1552   //
1553   address generate_unsafe_copy(const char *name,
1554                                address byte_copy_entry,
1555                                address short_copy_entry,
1556                                address int_copy_entry,
1557                                address long_copy_entry) {
1558 
1559     Label L_long_aligned, L_int_aligned, L_short_aligned;
1560 
1561     __ align(CodeEntryAlignment);
1562     StubCodeMark mark(this, "StubRoutines", name);
1563     address start = __ pc();
1564 
1565     const Register from       = rax;  // source array address
1566     const Register to         = rdx;  // destination array address
1567     const Register count      = rcx;  // elements count
1568 
1569     __ enter(); // required for proper stackwalking of RuntimeStub frame
1570     __ push(rsi);
1571     __ push(rdi);
1572     Address  from_arg(rsp, 12+ 4);      // from
1573     Address    to_arg(rsp, 12+ 8);      // to
1574     Address count_arg(rsp, 12+12);      // byte count
1575 
1576     // Load up:
1577     __ movptr(from ,  from_arg);
1578     __ movptr(to   ,    to_arg);
1579     __ movl2ptr(count, count_arg);
1580 
1581     // bump this on entry, not on exit:
1582     inc_counter_np(SharedRuntime::_unsafe_array_copy_ctr);
1583 
1584     const Register bits = rsi;
1585     __ mov(bits, from);
1586     __ orptr(bits, to);
1587     __ orptr(bits, count);
1588 
1589     __ testl(bits, BytesPerLong-1);
1590     __ jccb(Assembler::zero, L_long_aligned);
1591 
1592     __ testl(bits, BytesPerInt-1);
1593     __ jccb(Assembler::zero, L_int_aligned);
1594 
1595     __ testl(bits, BytesPerShort-1);
1596     __ jump_cc(Assembler::notZero, RuntimeAddress(byte_copy_entry));
1597 
1598     __ BIND(L_short_aligned);
1599     __ shrptr(count, LogBytesPerShort); // size => short_count
1600     __ movl(count_arg, count);          // update 'count'
1601     __ jump(RuntimeAddress(short_copy_entry));
1602 
1603     __ BIND(L_int_aligned);
1604     __ shrptr(count, LogBytesPerInt); // size => int_count
1605     __ movl(count_arg, count);          // update 'count'
1606     __ jump(RuntimeAddress(int_copy_entry));
1607 
1608     __ BIND(L_long_aligned);
1609     __ shrptr(count, LogBytesPerLong); // size => qword_count
1610     __ movl(count_arg, count);          // update 'count'
1611     __ pop(rdi); // Do pops here since jlong_arraycopy stub does not do it.
1612     __ pop(rsi);
1613     __ jump(RuntimeAddress(long_copy_entry));
1614 
1615     return start;
1616   }
1617 
1618 
1619   // Perform range checks on the proposed arraycopy.
1620   // Smashes src_pos and dst_pos.  (Uses them up for temps.)
1621   void arraycopy_range_checks(Register src,
1622                               Register src_pos,
1623                               Register dst,
1624                               Register dst_pos,
1625                               Address& length,
1626                               Label& L_failed) {
1627     BLOCK_COMMENT("arraycopy_range_checks:");
1628     const Register src_end = src_pos;   // source array end position
1629     const Register dst_end = dst_pos;   // destination array end position
1630     __ addl(src_end, length); // src_pos + length
1631     __ addl(dst_end, length); // dst_pos + length
1632 
1633     //  if (src_pos + length > arrayOop(src)->length() ) FAIL;
1634     __ cmpl(src_end, Address(src, arrayOopDesc::length_offset_in_bytes()));
1635     __ jcc(Assembler::above, L_failed);
1636 
1637     //  if (dst_pos + length > arrayOop(dst)->length() ) FAIL;
1638     __ cmpl(dst_end, Address(dst, arrayOopDesc::length_offset_in_bytes()));
1639     __ jcc(Assembler::above, L_failed);
1640 
1641     BLOCK_COMMENT("arraycopy_range_checks done");
1642   }
1643 
1644 
1645   //
1646   //  Generate generic array copy stubs
1647   //
1648   //  Input:
1649   //     4(rsp)    -  src oop
1650   //     8(rsp)    -  src_pos
1651   //    12(rsp)    -  dst oop
1652   //    16(rsp)    -  dst_pos
1653   //    20(rsp)    -  element count
1654   //
1655   //  Output:
1656   //    rax, ==  0  -  success
1657   //    rax, == -1^K - failure, where K is partial transfer count
1658   //
1659   address generate_generic_copy(const char *name,
1660                                 address entry_jbyte_arraycopy,
1661                                 address entry_jshort_arraycopy,
1662                                 address entry_jint_arraycopy,
1663                                 address entry_oop_arraycopy,
1664                                 address entry_jlong_arraycopy,
1665                                 address entry_checkcast_arraycopy) {
1666     Label L_failed, L_failed_0, L_objArray;
1667 
1668     { int modulus = CodeEntryAlignment;
1669       int target  = modulus - 5; // 5 = sizeof jmp(L_failed)
1670       int advance = target - (__ offset() % modulus);
1671       if (advance < 0)  advance += modulus;
1672       if (advance > 0)  __ nop(advance);
1673     }
1674     StubCodeMark mark(this, "StubRoutines", name);
1675 
1676     // Short-hop target to L_failed.  Makes for denser prologue code.
1677     __ BIND(L_failed_0);
1678     __ jmp(L_failed);
1679     assert(__ offset() % CodeEntryAlignment == 0, "no further alignment needed");
1680 
1681     __ align(CodeEntryAlignment);
1682     address start = __ pc();
1683 
1684     __ enter(); // required for proper stackwalking of RuntimeStub frame
1685     __ push(rsi);
1686     __ push(rdi);
1687 
1688     // bump this on entry, not on exit:
1689     inc_counter_np(SharedRuntime::_generic_array_copy_ctr);
1690 
1691     // Input values
1692     Address SRC     (rsp, 12+ 4);
1693     Address SRC_POS (rsp, 12+ 8);
1694     Address DST     (rsp, 12+12);
1695     Address DST_POS (rsp, 12+16);
1696     Address LENGTH  (rsp, 12+20);
1697 
1698     //-----------------------------------------------------------------------
1699     // Assembler stub will be used for this call to arraycopy
1700     // if the following conditions are met:
1701     //
1702     // (1) src and dst must not be null.
1703     // (2) src_pos must not be negative.
1704     // (3) dst_pos must not be negative.
1705     // (4) length  must not be negative.
1706     // (5) src klass and dst klass should be the same and not NULL.
1707     // (6) src and dst should be arrays.
1708     // (7) src_pos + length must not exceed length of src.
1709     // (8) dst_pos + length must not exceed length of dst.
1710     //
1711 
1712     const Register src     = rax;       // source array oop
1713     const Register src_pos = rsi;
1714     const Register dst     = rdx;       // destination array oop
1715     const Register dst_pos = rdi;
1716     const Register length  = rcx;       // transfer count
1717 
1718     //  if (src == NULL) return -1;
1719     __ movptr(src, SRC);      // src oop
1720     __ testptr(src, src);
1721     __ jccb(Assembler::zero, L_failed_0);
1722 
1723     //  if (src_pos < 0) return -1;
1724     __ movl2ptr(src_pos, SRC_POS);  // src_pos
1725     __ testl(src_pos, src_pos);
1726     __ jccb(Assembler::negative, L_failed_0);
1727 
1728     //  if (dst == NULL) return -1;
1729     __ movptr(dst, DST);      // dst oop
1730     __ testptr(dst, dst);
1731     __ jccb(Assembler::zero, L_failed_0);
1732 
1733     //  if (dst_pos < 0) return -1;
1734     __ movl2ptr(dst_pos, DST_POS);  // dst_pos
1735     __ testl(dst_pos, dst_pos);
1736     __ jccb(Assembler::negative, L_failed_0);
1737 
1738     //  if (length < 0) return -1;
1739     __ movl2ptr(length, LENGTH);   // length
1740     __ testl(length, length);
1741     __ jccb(Assembler::negative, L_failed_0);
1742 
1743     //  if (src->klass() == NULL) return -1;
1744     Address src_klass_addr(src, oopDesc::klass_offset_in_bytes());
1745     Address dst_klass_addr(dst, oopDesc::klass_offset_in_bytes());
1746     const Register rcx_src_klass = rcx;    // array klass
1747     __ movptr(rcx_src_klass, Address(src, oopDesc::klass_offset_in_bytes()));
1748 
1749 #ifdef ASSERT
1750     //  assert(src->klass() != NULL);
1751     BLOCK_COMMENT("assert klasses not null");
1752     { Label L1, L2;
1753       __ testptr(rcx_src_klass, rcx_src_klass);
1754       __ jccb(Assembler::notZero, L2);   // it is broken if klass is NULL
1755       __ bind(L1);
1756       __ stop("broken null klass");
1757       __ bind(L2);
1758       __ cmpptr(dst_klass_addr, (int32_t)NULL_WORD);
1759       __ jccb(Assembler::equal, L1);      // this would be broken also
1760       BLOCK_COMMENT("assert done");
1761     }
1762 #endif //ASSERT
1763 
1764     // Load layout helper (32-bits)
1765     //
1766     //  |array_tag|     | header_size | element_type |     |log2_element_size|
1767     // 32        30    24            16              8     2                 0
1768     //
1769     //   array_tag: typeArray = 0x3, objArray = 0x2, non-array = 0x0
1770     //
1771 
1772     int lh_offset = in_bytes(Klass::layout_helper_offset());
1773     Address src_klass_lh_addr(rcx_src_klass, lh_offset);
1774 
1775     // Handle objArrays completely differently...
1776     jint objArray_lh = Klass::array_layout_helper(T_OBJECT);
1777     __ cmpl(src_klass_lh_addr, objArray_lh);
1778     __ jcc(Assembler::equal, L_objArray);
1779 
1780     //  if (src->klass() != dst->klass()) return -1;
1781     __ cmpptr(rcx_src_klass, dst_klass_addr);
1782     __ jccb(Assembler::notEqual, L_failed_0);
1783 
1784     const Register rcx_lh = rcx;  // layout helper
1785     assert(rcx_lh == rcx_src_klass, "known alias");
1786     __ movl(rcx_lh, src_klass_lh_addr);
1787 
1788     //  if (!src->is_Array()) return -1;
1789     __ cmpl(rcx_lh, Klass::_lh_neutral_value);
1790     __ jcc(Assembler::greaterEqual, L_failed_0); // signed cmp
1791 
1792     // At this point, it is known to be a typeArray (array_tag 0x3).
1793 #ifdef ASSERT
1794     { Label L;
1795       __ cmpl(rcx_lh, (Klass::_lh_array_tag_type_value << Klass::_lh_array_tag_shift));
1796       __ jcc(Assembler::greaterEqual, L); // signed cmp
1797       __ stop("must be a primitive array");
1798       __ bind(L);
1799     }
1800 #endif
1801 
1802     assert_different_registers(src, src_pos, dst, dst_pos, rcx_lh);
1803     arraycopy_range_checks(src, src_pos, dst, dst_pos, LENGTH, L_failed);
1804 
1805     // TypeArrayKlass
1806     //
1807     // src_addr = (src + array_header_in_bytes()) + (src_pos << log2elemsize);
1808     // dst_addr = (dst + array_header_in_bytes()) + (dst_pos << log2elemsize);
1809     //
1810     const Register rsi_offset = rsi; // array offset
1811     const Register src_array  = src; // src array offset
1812     const Register dst_array  = dst; // dst array offset
1813     const Register rdi_elsize = rdi; // log2 element size
1814 
1815     __ mov(rsi_offset, rcx_lh);
1816     __ shrptr(rsi_offset, Klass::_lh_header_size_shift);
1817     __ andptr(rsi_offset, Klass::_lh_header_size_mask);   // array_offset
1818     __ addptr(src_array, rsi_offset);  // src array offset
1819     __ addptr(dst_array, rsi_offset);  // dst array offset
1820     __ andptr(rcx_lh, Klass::_lh_log2_element_size_mask); // log2 elsize
1821 
1822     // next registers should be set before the jump to corresponding stub
1823     const Register from       = src; // source array address
1824     const Register to         = dst; // destination array address
1825     const Register count      = rcx; // elements count
1826     // some of them should be duplicated on stack
1827 #define FROM   Address(rsp, 12+ 4)
1828 #define TO     Address(rsp, 12+ 8)   // Not used now
1829 #define COUNT  Address(rsp, 12+12)   // Only for oop arraycopy
1830 
1831     BLOCK_COMMENT("scale indexes to element size");
1832     __ movl2ptr(rsi, SRC_POS);  // src_pos
1833     __ shlptr(rsi);             // src_pos << rcx (log2 elsize)
1834     assert(src_array == from, "");
1835     __ addptr(from, rsi);       // from = src_array + SRC_POS << log2 elsize
1836     __ movl2ptr(rdi, DST_POS);  // dst_pos
1837     __ shlptr(rdi);             // dst_pos << rcx (log2 elsize)
1838     assert(dst_array == to, "");
1839     __ addptr(to,  rdi);        // to   = dst_array + DST_POS << log2 elsize
1840     __ movptr(FROM, from);      // src_addr
1841     __ mov(rdi_elsize, rcx_lh); // log2 elsize
1842     __ movl2ptr(count, LENGTH); // elements count
1843 
1844     BLOCK_COMMENT("choose copy loop based on element size");
1845     __ cmpl(rdi_elsize, 0);
1846 
1847     __ jump_cc(Assembler::equal, RuntimeAddress(entry_jbyte_arraycopy));
1848     __ cmpl(rdi_elsize, LogBytesPerShort);
1849     __ jump_cc(Assembler::equal, RuntimeAddress(entry_jshort_arraycopy));
1850     __ cmpl(rdi_elsize, LogBytesPerInt);
1851     __ jump_cc(Assembler::equal, RuntimeAddress(entry_jint_arraycopy));
1852 #ifdef ASSERT
1853     __ cmpl(rdi_elsize, LogBytesPerLong);
1854     __ jccb(Assembler::notEqual, L_failed);
1855 #endif
1856     __ pop(rdi); // Do pops here since jlong_arraycopy stub does not do it.
1857     __ pop(rsi);
1858     __ jump(RuntimeAddress(entry_jlong_arraycopy));
1859 
1860   __ BIND(L_failed);
1861     __ xorptr(rax, rax);
1862     __ notptr(rax); // return -1
1863     __ pop(rdi);
1864     __ pop(rsi);
1865     __ leave(); // required for proper stackwalking of RuntimeStub frame
1866     __ ret(0);
1867 
1868     // ObjArrayKlass
1869   __ BIND(L_objArray);
1870     // live at this point:  rcx_src_klass, src[_pos], dst[_pos]
1871 
1872     Label L_plain_copy, L_checkcast_copy;
1873     //  test array classes for subtyping
1874     __ cmpptr(rcx_src_klass, dst_klass_addr); // usual case is exact equality
1875     __ jccb(Assembler::notEqual, L_checkcast_copy);
1876 
1877     // Identically typed arrays can be copied without element-wise checks.
1878     assert_different_registers(src, src_pos, dst, dst_pos, rcx_src_klass);
1879     arraycopy_range_checks(src, src_pos, dst, dst_pos, LENGTH, L_failed);
1880 
1881   __ BIND(L_plain_copy);
1882     __ movl2ptr(count, LENGTH); // elements count
1883     __ movl2ptr(src_pos, SRC_POS);  // reload src_pos
1884     __ lea(from, Address(src, src_pos, Address::times_ptr,
1885                  arrayOopDesc::base_offset_in_bytes(T_OBJECT))); // src_addr
1886     __ movl2ptr(dst_pos, DST_POS);  // reload dst_pos
1887     __ lea(to,   Address(dst, dst_pos, Address::times_ptr,
1888                  arrayOopDesc::base_offset_in_bytes(T_OBJECT))); // dst_addr
1889     __ movptr(FROM,  from);   // src_addr
1890     __ movptr(TO,    to);     // dst_addr
1891     __ movl(COUNT, count);  // count
1892     __ jump(RuntimeAddress(entry_oop_arraycopy));
1893 
1894   __ BIND(L_checkcast_copy);
1895     // live at this point:  rcx_src_klass, dst[_pos], src[_pos]
1896     {
1897       // Handy offsets:
1898       int  ek_offset = in_bytes(ObjArrayKlass::element_klass_offset());
1899       int sco_offset = in_bytes(Klass::super_check_offset_offset());
1900 
1901       Register rsi_dst_klass = rsi;
1902       Register rdi_temp      = rdi;
1903       assert(rsi_dst_klass == src_pos, "expected alias w/ src_pos");
1904       assert(rdi_temp      == dst_pos, "expected alias w/ dst_pos");
1905       Address dst_klass_lh_addr(rsi_dst_klass, lh_offset);
1906 
1907       // Before looking at dst.length, make sure dst is also an objArray.
1908       __ movptr(rsi_dst_klass, dst_klass_addr);
1909       __ cmpl(dst_klass_lh_addr, objArray_lh);
1910       __ jccb(Assembler::notEqual, L_failed);
1911 
1912       // It is safe to examine both src.length and dst.length.
1913       __ movl2ptr(src_pos, SRC_POS);        // reload rsi
1914       arraycopy_range_checks(src, src_pos, dst, dst_pos, LENGTH, L_failed);
1915       // (Now src_pos and dst_pos are killed, but not src and dst.)
1916 
1917       // We'll need this temp (don't forget to pop it after the type check).
1918       __ push(rbx);
1919       Register rbx_src_klass = rbx;
1920 
1921       __ mov(rbx_src_klass, rcx_src_klass); // spill away from rcx
1922       __ movptr(rsi_dst_klass, dst_klass_addr);
1923       Address super_check_offset_addr(rsi_dst_klass, sco_offset);
1924       Label L_fail_array_check;
1925       generate_type_check(rbx_src_klass,
1926                           super_check_offset_addr, dst_klass_addr,
1927                           rdi_temp, NULL, &L_fail_array_check);
1928       // (On fall-through, we have passed the array type check.)
1929       __ pop(rbx);
1930       __ jmp(L_plain_copy);
1931 
1932       __ BIND(L_fail_array_check);
1933       // Reshuffle arguments so we can call checkcast_arraycopy:
1934 
1935       // match initial saves for checkcast_arraycopy
1936       // push(rsi);    // already done; see above
1937       // push(rdi);    // already done; see above
1938       // push(rbx);    // already done; see above
1939 
1940       // Marshal outgoing arguments now, freeing registers.
1941       Address   from_arg(rsp, 16+ 4);   // from
1942       Address     to_arg(rsp, 16+ 8);   // to
1943       Address length_arg(rsp, 16+12);   // elements count
1944       Address  ckoff_arg(rsp, 16+16);   // super_check_offset
1945       Address  ckval_arg(rsp, 16+20);   // super_klass
1946 
1947       Address SRC_POS_arg(rsp, 16+ 8);
1948       Address DST_POS_arg(rsp, 16+16);
1949       Address  LENGTH_arg(rsp, 16+20);
1950       // push rbx, changed the incoming offsets (why not just use rbp,??)
1951       // assert(SRC_POS_arg.disp() == SRC_POS.disp() + 4, "");
1952 
1953       __ movptr(rbx, Address(rsi_dst_klass, ek_offset));
1954       __ movl2ptr(length, LENGTH_arg);    // reload elements count
1955       __ movl2ptr(src_pos, SRC_POS_arg);  // reload src_pos
1956       __ movl2ptr(dst_pos, DST_POS_arg);  // reload dst_pos
1957 
1958       __ movptr(ckval_arg, rbx);          // destination element type
1959       __ movl(rbx, Address(rbx, sco_offset));
1960       __ movl(ckoff_arg, rbx);          // corresponding class check offset
1961 
1962       __ movl(length_arg, length);      // outgoing length argument
1963 
1964       __ lea(from, Address(src, src_pos, Address::times_ptr,
1965                             arrayOopDesc::base_offset_in_bytes(T_OBJECT)));
1966       __ movptr(from_arg, from);
1967 
1968       __ lea(to, Address(dst, dst_pos, Address::times_ptr,
1969                           arrayOopDesc::base_offset_in_bytes(T_OBJECT)));
1970       __ movptr(to_arg, to);
1971       __ jump(RuntimeAddress(entry_checkcast_arraycopy));
1972     }
1973 
1974     return start;
1975   }
1976 
1977   void generate_arraycopy_stubs() {
1978     address entry;
1979     address entry_jbyte_arraycopy;
1980     address entry_jshort_arraycopy;
1981     address entry_jint_arraycopy;
1982     address entry_oop_arraycopy;
1983     address entry_jlong_arraycopy;
1984     address entry_checkcast_arraycopy;
1985 
1986     StubRoutines::_arrayof_jbyte_disjoint_arraycopy =
1987         generate_disjoint_copy(T_BYTE,  true, Address::times_1, &entry,
1988                                "arrayof_jbyte_disjoint_arraycopy");
1989     StubRoutines::_arrayof_jbyte_arraycopy =
1990         generate_conjoint_copy(T_BYTE,  true, Address::times_1,  entry,
1991                                NULL, "arrayof_jbyte_arraycopy");
1992     StubRoutines::_jbyte_disjoint_arraycopy =
1993         generate_disjoint_copy(T_BYTE, false, Address::times_1, &entry,
1994                                "jbyte_disjoint_arraycopy");
1995     StubRoutines::_jbyte_arraycopy =
1996         generate_conjoint_copy(T_BYTE, false, Address::times_1,  entry,
1997                                &entry_jbyte_arraycopy, "jbyte_arraycopy");
1998 
1999     StubRoutines::_arrayof_jshort_disjoint_arraycopy =
2000         generate_disjoint_copy(T_SHORT,  true, Address::times_2, &entry,
2001                                "arrayof_jshort_disjoint_arraycopy");
2002     StubRoutines::_arrayof_jshort_arraycopy =
2003         generate_conjoint_copy(T_SHORT,  true, Address::times_2,  entry,
2004                                NULL, "arrayof_jshort_arraycopy");
2005     StubRoutines::_jshort_disjoint_arraycopy =
2006         generate_disjoint_copy(T_SHORT, false, Address::times_2, &entry,
2007                                "jshort_disjoint_arraycopy");
2008     StubRoutines::_jshort_arraycopy =
2009         generate_conjoint_copy(T_SHORT, false, Address::times_2,  entry,
2010                                &entry_jshort_arraycopy, "jshort_arraycopy");
2011 
2012     // Next arrays are always aligned on 4 bytes at least.
2013     StubRoutines::_jint_disjoint_arraycopy =
2014         generate_disjoint_copy(T_INT, true, Address::times_4, &entry,
2015                                "jint_disjoint_arraycopy");
2016     StubRoutines::_jint_arraycopy =
2017         generate_conjoint_copy(T_INT, true, Address::times_4,  entry,
2018                                &entry_jint_arraycopy, "jint_arraycopy");
2019 
2020     StubRoutines::_oop_disjoint_arraycopy =
2021         generate_disjoint_copy(T_OBJECT, true, Address::times_ptr, &entry,
2022                                "oop_disjoint_arraycopy");
2023     StubRoutines::_oop_arraycopy =
2024         generate_conjoint_copy(T_OBJECT, true, Address::times_ptr,  entry,
2025                                &entry_oop_arraycopy, "oop_arraycopy");
2026 
2027     StubRoutines::_oop_disjoint_arraycopy_uninit =
2028         generate_disjoint_copy(T_OBJECT, true, Address::times_ptr, &entry,
2029                                "oop_disjoint_arraycopy_uninit",
2030                                /*dest_uninitialized*/true);
2031     StubRoutines::_oop_arraycopy_uninit =
2032         generate_conjoint_copy(T_OBJECT, true, Address::times_ptr,  entry,
2033                                NULL, "oop_arraycopy_uninit",
2034                                /*dest_uninitialized*/true);
2035 
2036     StubRoutines::_jlong_disjoint_arraycopy =
2037         generate_disjoint_long_copy(&entry, "jlong_disjoint_arraycopy");
2038     StubRoutines::_jlong_arraycopy =
2039         generate_conjoint_long_copy(entry, &entry_jlong_arraycopy,
2040                                     "jlong_arraycopy");
2041 
2042     StubRoutines::_jbyte_fill = generate_fill(T_BYTE, false, "jbyte_fill");
2043     StubRoutines::_jshort_fill = generate_fill(T_SHORT, false, "jshort_fill");
2044     StubRoutines::_jint_fill = generate_fill(T_INT, false, "jint_fill");
2045     StubRoutines::_arrayof_jbyte_fill = generate_fill(T_BYTE, true, "arrayof_jbyte_fill");
2046     StubRoutines::_arrayof_jshort_fill = generate_fill(T_SHORT, true, "arrayof_jshort_fill");
2047     StubRoutines::_arrayof_jint_fill = generate_fill(T_INT, true, "arrayof_jint_fill");
2048 
2049     StubRoutines::_arrayof_jint_disjoint_arraycopy       = StubRoutines::_jint_disjoint_arraycopy;
2050     StubRoutines::_arrayof_oop_disjoint_arraycopy        = StubRoutines::_oop_disjoint_arraycopy;
2051     StubRoutines::_arrayof_oop_disjoint_arraycopy_uninit = StubRoutines::_oop_disjoint_arraycopy_uninit;
2052     StubRoutines::_arrayof_jlong_disjoint_arraycopy      = StubRoutines::_jlong_disjoint_arraycopy;
2053 
2054     StubRoutines::_arrayof_jint_arraycopy       = StubRoutines::_jint_arraycopy;
2055     StubRoutines::_arrayof_oop_arraycopy        = StubRoutines::_oop_arraycopy;
2056     StubRoutines::_arrayof_oop_arraycopy_uninit = StubRoutines::_oop_arraycopy_uninit;
2057     StubRoutines::_arrayof_jlong_arraycopy      = StubRoutines::_jlong_arraycopy;
2058 
2059     StubRoutines::_checkcast_arraycopy =
2060         generate_checkcast_copy("checkcast_arraycopy", &entry_checkcast_arraycopy);
2061     StubRoutines::_checkcast_arraycopy_uninit =
2062         generate_checkcast_copy("checkcast_arraycopy_uninit", NULL, /*dest_uninitialized*/true);
2063 
2064     StubRoutines::_unsafe_arraycopy =
2065         generate_unsafe_copy("unsafe_arraycopy",
2066                                entry_jbyte_arraycopy,
2067                                entry_jshort_arraycopy,
2068                                entry_jint_arraycopy,
2069                                entry_jlong_arraycopy);
2070 
2071     StubRoutines::_generic_arraycopy =
2072         generate_generic_copy("generic_arraycopy",
2073                                entry_jbyte_arraycopy,
2074                                entry_jshort_arraycopy,
2075                                entry_jint_arraycopy,
2076                                entry_oop_arraycopy,
2077                                entry_jlong_arraycopy,
2078                                entry_checkcast_arraycopy);
2079   }
2080 
2081   // AES intrinsic stubs
2082   enum {AESBlockSize = 16};
2083 
2084   address generate_key_shuffle_mask() {
2085     __ align(16);
2086     StubCodeMark mark(this, "StubRoutines", "key_shuffle_mask");
2087     address start = __ pc();
2088     __ emit_data(0x00010203, relocInfo::none, 0 );
2089     __ emit_data(0x04050607, relocInfo::none, 0 );
2090     __ emit_data(0x08090a0b, relocInfo::none, 0 );
2091     __ emit_data(0x0c0d0e0f, relocInfo::none, 0 );
2092     return start;
2093   }
2094 
2095   address generate_counter_shuffle_mask() {
2096     __ align(16);
2097     StubCodeMark mark(this, "StubRoutines", "counter_shuffle_mask");
2098     address start = __ pc();
2099     __ emit_data(0x0c0d0e0f, relocInfo::none, 0);
2100     __ emit_data(0x08090a0b, relocInfo::none, 0);
2101     __ emit_data(0x04050607, relocInfo::none, 0);
2102     __ emit_data(0x00010203, relocInfo::none, 0);
2103     return start;
2104   }
2105 
2106   // Utility routine for loading a 128-bit key word in little endian format
2107   // can optionally specify that the shuffle mask is already in an xmmregister
2108   void load_key(XMMRegister xmmdst, Register key, int offset, XMMRegister xmm_shuf_mask=NULL) {
2109     __ movdqu(xmmdst, Address(key, offset));
2110     if (xmm_shuf_mask != NULL) {
2111       __ pshufb(xmmdst, xmm_shuf_mask);
2112     } else {
2113       __ pshufb(xmmdst, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2114     }
2115   }
2116 
2117   // aesenc using specified key+offset
2118   // can optionally specify that the shuffle mask is already in an xmmregister
2119   void aes_enc_key(XMMRegister xmmdst, XMMRegister xmmtmp, Register key, int offset, XMMRegister xmm_shuf_mask=NULL) {
2120     load_key(xmmtmp, key, offset, xmm_shuf_mask);
2121     __ aesenc(xmmdst, xmmtmp);
2122   }
2123 
2124   // aesdec using specified key+offset
2125   // can optionally specify that the shuffle mask is already in an xmmregister
2126   void aes_dec_key(XMMRegister xmmdst, XMMRegister xmmtmp, Register key, int offset, XMMRegister xmm_shuf_mask=NULL) {
2127     load_key(xmmtmp, key, offset, xmm_shuf_mask);
2128     __ aesdec(xmmdst, xmmtmp);
2129   }
2130 
2131   // Utility routine for increase 128bit counter (iv in CTR mode)
2132   //  XMM_128bit,  D3, D2, D1, D0
2133   void inc_counter(Register reg, XMMRegister xmmdst, int inc_delta, Label& next_block) {
2134     __ pextrd(reg, xmmdst, 0x0);
2135     __ addl(reg, inc_delta);
2136     __ pinsrd(xmmdst, reg, 0x0);
2137     __ jcc(Assembler::carryClear, next_block); // jump if no carry
2138 
2139     __ pextrd(reg, xmmdst, 0x01); // Carry-> D1
2140     __ addl(reg, 0x01);
2141     __ pinsrd(xmmdst, reg, 0x01);
2142     __ jcc(Assembler::carryClear, next_block); // jump if no carry
2143 
2144     __ pextrd(reg, xmmdst, 0x02); // Carry-> D2
2145     __ addl(reg, 0x01);
2146     __ pinsrd(xmmdst, reg, 0x02);
2147     __ jcc(Assembler::carryClear, next_block); // jump if no carry
2148 
2149     __ pextrd(reg, xmmdst, 0x03); // Carry -> D3
2150     __ addl(reg, 0x01);
2151     __ pinsrd(xmmdst, reg, 0x03);
2152 
2153     __ BIND(next_block);          // next instruction
2154   }
2155 
2156 
2157   // Arguments:
2158   //
2159   // Inputs:
2160   //   c_rarg0   - source byte array address
2161   //   c_rarg1   - destination byte array address
2162   //   c_rarg2   - K (key) in little endian int array
2163   //
2164   address generate_aescrypt_encryptBlock() {
2165     assert(UseAES, "need AES instructions and misaligned SSE support");
2166     __ align(CodeEntryAlignment);
2167     StubCodeMark mark(this, "StubRoutines", "aescrypt_encryptBlock");
2168     Label L_doLast;
2169     address start = __ pc();
2170 
2171     const Register from        = rdx;      // source array address
2172     const Register to          = rdx;      // destination array address
2173     const Register key         = rcx;      // key array address
2174     const Register keylen      = rax;
2175     const Address  from_param(rbp, 8+0);
2176     const Address  to_param  (rbp, 8+4);
2177     const Address  key_param (rbp, 8+8);
2178 
2179     const XMMRegister xmm_result = xmm0;
2180     const XMMRegister xmm_key_shuf_mask = xmm1;
2181     const XMMRegister xmm_temp1  = xmm2;
2182     const XMMRegister xmm_temp2  = xmm3;
2183     const XMMRegister xmm_temp3  = xmm4;
2184     const XMMRegister xmm_temp4  = xmm5;
2185 
2186     __ enter();   // required for proper stackwalking of RuntimeStub frame
2187 
2188     __ movptr(from, from_param);
2189     __ movptr(key, key_param);
2190 
2191     // keylen could be only {11, 13, 15} * 4 = {44, 52, 60}
2192     __ movl(keylen, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
2193 
2194     __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2195     __ movdqu(xmm_result, Address(from, 0));  // get 16 bytes of input
2196     __ movptr(to, to_param);
2197 
2198     // For encryption, the java expanded key ordering is just what we need
2199 
2200     load_key(xmm_temp1, key, 0x00, xmm_key_shuf_mask);
2201     __ pxor(xmm_result, xmm_temp1);
2202 
2203     load_key(xmm_temp1, key, 0x10, xmm_key_shuf_mask);
2204     load_key(xmm_temp2, key, 0x20, xmm_key_shuf_mask);
2205     load_key(xmm_temp3, key, 0x30, xmm_key_shuf_mask);
2206     load_key(xmm_temp4, key, 0x40, xmm_key_shuf_mask);
2207 
2208     __ aesenc(xmm_result, xmm_temp1);
2209     __ aesenc(xmm_result, xmm_temp2);
2210     __ aesenc(xmm_result, xmm_temp3);
2211     __ aesenc(xmm_result, xmm_temp4);
2212 
2213     load_key(xmm_temp1, key, 0x50, xmm_key_shuf_mask);
2214     load_key(xmm_temp2, key, 0x60, xmm_key_shuf_mask);
2215     load_key(xmm_temp3, key, 0x70, xmm_key_shuf_mask);
2216     load_key(xmm_temp4, key, 0x80, xmm_key_shuf_mask);
2217 
2218     __ aesenc(xmm_result, xmm_temp1);
2219     __ aesenc(xmm_result, xmm_temp2);
2220     __ aesenc(xmm_result, xmm_temp3);
2221     __ aesenc(xmm_result, xmm_temp4);
2222 
2223     load_key(xmm_temp1, key, 0x90, xmm_key_shuf_mask);
2224     load_key(xmm_temp2, key, 0xa0, xmm_key_shuf_mask);
2225 
2226     __ cmpl(keylen, 44);
2227     __ jccb(Assembler::equal, L_doLast);
2228 
2229     __ aesenc(xmm_result, xmm_temp1);
2230     __ aesenc(xmm_result, xmm_temp2);
2231 
2232     load_key(xmm_temp1, key, 0xb0, xmm_key_shuf_mask);
2233     load_key(xmm_temp2, key, 0xc0, xmm_key_shuf_mask);
2234 
2235     __ cmpl(keylen, 52);
2236     __ jccb(Assembler::equal, L_doLast);
2237 
2238     __ aesenc(xmm_result, xmm_temp1);
2239     __ aesenc(xmm_result, xmm_temp2);
2240 
2241     load_key(xmm_temp1, key, 0xd0, xmm_key_shuf_mask);
2242     load_key(xmm_temp2, key, 0xe0, xmm_key_shuf_mask);
2243 
2244     __ BIND(L_doLast);
2245     __ aesenc(xmm_result, xmm_temp1);
2246     __ aesenclast(xmm_result, xmm_temp2);
2247     __ movdqu(Address(to, 0), xmm_result);        // store the result
2248     __ xorptr(rax, rax); // return 0
2249     __ leave(); // required for proper stackwalking of RuntimeStub frame
2250     __ ret(0);
2251 
2252     return start;
2253   }
2254 
2255 
2256   // Arguments:
2257   //
2258   // Inputs:
2259   //   c_rarg0   - source byte array address
2260   //   c_rarg1   - destination byte array address
2261   //   c_rarg2   - K (key) in little endian int array
2262   //
2263   address generate_aescrypt_decryptBlock() {
2264     assert(UseAES, "need AES instructions and misaligned SSE support");
2265     __ align(CodeEntryAlignment);
2266     StubCodeMark mark(this, "StubRoutines", "aescrypt_decryptBlock");
2267     Label L_doLast;
2268     address start = __ pc();
2269 
2270     const Register from        = rdx;      // source array address
2271     const Register to          = rdx;      // destination array address
2272     const Register key         = rcx;      // key array address
2273     const Register keylen      = rax;
2274     const Address  from_param(rbp, 8+0);
2275     const Address  to_param  (rbp, 8+4);
2276     const Address  key_param (rbp, 8+8);
2277 
2278     const XMMRegister xmm_result = xmm0;
2279     const XMMRegister xmm_key_shuf_mask = xmm1;
2280     const XMMRegister xmm_temp1  = xmm2;
2281     const XMMRegister xmm_temp2  = xmm3;
2282     const XMMRegister xmm_temp3  = xmm4;
2283     const XMMRegister xmm_temp4  = xmm5;
2284 
2285     __ enter(); // required for proper stackwalking of RuntimeStub frame
2286 
2287     __ movptr(from, from_param);
2288     __ movptr(key, key_param);
2289 
2290     // keylen could be only {11, 13, 15} * 4 = {44, 52, 60}
2291     __ movl(keylen, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
2292 
2293     __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2294     __ movdqu(xmm_result, Address(from, 0));
2295     __ movptr(to, to_param);
2296 
2297     // for decryption java expanded key ordering is rotated one position from what we want
2298     // so we start from 0x10 here and hit 0x00 last
2299     // we don't know if the key is aligned, hence not using load-execute form
2300     load_key(xmm_temp1, key, 0x10, xmm_key_shuf_mask);
2301     load_key(xmm_temp2, key, 0x20, xmm_key_shuf_mask);
2302     load_key(xmm_temp3, key, 0x30, xmm_key_shuf_mask);
2303     load_key(xmm_temp4, key, 0x40, xmm_key_shuf_mask);
2304 
2305     __ pxor  (xmm_result, xmm_temp1);
2306     __ aesdec(xmm_result, xmm_temp2);
2307     __ aesdec(xmm_result, xmm_temp3);
2308     __ aesdec(xmm_result, xmm_temp4);
2309 
2310     load_key(xmm_temp1, key, 0x50, xmm_key_shuf_mask);
2311     load_key(xmm_temp2, key, 0x60, xmm_key_shuf_mask);
2312     load_key(xmm_temp3, key, 0x70, xmm_key_shuf_mask);
2313     load_key(xmm_temp4, key, 0x80, xmm_key_shuf_mask);
2314 
2315     __ aesdec(xmm_result, xmm_temp1);
2316     __ aesdec(xmm_result, xmm_temp2);
2317     __ aesdec(xmm_result, xmm_temp3);
2318     __ aesdec(xmm_result, xmm_temp4);
2319 
2320     load_key(xmm_temp1, key, 0x90, xmm_key_shuf_mask);
2321     load_key(xmm_temp2, key, 0xa0, xmm_key_shuf_mask);
2322     load_key(xmm_temp3, key, 0x00, xmm_key_shuf_mask);
2323 
2324     __ cmpl(keylen, 44);
2325     __ jccb(Assembler::equal, L_doLast);
2326 
2327     __ aesdec(xmm_result, xmm_temp1);
2328     __ aesdec(xmm_result, xmm_temp2);
2329 
2330     load_key(xmm_temp1, key, 0xb0, xmm_key_shuf_mask);
2331     load_key(xmm_temp2, key, 0xc0, xmm_key_shuf_mask);
2332 
2333     __ cmpl(keylen, 52);
2334     __ jccb(Assembler::equal, L_doLast);
2335 
2336     __ aesdec(xmm_result, xmm_temp1);
2337     __ aesdec(xmm_result, xmm_temp2);
2338 
2339     load_key(xmm_temp1, key, 0xd0, xmm_key_shuf_mask);
2340     load_key(xmm_temp2, key, 0xe0, xmm_key_shuf_mask);
2341 
2342     __ BIND(L_doLast);
2343     __ aesdec(xmm_result, xmm_temp1);
2344     __ aesdec(xmm_result, xmm_temp2);
2345 
2346     // for decryption the aesdeclast operation is always on key+0x00
2347     __ aesdeclast(xmm_result, xmm_temp3);
2348     __ movdqu(Address(to, 0), xmm_result);  // store the result
2349     __ xorptr(rax, rax); // return 0
2350     __ leave(); // required for proper stackwalking of RuntimeStub frame
2351     __ ret(0);
2352 
2353     return start;
2354   }
2355 
2356   void handleSOERegisters(bool saving) {
2357     const int saveFrameSizeInBytes = 4 * wordSize;
2358     const Address saved_rbx     (rbp, -3 * wordSize);
2359     const Address saved_rsi     (rbp, -2 * wordSize);
2360     const Address saved_rdi     (rbp, -1 * wordSize);
2361 
2362     if (saving) {
2363       __ subptr(rsp, saveFrameSizeInBytes);
2364       __ movptr(saved_rsi, rsi);
2365       __ movptr(saved_rdi, rdi);
2366       __ movptr(saved_rbx, rbx);
2367     } else {
2368       // restoring
2369       __ movptr(rsi, saved_rsi);
2370       __ movptr(rdi, saved_rdi);
2371       __ movptr(rbx, saved_rbx);
2372     }
2373   }
2374 
2375   // Arguments:
2376   //
2377   // Inputs:
2378   //   c_rarg0   - source byte array address
2379   //   c_rarg1   - destination byte array address
2380   //   c_rarg2   - K (key) in little endian int array
2381   //   c_rarg3   - r vector byte array address
2382   //   c_rarg4   - input length
2383   //
2384   // Output:
2385   //   rax       - input length
2386   //
2387   address generate_cipherBlockChaining_encryptAESCrypt() {
2388     assert(UseAES, "need AES instructions and misaligned SSE support");
2389     __ align(CodeEntryAlignment);
2390     StubCodeMark mark(this, "StubRoutines", "cipherBlockChaining_encryptAESCrypt");
2391     address start = __ pc();
2392 
2393     Label L_exit, L_key_192_256, L_key_256, L_loopTop_128, L_loopTop_192, L_loopTop_256;
2394     const Register from        = rsi;      // source array address
2395     const Register to          = rdx;      // destination array address
2396     const Register key         = rcx;      // key array address
2397     const Register rvec        = rdi;      // r byte array initialized from initvector array address
2398                                            // and left with the results of the last encryption block
2399     const Register len_reg     = rbx;      // src len (must be multiple of blocksize 16)
2400     const Register pos         = rax;
2401 
2402     // xmm register assignments for the loops below
2403     const XMMRegister xmm_result = xmm0;
2404     const XMMRegister xmm_temp   = xmm1;
2405     // first 6 keys preloaded into xmm2-xmm7
2406     const int XMM_REG_NUM_KEY_FIRST = 2;
2407     const int XMM_REG_NUM_KEY_LAST  = 7;
2408     const XMMRegister xmm_key0   = as_XMMRegister(XMM_REG_NUM_KEY_FIRST);
2409 
2410     __ enter(); // required for proper stackwalking of RuntimeStub frame
2411     handleSOERegisters(true /*saving*/);
2412 
2413     // load registers from incoming parameters
2414     const Address  from_param(rbp, 8+0);
2415     const Address  to_param  (rbp, 8+4);
2416     const Address  key_param (rbp, 8+8);
2417     const Address  rvec_param (rbp, 8+12);
2418     const Address  len_param  (rbp, 8+16);
2419     __ movptr(from , from_param);
2420     __ movptr(to   , to_param);
2421     __ movptr(key  , key_param);
2422     __ movptr(rvec , rvec_param);
2423     __ movptr(len_reg , len_param);
2424 
2425     const XMMRegister xmm_key_shuf_mask = xmm_temp;  // used temporarily to swap key bytes up front
2426     __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2427     // load up xmm regs 2 thru 7 with keys 0-5
2428     for (int rnum = XMM_REG_NUM_KEY_FIRST, offset = 0x00; rnum  <= XMM_REG_NUM_KEY_LAST; rnum++) {
2429       load_key(as_XMMRegister(rnum), key, offset, xmm_key_shuf_mask);
2430       offset += 0x10;
2431     }
2432 
2433     __ movdqu(xmm_result, Address(rvec, 0x00));   // initialize xmm_result with r vec
2434 
2435     // now split to different paths depending on the keylen (len in ints of AESCrypt.KLE array (52=192, or 60=256))
2436     __ movl(rax, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
2437     __ cmpl(rax, 44);
2438     __ jcc(Assembler::notEqual, L_key_192_256);
2439 
2440     // 128 bit code follows here
2441     __ movl(pos, 0);
2442     __ align(OptoLoopAlignment);
2443     __ BIND(L_loopTop_128);
2444     __ movdqu(xmm_temp, Address(from, pos, Address::times_1, 0));   // get next 16 bytes of input
2445     __ pxor  (xmm_result, xmm_temp);                                // xor with the current r vector
2446 
2447     __ pxor  (xmm_result, xmm_key0);                                // do the aes rounds
2448     for (int rnum = XMM_REG_NUM_KEY_FIRST + 1; rnum  <= XMM_REG_NUM_KEY_LAST; rnum++) {
2449       __ aesenc(xmm_result, as_XMMRegister(rnum));
2450     }
2451     for (int key_offset = 0x60; key_offset <= 0x90; key_offset += 0x10) {
2452       aes_enc_key(xmm_result, xmm_temp, key, key_offset);
2453     }
2454     load_key(xmm_temp, key, 0xa0);
2455     __ aesenclast(xmm_result, xmm_temp);
2456 
2457     __ movdqu(Address(to, pos, Address::times_1, 0), xmm_result);     // store into the next 16 bytes of output
2458     // no need to store r to memory until we exit
2459     __ addptr(pos, AESBlockSize);
2460     __ subptr(len_reg, AESBlockSize);
2461     __ jcc(Assembler::notEqual, L_loopTop_128);
2462 
2463     __ BIND(L_exit);
2464     __ movdqu(Address(rvec, 0), xmm_result);     // final value of r stored in rvec of CipherBlockChaining object
2465 
2466     handleSOERegisters(false /*restoring*/);
2467     __ movptr(rax, len_param); // return length
2468     __ leave();                                  // required for proper stackwalking of RuntimeStub frame
2469     __ ret(0);
2470 
2471     __ BIND(L_key_192_256);
2472     // here rax = len in ints of AESCrypt.KLE array (52=192, or 60=256)
2473     __ cmpl(rax, 52);
2474     __ jcc(Assembler::notEqual, L_key_256);
2475 
2476     // 192-bit code follows here (could be changed to use more xmm registers)
2477     __ movl(pos, 0);
2478     __ align(OptoLoopAlignment);
2479     __ BIND(L_loopTop_192);
2480     __ movdqu(xmm_temp, Address(from, pos, Address::times_1, 0));   // get next 16 bytes of input
2481     __ pxor  (xmm_result, xmm_temp);                                // xor with the current r vector
2482 
2483     __ pxor  (xmm_result, xmm_key0);                                // do the aes rounds
2484     for (int rnum = XMM_REG_NUM_KEY_FIRST + 1; rnum  <= XMM_REG_NUM_KEY_LAST; rnum++) {
2485       __ aesenc(xmm_result, as_XMMRegister(rnum));
2486     }
2487     for (int key_offset = 0x60; key_offset <= 0xb0; key_offset += 0x10) {
2488       aes_enc_key(xmm_result, xmm_temp, key, key_offset);
2489     }
2490     load_key(xmm_temp, key, 0xc0);
2491     __ aesenclast(xmm_result, xmm_temp);
2492 
2493     __ movdqu(Address(to, pos, Address::times_1, 0), xmm_result);   // store into the next 16 bytes of output
2494     // no need to store r to memory until we exit
2495     __ addptr(pos, AESBlockSize);
2496     __ subptr(len_reg, AESBlockSize);
2497     __ jcc(Assembler::notEqual, L_loopTop_192);
2498     __ jmp(L_exit);
2499 
2500     __ BIND(L_key_256);
2501     // 256-bit code follows here (could be changed to use more xmm registers)
2502     __ movl(pos, 0);
2503     __ align(OptoLoopAlignment);
2504     __ BIND(L_loopTop_256);
2505     __ movdqu(xmm_temp, Address(from, pos, Address::times_1, 0));   // get next 16 bytes of input
2506     __ pxor  (xmm_result, xmm_temp);                                // xor with the current r vector
2507 
2508     __ pxor  (xmm_result, xmm_key0);                                // do the aes rounds
2509     for (int rnum = XMM_REG_NUM_KEY_FIRST + 1; rnum  <= XMM_REG_NUM_KEY_LAST; rnum++) {
2510       __ aesenc(xmm_result, as_XMMRegister(rnum));
2511     }
2512     for (int key_offset = 0x60; key_offset <= 0xd0; key_offset += 0x10) {
2513       aes_enc_key(xmm_result, xmm_temp, key, key_offset);
2514     }
2515     load_key(xmm_temp, key, 0xe0);
2516     __ aesenclast(xmm_result, xmm_temp);
2517 
2518     __ movdqu(Address(to, pos, Address::times_1, 0), xmm_result);   // store into the next 16 bytes of output
2519     // no need to store r to memory until we exit
2520     __ addptr(pos, AESBlockSize);
2521     __ subptr(len_reg, AESBlockSize);
2522     __ jcc(Assembler::notEqual, L_loopTop_256);
2523     __ jmp(L_exit);
2524 
2525     return start;
2526   }
2527 
2528 
2529   // CBC AES Decryption.
2530   // In 32-bit stub, because of lack of registers we do not try to parallelize 4 blocks at a time.
2531   //
2532   // Arguments:
2533   //
2534   // Inputs:
2535   //   c_rarg0   - source byte array address
2536   //   c_rarg1   - destination byte array address
2537   //   c_rarg2   - K (key) in little endian int array
2538   //   c_rarg3   - r vector byte array address
2539   //   c_rarg4   - input length
2540   //
2541   // Output:
2542   //   rax       - input length
2543   //
2544 
2545   address generate_cipherBlockChaining_decryptAESCrypt_Parallel() {
2546     assert(UseAES, "need AES instructions and misaligned SSE support");
2547     __ align(CodeEntryAlignment);
2548     StubCodeMark mark(this, "StubRoutines", "cipherBlockChaining_decryptAESCrypt");
2549     address start = __ pc();
2550 
2551     const Register from        = rsi;      // source array address
2552     const Register to          = rdx;      // destination array address
2553     const Register key         = rcx;      // key array address
2554     const Register rvec        = rdi;      // r byte array initialized from initvector array address
2555                                            // and left with the results of the last encryption block
2556     const Register len_reg     = rbx;      // src len (must be multiple of blocksize 16)
2557     const Register pos         = rax;
2558 
2559     const int PARALLEL_FACTOR = 4;
2560     const int ROUNDS[3] = { 10, 12, 14 }; //aes rounds for key128, key192, key256
2561 
2562     Label L_exit;
2563     Label L_singleBlock_loopTop[3]; //128, 192, 256
2564     Label L_multiBlock_loopTop[3]; //128, 192, 256
2565 
2566     const XMMRegister xmm_prev_block_cipher = xmm0; // holds cipher of previous block
2567     const XMMRegister xmm_key_shuf_mask = xmm1;
2568 
2569     const XMMRegister xmm_key_tmp0 = xmm2;
2570     const XMMRegister xmm_key_tmp1 = xmm3;
2571 
2572     // registers holding the six results in the parallelized loop
2573     const XMMRegister xmm_result0 = xmm4;
2574     const XMMRegister xmm_result1 = xmm5;
2575     const XMMRegister xmm_result2 = xmm6;
2576     const XMMRegister xmm_result3 = xmm7;
2577 
2578     __ enter(); // required for proper stackwalking of RuntimeStub frame
2579     handleSOERegisters(true /*saving*/);
2580 
2581     // load registers from incoming parameters
2582     const Address  from_param(rbp, 8+0);
2583     const Address  to_param  (rbp, 8+4);
2584     const Address  key_param (rbp, 8+8);
2585     const Address  rvec_param (rbp, 8+12);
2586     const Address  len_param  (rbp, 8+16);
2587 
2588     __ movptr(from , from_param);
2589     __ movptr(to   , to_param);
2590     __ movptr(key  , key_param);
2591     __ movptr(rvec , rvec_param);
2592     __ movptr(len_reg , len_param);
2593 
2594     __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2595     __ movdqu(xmm_prev_block_cipher, Address(rvec, 0x00)); // initialize with initial rvec
2596 
2597     __ xorptr(pos, pos);
2598 
2599     // now split to different paths depending on the keylen (len in ints of AESCrypt.KLE array (52=192, or 60=256))
2600     // rvec is reused
2601     __ movl(rvec, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
2602     __ cmpl(rvec, 52);
2603     __ jcc(Assembler::equal, L_multiBlock_loopTop[1]);
2604     __ cmpl(rvec, 60);
2605     __ jcc(Assembler::equal, L_multiBlock_loopTop[2]);
2606 
2607 #define DoFour(opc, src_reg)           \
2608   __ opc(xmm_result0, src_reg);         \
2609   __ opc(xmm_result1, src_reg);         \
2610   __ opc(xmm_result2, src_reg);         \
2611   __ opc(xmm_result3, src_reg);         \
2612 
2613     for (int k = 0; k < 3; ++k) {
2614       __ align(OptoLoopAlignment);
2615       __ BIND(L_multiBlock_loopTop[k]);
2616       __ cmpptr(len_reg, PARALLEL_FACTOR * AESBlockSize); // see if at least 4 blocks left
2617       __ jcc(Assembler::less, L_singleBlock_loopTop[k]);
2618 
2619       __ movdqu(xmm_result0, Address(from, pos, Address::times_1, 0 * AESBlockSize)); // get next 4 blocks into xmmresult registers
2620       __ movdqu(xmm_result1, Address(from, pos, Address::times_1, 1 * AESBlockSize));
2621       __ movdqu(xmm_result2, Address(from, pos, Address::times_1, 2 * AESBlockSize));
2622       __ movdqu(xmm_result3, Address(from, pos, Address::times_1, 3 * AESBlockSize));
2623 
2624       // the java expanded key ordering is rotated one position from what we want
2625       // so we start from 0x10 here and hit 0x00 last
2626       load_key(xmm_key_tmp0, key, 0x10, xmm_key_shuf_mask);
2627       DoFour(pxor, xmm_key_tmp0); //xor with first key
2628       // do the aes dec rounds
2629       for (int rnum = 1; rnum <= ROUNDS[k];) {
2630         //load two keys at a time
2631         //k1->0x20, ..., k9->0xa0, k10->0x00
2632         load_key(xmm_key_tmp1, key, (rnum + 1) * 0x10, xmm_key_shuf_mask);
2633         load_key(xmm_key_tmp0, key, ((rnum + 2) % (ROUNDS[k] + 1)) * 0x10, xmm_key_shuf_mask); // hit 0x00 last!
2634         DoFour(aesdec, xmm_key_tmp1);
2635         rnum++;
2636         if (rnum != ROUNDS[k]) {
2637           DoFour(aesdec, xmm_key_tmp0);
2638         }
2639         else {
2640           DoFour(aesdeclast, xmm_key_tmp0);
2641         }
2642         rnum++;
2643       }
2644 
2645       // for each result, xor with the r vector of previous cipher block
2646       __ pxor(xmm_result0, xmm_prev_block_cipher);
2647       __ movdqu(xmm_prev_block_cipher, Address(from, pos, Address::times_1, 0 * AESBlockSize));
2648       __ pxor(xmm_result1, xmm_prev_block_cipher);
2649       __ movdqu(xmm_prev_block_cipher, Address(from, pos, Address::times_1, 1 * AESBlockSize));
2650       __ pxor(xmm_result2, xmm_prev_block_cipher);
2651       __ movdqu(xmm_prev_block_cipher, Address(from, pos, Address::times_1, 2 * AESBlockSize));
2652       __ pxor(xmm_result3, xmm_prev_block_cipher);
2653       __ movdqu(xmm_prev_block_cipher, Address(from, pos, Address::times_1, 3 * AESBlockSize)); // this will carry over to next set of blocks
2654 
2655             // store 4 results into the next 64 bytes of output
2656        __ movdqu(Address(to, pos, Address::times_1, 0 * AESBlockSize), xmm_result0);
2657        __ movdqu(Address(to, pos, Address::times_1, 1 * AESBlockSize), xmm_result1);
2658        __ movdqu(Address(to, pos, Address::times_1, 2 * AESBlockSize), xmm_result2);
2659        __ movdqu(Address(to, pos, Address::times_1, 3 * AESBlockSize), xmm_result3);
2660 
2661        __ addptr(pos, 4 * AESBlockSize);
2662        __ subptr(len_reg, 4 * AESBlockSize);
2663        __ jmp(L_multiBlock_loopTop[k]);
2664 
2665        //singleBlock starts here
2666        __ align(OptoLoopAlignment);
2667        __ BIND(L_singleBlock_loopTop[k]);
2668        __ cmpptr(len_reg, 0); // any blocks left?
2669        __ jcc(Assembler::equal, L_exit);
2670        __ movdqu(xmm_result0, Address(from, pos, Address::times_1, 0)); // get next 16 bytes of cipher input
2671        __ movdqa(xmm_result1, xmm_result0);
2672 
2673        load_key(xmm_key_tmp0, key, 0x10, xmm_key_shuf_mask);
2674        __ pxor(xmm_result0, xmm_key_tmp0);
2675        // do the aes dec rounds
2676        for (int rnum = 1; rnum < ROUNDS[k]; rnum++) {
2677          // the java expanded key ordering is rotated one position from what we want
2678          load_key(xmm_key_tmp0, key, (rnum + 1) * 0x10, xmm_key_shuf_mask);
2679          __ aesdec(xmm_result0, xmm_key_tmp0);
2680        }
2681        load_key(xmm_key_tmp0, key, 0x00, xmm_key_shuf_mask);
2682        __ aesdeclast(xmm_result0, xmm_key_tmp0);
2683        __ pxor(xmm_result0, xmm_prev_block_cipher); // xor with the current r vector
2684        __ movdqu(Address(to, pos, Address::times_1, 0), xmm_result0); // store into the next 16 bytes of output
2685        // no need to store r to memory until we exit
2686        __ movdqa(xmm_prev_block_cipher, xmm_result1); // set up next r vector with cipher input from this block
2687 
2688        __ addptr(pos, AESBlockSize);
2689        __ subptr(len_reg, AESBlockSize);
2690        __ jmp(L_singleBlock_loopTop[k]);
2691     }//for 128/192/256
2692 
2693     __ BIND(L_exit);
2694     __ movptr(rvec, rvec_param);                        // restore this since reused earlier
2695     __ movdqu(Address(rvec, 0), xmm_prev_block_cipher); // final value of r stored in rvec of CipherBlockChaining object
2696     handleSOERegisters(false /*restoring*/);
2697     __ movptr(rax, len_param);                          // return length
2698     __ leave();                                         // required for proper stackwalking of RuntimeStub frame
2699     __ ret(0);
2700 
2701     return start;
2702   }
2703 
2704   // CTR AES crypt.
2705   // In 32-bit stub, parallelize 4 blocks at a time
2706   // Arguments:
2707   //
2708   // Inputs:
2709   //   c_rarg0   - source byte array address
2710   //   c_rarg1   - destination byte array address
2711   //   c_rarg2   - K (key) in little endian int array
2712   //   c_rarg3   - counter vector byte array address
2713   //   c_rarg4   - input length
2714   //
2715   // Output:
2716   //   rax       - input length
2717   //
2718   address generate_counterMode_AESCrypt_Parallel() {
2719     assert(UseAES, "need AES instructions and misaligned SSE support");
2720     __ align(CodeEntryAlignment);
2721     StubCodeMark mark(this, "StubRoutines", "counterMode_AESCrypt");
2722     address start = __ pc();
2723     const Register from        = rsi;      // source array address
2724     const Register to          = rdx;      // destination array address
2725     const Register key         = rcx;      // key array address
2726     const Register counter     = rdi;      // counter byte array initialized from initvector array address
2727                                            // and updated with the incremented counter in the end
2728     const Register len_reg     = rbx;
2729     const Register pos         = rax;
2730 
2731     __ enter(); // required for proper stackwalking of RuntimeStub frame
2732     handleSOERegisters(true /*saving*/); // save rbx, rsi, rdi
2733 
2734     // load registers from incoming parameters
2735     const Address  from_param(rbp, 8+0);
2736     const Address  to_param  (rbp, 8+4);
2737     const Address  key_param (rbp, 8+8);
2738     const Address  rvec_param (rbp, 8+12);
2739     const Address  len_param  (rbp, 8+16);
2740     const Address  saved_counter_param(rbp, 8 + 20);
2741     const Address  used_addr_param(rbp, 8 + 24);
2742 
2743     __ movptr(from , from_param);
2744     __ movptr(to   , to_param);
2745     __ movptr(len_reg , len_param);
2746 
2747     // Use the partially used encrpyted counter from last invocation
2748     Label L_exit_preLoop, L_preLoop_start;
2749 
2750     // Use the registers 'counter' and 'key' here in this preloop
2751     // to hold of last 2 params 'used' and 'saved_encCounter_start'
2752     Register used = counter;
2753     Register saved_encCounter_start = key;
2754     Register used_addr = saved_encCounter_start;
2755 
2756     __ movptr(used_addr, used_addr_param);
2757     __ movptr(used, Address(used_addr, 0));
2758     __ movptr(saved_encCounter_start, saved_counter_param);
2759 
2760     __ BIND(L_preLoop_start);
2761     __ cmpptr(used, 16);
2762     __ jcc(Assembler::aboveEqual, L_exit_preLoop);
2763     __ cmpptr(len_reg, 0);
2764     __ jcc(Assembler::lessEqual, L_exit_preLoop);
2765     __ movb(rax, Address(saved_encCounter_start, used));
2766     __ xorb(rax, Address(from, 0));
2767     __ movb(Address(to, 0), rax);
2768     __ addptr(from, 1);
2769     __ addptr(to, 1);
2770     __ addptr(used, 1);
2771     __ subptr(len_reg, 1);
2772 
2773     __ jmp(L_preLoop_start);
2774 
2775     __ BIND(L_exit_preLoop);
2776     __ movptr(used_addr, used_addr_param);
2777     __ movptr(used_addr, used_addr_param);
2778     __ movl(Address(used_addr, 0), used);
2779 
2780     // load the parameters 'key' and 'counter'
2781     __ movptr(key, key_param);
2782     __ movptr(counter, rvec_param);
2783 
2784     // xmm register assignments for the loops below
2785     const XMMRegister xmm_curr_counter      = xmm0;
2786     const XMMRegister xmm_counter_shuf_mask = xmm1;  // need to be reloaded
2787     const XMMRegister xmm_key_shuf_mask     = xmm2;  // need to be reloaded
2788     const XMMRegister xmm_key               = xmm3;
2789     const XMMRegister xmm_result0           = xmm4;
2790     const XMMRegister xmm_result1           = xmm5;
2791     const XMMRegister xmm_result2           = xmm6;
2792     const XMMRegister xmm_result3           = xmm7;
2793     const XMMRegister xmm_from0             = xmm1;   //reuse XMM register
2794     const XMMRegister xmm_from1             = xmm2;
2795     const XMMRegister xmm_from2             = xmm3;
2796     const XMMRegister xmm_from3             = xmm4;
2797 
2798     //for key_128, key_192, key_256
2799     const int rounds[3] = {10, 12, 14};
2800     Label L_singleBlockLoopTop[3];
2801     Label L_multiBlock_loopTop[3];
2802     Label L_key192_top, L_key256_top;
2803     Label L_incCounter[3][4]; // 3: different key length,  4: 4 blocks at a time
2804     Label L_incCounter_single[3]; //for single block, key128, key192, key256
2805     Label L_processTail_insr[3], L_processTail_4_insr[3], L_processTail_2_insr[3], L_processTail_1_insr[3], L_processTail_exit_insr[3];
2806     Label L_processTail_extr[3], L_processTail_4_extr[3], L_processTail_2_extr[3], L_processTail_1_extr[3], L_processTail_exit_extr[3];
2807 
2808     Label L_exit;
2809     const int PARALLEL_FACTOR = 4;  //because of the limited register number
2810 
2811     // initialize counter with initial counter
2812     __ movdqu(xmm_curr_counter, Address(counter, 0x00));
2813     __ movdqu(xmm_counter_shuf_mask, ExternalAddress(StubRoutines::x86::counter_shuffle_mask_addr()));
2814     __ pshufb(xmm_curr_counter, xmm_counter_shuf_mask); //counter is shuffled for increase
2815 
2816     // key length could be only {11, 13, 15} * 4 = {44, 52, 60}
2817     __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2818     __ movl(rax, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
2819     __ cmpl(rax, 52);
2820     __ jcc(Assembler::equal, L_key192_top);
2821     __ cmpl(rax, 60);
2822     __ jcc(Assembler::equal, L_key256_top);
2823 
2824     //key128 begins here
2825     __ movptr(pos, 0); // init pos before L_multiBlock_loopTop
2826 
2827 #define CTR_DoFour(opc, src_reg)               \
2828     __ opc(xmm_result0, src_reg);              \
2829     __ opc(xmm_result1, src_reg);              \
2830     __ opc(xmm_result2, src_reg);              \
2831     __ opc(xmm_result3, src_reg);
2832 
2833     // k == 0 :  generate code for key_128
2834     // k == 1 :  generate code for key_192
2835     // k == 2 :  generate code for key_256
2836     for (int k = 0; k < 3; ++k) {
2837       //multi blocks starts here
2838       __ align(OptoLoopAlignment);
2839       __ BIND(L_multiBlock_loopTop[k]);
2840       __ cmpptr(len_reg, PARALLEL_FACTOR * AESBlockSize); // see if at least PARALLEL_FACTOR blocks left
2841       __ jcc(Assembler::less, L_singleBlockLoopTop[k]);
2842 
2843       __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2844       __ movdqu(xmm_counter_shuf_mask, ExternalAddress(StubRoutines::x86::counter_shuffle_mask_addr()));
2845 
2846       //load, then increase counters
2847       CTR_DoFour(movdqa, xmm_curr_counter);
2848       __ push(rbx);
2849       inc_counter(rbx, xmm_result1, 0x01, L_incCounter[k][0]);
2850       inc_counter(rbx, xmm_result2, 0x02, L_incCounter[k][1]);
2851       inc_counter(rbx, xmm_result3, 0x03, L_incCounter[k][2]);
2852       inc_counter(rbx, xmm_curr_counter, 0x04, L_incCounter[k][3]);
2853       __ pop (rbx);
2854 
2855       load_key(xmm_key, key, 0x00, xmm_key_shuf_mask); // load Round 0 key. interleaving for better performance
2856 
2857       CTR_DoFour(pshufb, xmm_counter_shuf_mask); // after increased, shuffled counters back for PXOR
2858       CTR_DoFour(pxor, xmm_key);   //PXOR with Round 0 key
2859 
2860       for (int i = 1; i < rounds[k]; ++i) {
2861         load_key(xmm_key, key, (0x10 * i), xmm_key_shuf_mask);
2862         CTR_DoFour(aesenc, xmm_key);
2863       }
2864       load_key(xmm_key, key, (0x10 * rounds[k]), xmm_key_shuf_mask);
2865       CTR_DoFour(aesenclast, xmm_key);
2866 
2867       // get next PARALLEL_FACTOR blocks into xmm_from registers
2868       __ movdqu(xmm_from0, Address(from, pos, Address::times_1, 0 * AESBlockSize));
2869       __ movdqu(xmm_from1, Address(from, pos, Address::times_1, 1 * AESBlockSize));
2870       __ movdqu(xmm_from2, Address(from, pos, Address::times_1, 2 * AESBlockSize));
2871 
2872       // PXOR with input text
2873       __ pxor(xmm_result0, xmm_from0); //result0 is xmm4
2874       __ pxor(xmm_result1, xmm_from1);
2875       __ pxor(xmm_result2, xmm_from2);
2876 
2877       // store PARALLEL_FACTOR results into the next 64 bytes of output
2878       __ movdqu(Address(to, pos, Address::times_1, 0 * AESBlockSize), xmm_result0);
2879       __ movdqu(Address(to, pos, Address::times_1, 1 * AESBlockSize), xmm_result1);
2880       __ movdqu(Address(to, pos, Address::times_1, 2 * AESBlockSize), xmm_result2);
2881 
2882       // do it here after xmm_result0 is saved, because xmm_from3 reuse the same register of xmm_result0.
2883       __ movdqu(xmm_from3, Address(from, pos, Address::times_1, 3 * AESBlockSize));
2884       __ pxor(xmm_result3, xmm_from3);
2885       __ movdqu(Address(to, pos, Address::times_1, 3 * AESBlockSize), xmm_result3);
2886 
2887       __ addptr(pos, PARALLEL_FACTOR * AESBlockSize); // increase the length of crypt text
2888       __ subptr(len_reg, PARALLEL_FACTOR * AESBlockSize); // decrease the remaining length
2889       __ jmp(L_multiBlock_loopTop[k]);
2890 
2891       // singleBlock starts here
2892       __ align(OptoLoopAlignment);
2893       __ BIND(L_singleBlockLoopTop[k]);
2894       __ cmpptr(len_reg, 0);
2895       __ jcc(Assembler::equal, L_exit);
2896       __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2897       __ movdqu(xmm_counter_shuf_mask, ExternalAddress(StubRoutines::x86::counter_shuffle_mask_addr()));
2898       __ movdqa(xmm_result0, xmm_curr_counter);
2899       load_key(xmm_key, key, 0x00, xmm_key_shuf_mask);
2900       __ push(rbx);//rbx is used for increasing counter
2901       inc_counter(rbx, xmm_curr_counter, 0x01, L_incCounter_single[k]);
2902       __ pop (rbx);
2903       __ pshufb(xmm_result0, xmm_counter_shuf_mask);
2904       __ pxor(xmm_result0, xmm_key);
2905       for (int i = 1; i < rounds[k]; i++) {
2906         load_key(xmm_key, key, (0x10 * i), xmm_key_shuf_mask);
2907         __ aesenc(xmm_result0, xmm_key);
2908       }
2909       load_key(xmm_key, key, (0x10 * rounds[k]), xmm_key_shuf_mask);
2910       __ aesenclast(xmm_result0, xmm_key);
2911       __ cmpptr(len_reg, AESBlockSize);
2912       __ jcc(Assembler::less, L_processTail_insr[k]);
2913         __ movdqu(xmm_from0, Address(from, pos, Address::times_1, 0 * AESBlockSize));
2914         __ pxor(xmm_result0, xmm_from0);
2915         __ movdqu(Address(to, pos, Address::times_1, 0 * AESBlockSize), xmm_result0);
2916         __ addptr(pos, AESBlockSize);
2917         __ subptr(len_reg, AESBlockSize);
2918         __ jmp(L_singleBlockLoopTop[k]);
2919 
2920       __ BIND(L_processTail_insr[k]);                                               // Process the tail part of the input array
2921         __ addptr(pos, len_reg);                                                    // 1. Insert bytes from src array into xmm_from0 register
2922         __ testptr(len_reg, 8);
2923         __ jcc(Assembler::zero, L_processTail_4_insr[k]);
2924           __ subptr(pos,8);
2925           __ pinsrd(xmm_from0, Address(from, pos), 0);
2926           __ pinsrd(xmm_from0, Address(from, pos, Address::times_1, 4), 1);
2927         __ BIND(L_processTail_4_insr[k]);
2928         __ testptr(len_reg, 4);
2929         __ jcc(Assembler::zero, L_processTail_2_insr[k]);
2930           __ subptr(pos,4);
2931           __ pslldq(xmm_from0, 4);
2932           __ pinsrd(xmm_from0, Address(from, pos), 0);
2933         __ BIND(L_processTail_2_insr[k]);
2934         __ testptr(len_reg, 2);
2935         __ jcc(Assembler::zero, L_processTail_1_insr[k]);
2936           __ subptr(pos, 2);
2937           __ pslldq(xmm_from0, 2);
2938           __ pinsrw(xmm_from0, Address(from, pos), 0);
2939         __ BIND(L_processTail_1_insr[k]);
2940         __ testptr(len_reg, 1);
2941         __ jcc(Assembler::zero, L_processTail_exit_insr[k]);
2942           __ subptr(pos, 1);
2943           __ pslldq(xmm_from0, 1);
2944           __ pinsrb(xmm_from0, Address(from, pos), 0);
2945         __ BIND(L_processTail_exit_insr[k]);
2946 
2947         __ movptr(saved_encCounter_start, saved_counter_param);
2948         __ movdqu(Address(saved_encCounter_start, 0), xmm_result0);               // 2. Perform pxor of the encrypted counter and plaintext Bytes.
2949         __ pxor(xmm_result0, xmm_from0);                                          //    Also the encrypted counter is saved for next invocation.
2950 
2951         __ testptr(len_reg, 8);
2952         __ jcc(Assembler::zero, L_processTail_4_extr[k]);                        // 3. Extract bytes from xmm_result0 into the dest. array
2953           __ pextrd(Address(to, pos), xmm_result0, 0);
2954           __ pextrd(Address(to, pos, Address::times_1, 4), xmm_result0, 1);
2955           __ psrldq(xmm_result0, 8);
2956           __ addptr(pos, 8);
2957         __ BIND(L_processTail_4_extr[k]);
2958         __ testptr(len_reg, 4);
2959         __ jcc(Assembler::zero, L_processTail_2_extr[k]);
2960           __ pextrd(Address(to, pos), xmm_result0, 0);
2961           __ psrldq(xmm_result0, 4);
2962           __ addptr(pos, 4);
2963         __ BIND(L_processTail_2_extr[k]);
2964         __ testptr(len_reg, 2);
2965         __ jcc(Assembler::zero, L_processTail_1_extr[k]);
2966           __ pextrb(Address(to, pos), xmm_result0, 0);
2967           __ pextrb(Address(to, pos, Address::times_1, 1), xmm_result0, 1);
2968           __ psrldq(xmm_result0, 2);
2969           __ addptr(pos, 2);
2970         __ BIND(L_processTail_1_extr[k]);
2971         __ testptr(len_reg, 1);
2972         __ jcc(Assembler::zero, L_processTail_exit_extr[k]);
2973           __ pextrb(Address(to, pos), xmm_result0, 0);
2974 
2975         __ BIND(L_processTail_exit_extr[k]);
2976         __ movptr(used_addr, used_addr_param);
2977         __ movl(Address(used_addr, 0), len_reg);
2978         __ jmp(L_exit);
2979     }
2980 
2981     __ BIND(L_exit);
2982     __ movdqu(xmm_counter_shuf_mask, ExternalAddress(StubRoutines::x86::counter_shuffle_mask_addr()));
2983     __ pshufb(xmm_curr_counter, xmm_counter_shuf_mask); //counter is shuffled back.
2984     __ movdqu(Address(counter, 0), xmm_curr_counter); //save counter back
2985     handleSOERegisters(false /*restoring*/);
2986     __ movptr(rax, len_param); // return length
2987     __ leave();                // required for proper stackwalking of RuntimeStub frame
2988     __ ret(0);
2989 
2990     __ BIND (L_key192_top);
2991     __ movptr(pos, 0); // init pos before L_multiBlock_loopTop
2992     __ jmp(L_multiBlock_loopTop[1]); //key192
2993 
2994     __ BIND (L_key256_top);
2995     __ movptr(pos, 0); // init pos before L_multiBlock_loopTop
2996     __ jmp(L_multiBlock_loopTop[2]); //key192
2997 
2998     return start;
2999   }
3000 
3001   address generate_upper_word_mask() {
3002     __ align(64);
3003     StubCodeMark mark(this, "StubRoutines", "upper_word_mask");
3004     address start = __ pc();
3005     __ emit_data(0x00000000, relocInfo::none, 0);
3006     __ emit_data(0x00000000, relocInfo::none, 0);
3007     __ emit_data(0x00000000, relocInfo::none, 0);
3008     __ emit_data(0xFFFFFFFF, relocInfo::none, 0);
3009     return start;
3010   }
3011 
3012   address generate_shuffle_byte_flip_mask() {
3013     __ align(64);
3014     StubCodeMark mark(this, "StubRoutines", "shuffle_byte_flip_mask");
3015     address start = __ pc();
3016     __ emit_data(0x0c0d0e0f, relocInfo::none, 0);
3017     __ emit_data(0x08090a0b, relocInfo::none, 0);
3018     __ emit_data(0x04050607, relocInfo::none, 0);
3019     __ emit_data(0x00010203, relocInfo::none, 0);
3020     return start;
3021   }
3022 
3023   // ofs and limit are use for multi-block byte array.
3024   // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
3025   address generate_sha1_implCompress(bool multi_block, const char *name) {
3026     __ align(CodeEntryAlignment);
3027     StubCodeMark mark(this, "StubRoutines", name);
3028     address start = __ pc();
3029 
3030     Register buf   = rax;
3031     Register state = rdx;
3032     Register ofs   = rcx;
3033     Register limit = rdi;
3034 
3035     const Address  buf_param(rbp, 8 + 0);
3036     const Address  state_param(rbp, 8 + 4);
3037     const Address  ofs_param(rbp, 8 + 8);
3038     const Address  limit_param(rbp, 8 + 12);
3039 
3040     const XMMRegister abcd = xmm0;
3041     const XMMRegister e0 = xmm1;
3042     const XMMRegister e1 = xmm2;
3043     const XMMRegister msg0 = xmm3;
3044 
3045     const XMMRegister msg1 = xmm4;
3046     const XMMRegister msg2 = xmm5;
3047     const XMMRegister msg3 = xmm6;
3048     const XMMRegister shuf_mask = xmm7;
3049 
3050     __ enter();
3051     __ subptr(rsp, 8 * wordSize);
3052     handleSOERegisters(true /*saving*/);
3053 
3054     __ movptr(buf, buf_param);
3055     __ movptr(state, state_param);
3056     if (multi_block) {
3057       __ movptr(ofs, ofs_param);
3058       __ movptr(limit, limit_param);
3059     }
3060 
3061     __ fast_sha1(abcd, e0, e1, msg0, msg1, msg2, msg3, shuf_mask,
3062       buf, state, ofs, limit, rsp, multi_block);
3063 
3064     handleSOERegisters(false /*restoring*/);
3065     __ addptr(rsp, 8 * wordSize);
3066     __ leave();
3067     __ ret(0);
3068     return start;
3069   }
3070 
3071   address generate_pshuffle_byte_flip_mask() {
3072     __ align(64);
3073     StubCodeMark mark(this, "StubRoutines", "pshuffle_byte_flip_mask");
3074     address start = __ pc();
3075     __ emit_data(0x00010203, relocInfo::none, 0);
3076     __ emit_data(0x04050607, relocInfo::none, 0);
3077     __ emit_data(0x08090a0b, relocInfo::none, 0);
3078     __ emit_data(0x0c0d0e0f, relocInfo::none, 0);
3079     return start;
3080   }
3081 
3082   // ofs and limit are use for multi-block byte array.
3083   // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
3084  address generate_sha256_implCompress(bool multi_block, const char *name) {
3085     __ align(CodeEntryAlignment);
3086     StubCodeMark mark(this, "StubRoutines", name);
3087     address start = __ pc();
3088 
3089     Register buf = rbx;
3090     Register state = rsi;
3091     Register ofs = rdx;
3092     Register limit = rcx;
3093 
3094     const Address  buf_param(rbp, 8 + 0);
3095     const Address  state_param(rbp, 8 + 4);
3096     const Address  ofs_param(rbp, 8 + 8);
3097     const Address  limit_param(rbp, 8 + 12);
3098 
3099     const XMMRegister msg = xmm0;
3100     const XMMRegister state0 = xmm1;
3101     const XMMRegister state1 = xmm2;
3102     const XMMRegister msgtmp0 = xmm3;
3103 
3104     const XMMRegister msgtmp1 = xmm4;
3105     const XMMRegister msgtmp2 = xmm5;
3106     const XMMRegister msgtmp3 = xmm6;
3107     const XMMRegister msgtmp4 = xmm7;
3108 
3109     __ enter();
3110     __ subptr(rsp, 8 * wordSize);
3111     handleSOERegisters(true /*saving*/);
3112     __ movptr(buf, buf_param);
3113     __ movptr(state, state_param);
3114     if (multi_block) {
3115      __ movptr(ofs, ofs_param);
3116      __ movptr(limit, limit_param);
3117     }
3118 
3119     __ fast_sha256(msg, state0, state1, msgtmp0, msgtmp1, msgtmp2, msgtmp3, msgtmp4,
3120       buf, state, ofs, limit, rsp, multi_block);
3121 
3122     handleSOERegisters(false);
3123     __ addptr(rsp, 8 * wordSize);
3124     __ leave();
3125     __ ret(0);
3126     return start;
3127   }
3128 
3129   // byte swap x86 long
3130   address generate_ghash_long_swap_mask() {
3131     __ align(CodeEntryAlignment);
3132     StubCodeMark mark(this, "StubRoutines", "ghash_long_swap_mask");
3133     address start = __ pc();
3134     __ emit_data(0x0b0a0908, relocInfo::none, 0);
3135     __ emit_data(0x0f0e0d0c, relocInfo::none, 0);
3136     __ emit_data(0x03020100, relocInfo::none, 0);
3137     __ emit_data(0x07060504, relocInfo::none, 0);
3138 
3139   return start;
3140   }
3141 
3142   // byte swap x86 byte array
3143   address generate_ghash_byte_swap_mask() {
3144     __ align(CodeEntryAlignment);
3145     StubCodeMark mark(this, "StubRoutines", "ghash_byte_swap_mask");
3146     address start = __ pc();
3147     __ emit_data(0x0c0d0e0f, relocInfo::none, 0);
3148     __ emit_data(0x08090a0b, relocInfo::none, 0);
3149     __ emit_data(0x04050607, relocInfo::none, 0);
3150     __ emit_data(0x00010203, relocInfo::none, 0);
3151   return start;
3152   }
3153 
3154   /* Single and multi-block ghash operations */
3155   address generate_ghash_processBlocks() {
3156     assert(UseGHASHIntrinsics, "need GHASH intrinsics and CLMUL support");
3157     __ align(CodeEntryAlignment);
3158     Label L_ghash_loop, L_exit;
3159     StubCodeMark mark(this, "StubRoutines", "ghash_processBlocks");
3160     address start = __ pc();
3161 
3162     const Register state        = rdi;
3163     const Register subkeyH      = rsi;
3164     const Register data         = rdx;
3165     const Register blocks       = rcx;
3166 
3167     const Address  state_param(rbp, 8+0);
3168     const Address  subkeyH_param(rbp, 8+4);
3169     const Address  data_param(rbp, 8+8);
3170     const Address  blocks_param(rbp, 8+12);
3171 
3172     const XMMRegister xmm_temp0 = xmm0;
3173     const XMMRegister xmm_temp1 = xmm1;
3174     const XMMRegister xmm_temp2 = xmm2;
3175     const XMMRegister xmm_temp3 = xmm3;
3176     const XMMRegister xmm_temp4 = xmm4;
3177     const XMMRegister xmm_temp5 = xmm5;
3178     const XMMRegister xmm_temp6 = xmm6;
3179     const XMMRegister xmm_temp7 = xmm7;
3180 
3181     __ enter();
3182     handleSOERegisters(true);  // Save registers
3183 
3184     __ movptr(state, state_param);
3185     __ movptr(subkeyH, subkeyH_param);
3186     __ movptr(data, data_param);
3187     __ movptr(blocks, blocks_param);
3188 
3189     __ movdqu(xmm_temp0, Address(state, 0));
3190     __ pshufb(xmm_temp0, ExternalAddress(StubRoutines::x86::ghash_long_swap_mask_addr()));
3191 
3192     __ movdqu(xmm_temp1, Address(subkeyH, 0));
3193     __ pshufb(xmm_temp1, ExternalAddress(StubRoutines::x86::ghash_long_swap_mask_addr()));
3194 
3195     __ BIND(L_ghash_loop);
3196     __ movdqu(xmm_temp2, Address(data, 0));
3197     __ pshufb(xmm_temp2, ExternalAddress(StubRoutines::x86::ghash_byte_swap_mask_addr()));
3198 
3199     __ pxor(xmm_temp0, xmm_temp2);
3200 
3201     //
3202     // Multiply with the hash key
3203     //
3204     __ movdqu(xmm_temp3, xmm_temp0);
3205     __ pclmulqdq(xmm_temp3, xmm_temp1, 0);      // xmm3 holds a0*b0
3206     __ movdqu(xmm_temp4, xmm_temp0);
3207     __ pclmulqdq(xmm_temp4, xmm_temp1, 16);     // xmm4 holds a0*b1
3208 
3209     __ movdqu(xmm_temp5, xmm_temp0);
3210     __ pclmulqdq(xmm_temp5, xmm_temp1, 1);      // xmm5 holds a1*b0
3211     __ movdqu(xmm_temp6, xmm_temp0);
3212     __ pclmulqdq(xmm_temp6, xmm_temp1, 17);     // xmm6 holds a1*b1
3213 
3214     __ pxor(xmm_temp4, xmm_temp5);      // xmm4 holds a0*b1 + a1*b0
3215 
3216     __ movdqu(xmm_temp5, xmm_temp4);    // move the contents of xmm4 to xmm5
3217     __ psrldq(xmm_temp4, 8);    // shift by xmm4 64 bits to the right
3218     __ pslldq(xmm_temp5, 8);    // shift by xmm5 64 bits to the left
3219     __ pxor(xmm_temp3, xmm_temp5);
3220     __ pxor(xmm_temp6, xmm_temp4);      // Register pair <xmm6:xmm3> holds the result
3221                                         // of the carry-less multiplication of
3222                                         // xmm0 by xmm1.
3223 
3224     // We shift the result of the multiplication by one bit position
3225     // to the left to cope for the fact that the bits are reversed.
3226     __ movdqu(xmm_temp7, xmm_temp3);
3227     __ movdqu(xmm_temp4, xmm_temp6);
3228     __ pslld (xmm_temp3, 1);
3229     __ pslld(xmm_temp6, 1);
3230     __ psrld(xmm_temp7, 31);
3231     __ psrld(xmm_temp4, 31);
3232     __ movdqu(xmm_temp5, xmm_temp7);
3233     __ pslldq(xmm_temp4, 4);
3234     __ pslldq(xmm_temp7, 4);
3235     __ psrldq(xmm_temp5, 12);
3236     __ por(xmm_temp3, xmm_temp7);
3237     __ por(xmm_temp6, xmm_temp4);
3238     __ por(xmm_temp6, xmm_temp5);
3239 
3240     //
3241     // First phase of the reduction
3242     //
3243     // Move xmm3 into xmm4, xmm5, xmm7 in order to perform the shifts
3244     // independently.
3245     __ movdqu(xmm_temp7, xmm_temp3);
3246     __ movdqu(xmm_temp4, xmm_temp3);
3247     __ movdqu(xmm_temp5, xmm_temp3);
3248     __ pslld(xmm_temp7, 31);    // packed right shift shifting << 31
3249     __ pslld(xmm_temp4, 30);    // packed right shift shifting << 30
3250     __ pslld(xmm_temp5, 25);    // packed right shift shifting << 25
3251     __ pxor(xmm_temp7, xmm_temp4);      // xor the shifted versions
3252     __ pxor(xmm_temp7, xmm_temp5);
3253     __ movdqu(xmm_temp4, xmm_temp7);
3254     __ pslldq(xmm_temp7, 12);
3255     __ psrldq(xmm_temp4, 4);
3256     __ pxor(xmm_temp3, xmm_temp7);      // first phase of the reduction complete
3257 
3258     //
3259     // Second phase of the reduction
3260     //
3261     // Make 3 copies of xmm3 in xmm2, xmm5, xmm7 for doing these
3262     // shift operations.
3263     __ movdqu(xmm_temp2, xmm_temp3);
3264     __ movdqu(xmm_temp7, xmm_temp3);
3265     __ movdqu(xmm_temp5, xmm_temp3);
3266     __ psrld(xmm_temp2, 1);     // packed left shifting >> 1
3267     __ psrld(xmm_temp7, 2);     // packed left shifting >> 2
3268     __ psrld(xmm_temp5, 7);     // packed left shifting >> 7
3269     __ pxor(xmm_temp2, xmm_temp7);      // xor the shifted versions
3270     __ pxor(xmm_temp2, xmm_temp5);
3271     __ pxor(xmm_temp2, xmm_temp4);
3272     __ pxor(xmm_temp3, xmm_temp2);
3273     __ pxor(xmm_temp6, xmm_temp3);      // the result is in xmm6
3274 
3275     __ decrement(blocks);
3276     __ jcc(Assembler::zero, L_exit);
3277     __ movdqu(xmm_temp0, xmm_temp6);
3278     __ addptr(data, 16);
3279     __ jmp(L_ghash_loop);
3280 
3281     __ BIND(L_exit);
3282        // Byte swap 16-byte result
3283     __ pshufb(xmm_temp6, ExternalAddress(StubRoutines::x86::ghash_long_swap_mask_addr()));
3284     __ movdqu(Address(state, 0), xmm_temp6);   // store the result
3285 
3286     handleSOERegisters(false);  // restore registers
3287     __ leave();
3288     __ ret(0);
3289     return start;
3290   }
3291 
3292   /**
3293    *  Arguments:
3294    *
3295    * Inputs:
3296    *   rsp(4)   - int crc
3297    *   rsp(8)   - byte* buf
3298    *   rsp(12)  - int length
3299    *
3300    * Ouput:
3301    *       rax   - int crc result
3302    */
3303   address generate_updateBytesCRC32() {
3304     assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions");
3305 
3306     __ align(CodeEntryAlignment);
3307     StubCodeMark mark(this, "StubRoutines", "updateBytesCRC32");
3308 
3309     address start = __ pc();
3310 
3311     const Register crc   = rdx;  // crc
3312     const Register buf   = rsi;  // source java byte array address
3313     const Register len   = rcx;  // length
3314     const Register table = rdi;  // crc_table address (reuse register)
3315     const Register tmp   = rbx;
3316     assert_different_registers(crc, buf, len, table, tmp, rax);
3317 
3318     BLOCK_COMMENT("Entry:");
3319     __ enter(); // required for proper stackwalking of RuntimeStub frame
3320     __ push(rsi);
3321     __ push(rdi);
3322     __ push(rbx);
3323 
3324     Address crc_arg(rbp, 8 + 0);
3325     Address buf_arg(rbp, 8 + 4);
3326     Address len_arg(rbp, 8 + 8);
3327 
3328     // Load up:
3329     __ movl(crc,   crc_arg);
3330     __ movptr(buf, buf_arg);
3331     __ movl(len,   len_arg);
3332 
3333     __ kernel_crc32(crc, buf, len, table, tmp);
3334 
3335     __ movl(rax, crc);
3336     __ pop(rbx);
3337     __ pop(rdi);
3338     __ pop(rsi);
3339     __ vzeroupper();
3340     __ leave(); // required for proper stackwalking of RuntimeStub frame
3341     __ ret(0);
3342 
3343     return start;
3344   }
3345 
3346   /**
3347   *  Arguments:
3348   *
3349   * Inputs:
3350   *   rsp(4)   - int crc
3351   *   rsp(8)   - byte* buf
3352   *   rsp(12)  - int length
3353   *   rsp(16)  - table_start - optional (present only when doing a library_calll,
3354   *              not used by x86 algorithm)
3355   *
3356   * Ouput:
3357   *       rax  - int crc result
3358   */
3359   address generate_updateBytesCRC32C(bool is_pclmulqdq_supported) {
3360     assert(UseCRC32CIntrinsics, "need SSE4_2");
3361     __ align(CodeEntryAlignment);
3362     StubCodeMark mark(this, "StubRoutines", "updateBytesCRC32C");
3363     address start = __ pc();
3364     const Register crc = rax;  // crc
3365     const Register buf = rcx;  // source java byte array address
3366     const Register len = rdx;  // length
3367     const Register d = rbx;
3368     const Register g = rsi;
3369     const Register h = rdi;
3370     const Register empty = 0; // will never be used, in order not
3371                               // to change a signature for crc32c_IPL_Alg2_Alt2
3372                               // between 64/32 I'm just keeping it here
3373     assert_different_registers(crc, buf, len, d, g, h);
3374 
3375     BLOCK_COMMENT("Entry:");
3376     __ enter(); // required for proper stackwalking of RuntimeStub frame
3377     Address crc_arg(rsp, 4 + 4 + 0); // ESP+4 +
3378                                      // we need to add additional 4 because __ enter
3379                                      // have just pushed ebp on a stack
3380     Address buf_arg(rsp, 4 + 4 + 4);
3381     Address len_arg(rsp, 4 + 4 + 8);
3382       // Load up:
3383       __ movl(crc, crc_arg);
3384       __ movl(buf, buf_arg);
3385       __ movl(len, len_arg);
3386       __ push(d);
3387       __ push(g);
3388       __ push(h);
3389       __ crc32c_ipl_alg2_alt2(crc, buf, len,
3390                               d, g, h,
3391                               empty, empty, empty,
3392                               xmm0, xmm1, xmm2,
3393                               is_pclmulqdq_supported);
3394       __ pop(h);
3395       __ pop(g);
3396       __ pop(d);
3397     __ vzeroupper();
3398     __ leave(); // required for proper stackwalking of RuntimeStub frame
3399     __ ret(0);
3400 
3401     return start;
3402   }
3403 
3404  address generate_libmExp() {
3405     StubCodeMark mark(this, "StubRoutines", "libmExp");
3406 
3407     address start = __ pc();
3408 
3409     const XMMRegister x0  = xmm0;
3410     const XMMRegister x1  = xmm1;
3411     const XMMRegister x2  = xmm2;
3412     const XMMRegister x3  = xmm3;
3413 
3414     const XMMRegister x4  = xmm4;
3415     const XMMRegister x5  = xmm5;
3416     const XMMRegister x6  = xmm6;
3417     const XMMRegister x7  = xmm7;
3418 
3419     const Register tmp   = rbx;
3420 
3421     BLOCK_COMMENT("Entry:");
3422     __ enter(); // required for proper stackwalking of RuntimeStub frame
3423     __ fast_exp(x0, x1, x2, x3, x4, x5, x6, x7, rax, rcx, rdx, tmp);
3424     __ leave(); // required for proper stackwalking of RuntimeStub frame
3425     __ ret(0);
3426 
3427     return start;
3428 
3429   }
3430 
3431  address generate_libmLog() {
3432    StubCodeMark mark(this, "StubRoutines", "libmLog");
3433 
3434    address start = __ pc();
3435 
3436    const XMMRegister x0 = xmm0;
3437    const XMMRegister x1 = xmm1;
3438    const XMMRegister x2 = xmm2;
3439    const XMMRegister x3 = xmm3;
3440 
3441    const XMMRegister x4 = xmm4;
3442    const XMMRegister x5 = xmm5;
3443    const XMMRegister x6 = xmm6;
3444    const XMMRegister x7 = xmm7;
3445 
3446    const Register tmp = rbx;
3447 
3448    BLOCK_COMMENT("Entry:");
3449    __ enter(); // required for proper stackwalking of RuntimeStub frame
3450    __ fast_log(x0, x1, x2, x3, x4, x5, x6, x7, rax, rcx, rdx, tmp);
3451    __ leave(); // required for proper stackwalking of RuntimeStub frame
3452    __ ret(0);
3453 
3454    return start;
3455 
3456  }
3457 
3458  address generate_libmLog10() {
3459    StubCodeMark mark(this, "StubRoutines", "libmLog10");
3460 
3461    address start = __ pc();
3462 
3463    const XMMRegister x0 = xmm0;
3464    const XMMRegister x1 = xmm1;
3465    const XMMRegister x2 = xmm2;
3466    const XMMRegister x3 = xmm3;
3467 
3468    const XMMRegister x4 = xmm4;
3469    const XMMRegister x5 = xmm5;
3470    const XMMRegister x6 = xmm6;
3471    const XMMRegister x7 = xmm7;
3472 
3473    const Register tmp = rbx;
3474 
3475    BLOCK_COMMENT("Entry:");
3476    __ enter(); // required for proper stackwalking of RuntimeStub frame
3477    __ fast_log10(x0, x1, x2, x3, x4, x5, x6, x7, rax, rcx, rdx, tmp);
3478    __ leave(); // required for proper stackwalking of RuntimeStub frame
3479    __ ret(0);
3480 
3481    return start;
3482 
3483  }
3484 
3485  address generate_libmPow() {
3486    StubCodeMark mark(this, "StubRoutines", "libmPow");
3487 
3488    address start = __ pc();
3489 
3490    const XMMRegister x0 = xmm0;
3491    const XMMRegister x1 = xmm1;
3492    const XMMRegister x2 = xmm2;
3493    const XMMRegister x3 = xmm3;
3494 
3495    const XMMRegister x4 = xmm4;
3496    const XMMRegister x5 = xmm5;
3497    const XMMRegister x6 = xmm6;
3498    const XMMRegister x7 = xmm7;
3499 
3500    const Register tmp = rbx;
3501 
3502    BLOCK_COMMENT("Entry:");
3503    __ enter(); // required for proper stackwalking of RuntimeStub frame
3504    __ fast_pow(x0, x1, x2, x3, x4, x5, x6, x7, rax, rcx, rdx, tmp);
3505    __ leave(); // required for proper stackwalking of RuntimeStub frame
3506    __ ret(0);
3507 
3508    return start;
3509 
3510  }
3511 
3512  address generate_libm_reduce_pi04l() {
3513    StubCodeMark mark(this, "StubRoutines", "libm_reduce_pi04l");
3514 
3515    address start = __ pc();
3516 
3517    BLOCK_COMMENT("Entry:");
3518    __ libm_reduce_pi04l(rax, rcx, rdx, rbx, rsi, rdi, rbp, rsp);
3519 
3520    return start;
3521 
3522  }
3523 
3524  address generate_libm_sin_cos_huge() {
3525    StubCodeMark mark(this, "StubRoutines", "libm_sin_cos_huge");
3526 
3527    address start = __ pc();
3528 
3529    const XMMRegister x0 = xmm0;
3530    const XMMRegister x1 = xmm1;
3531 
3532    BLOCK_COMMENT("Entry:");
3533    __ libm_sincos_huge(x0, x1, rax, rcx, rdx, rbx, rsi, rdi, rbp, rsp);
3534 
3535    return start;
3536 
3537  }
3538 
3539  address generate_libmSin() {
3540    StubCodeMark mark(this, "StubRoutines", "libmSin");
3541 
3542    address start = __ pc();
3543 
3544    const XMMRegister x0 = xmm0;
3545    const XMMRegister x1 = xmm1;
3546    const XMMRegister x2 = xmm2;
3547    const XMMRegister x3 = xmm3;
3548 
3549    const XMMRegister x4 = xmm4;
3550    const XMMRegister x5 = xmm5;
3551    const XMMRegister x6 = xmm6;
3552    const XMMRegister x7 = xmm7;
3553 
3554    BLOCK_COMMENT("Entry:");
3555    __ enter(); // required for proper stackwalking of RuntimeStub frame
3556    __ fast_sin(x0, x1, x2, x3, x4, x5, x6, x7, rax, rbx, rdx);
3557    __ leave(); // required for proper stackwalking of RuntimeStub frame
3558    __ ret(0);
3559 
3560    return start;
3561 
3562  }
3563 
3564  address generate_libmCos() {
3565    StubCodeMark mark(this, "StubRoutines", "libmCos");
3566 
3567    address start = __ pc();
3568 
3569    const XMMRegister x0 = xmm0;
3570    const XMMRegister x1 = xmm1;
3571    const XMMRegister x2 = xmm2;
3572    const XMMRegister x3 = xmm3;
3573 
3574    const XMMRegister x4 = xmm4;
3575    const XMMRegister x5 = xmm5;
3576    const XMMRegister x6 = xmm6;
3577    const XMMRegister x7 = xmm7;
3578 
3579    const Register tmp = rbx;
3580 
3581    BLOCK_COMMENT("Entry:");
3582    __ enter(); // required for proper stackwalking of RuntimeStub frame
3583    __ fast_cos(x0, x1, x2, x3, x4, x5, x6, x7, rax, rcx, rdx, tmp);
3584    __ leave(); // required for proper stackwalking of RuntimeStub frame
3585    __ ret(0);
3586 
3587    return start;
3588 
3589  }
3590 
3591  address generate_libm_tan_cot_huge() {
3592    StubCodeMark mark(this, "StubRoutines", "libm_tan_cot_huge");
3593 
3594    address start = __ pc();
3595 
3596    const XMMRegister x0 = xmm0;
3597    const XMMRegister x1 = xmm1;
3598 
3599    BLOCK_COMMENT("Entry:");
3600    __ libm_tancot_huge(x0, x1, rax, rcx, rdx, rbx, rsi, rdi, rbp, rsp);
3601 
3602    return start;
3603 
3604  }
3605 
3606  address generate_libmTan() {
3607    StubCodeMark mark(this, "StubRoutines", "libmTan");
3608 
3609    address start = __ pc();
3610 
3611    const XMMRegister x0 = xmm0;
3612    const XMMRegister x1 = xmm1;
3613    const XMMRegister x2 = xmm2;
3614    const XMMRegister x3 = xmm3;
3615 
3616    const XMMRegister x4 = xmm4;
3617    const XMMRegister x5 = xmm5;
3618    const XMMRegister x6 = xmm6;
3619    const XMMRegister x7 = xmm7;
3620 
3621    const Register tmp = rbx;
3622 
3623    BLOCK_COMMENT("Entry:");
3624    __ enter(); // required for proper stackwalking of RuntimeStub frame
3625    __ fast_tan(x0, x1, x2, x3, x4, x5, x6, x7, rax, rcx, rdx, tmp);
3626    __ leave(); // required for proper stackwalking of RuntimeStub frame
3627    __ ret(0);
3628 
3629    return start;
3630 
3631  }
3632 
3633   // Safefetch stubs.
3634   void generate_safefetch(const char* name, int size, address* entry,
3635                           address* fault_pc, address* continuation_pc) {
3636     // safefetch signatures:
3637     //   int      SafeFetch32(int*      adr, int      errValue);
3638     //   intptr_t SafeFetchN (intptr_t* adr, intptr_t errValue);
3639 
3640     StubCodeMark mark(this, "StubRoutines", name);
3641 
3642     // Entry point, pc or function descriptor.
3643     *entry = __ pc();
3644 
3645     __ movl(rax, Address(rsp, 0x8));
3646     __ movl(rcx, Address(rsp, 0x4));
3647     // Load *adr into eax, may fault.
3648     *fault_pc = __ pc();
3649     switch (size) {
3650       case 4:
3651         // int32_t
3652         __ movl(rax, Address(rcx, 0));
3653         break;
3654       case 8:
3655         // int64_t
3656         Unimplemented();
3657         break;
3658       default:
3659         ShouldNotReachHere();
3660     }
3661 
3662     // Return errValue or *adr.
3663     *continuation_pc = __ pc();
3664     __ ret(0);
3665   }
3666 
3667   address generate_method_entry_barrier() {
3668     __ align(CodeEntryAlignment);
3669     StubCodeMark mark(this, "StubRoutines", "nmethod_entry_barrier");
3670 
3671     Label deoptimize_label;
3672 
3673     address start = __ pc();
3674 
3675     __ push(-1); // cookie, this is used for writing the new rsp when deoptimizing
3676 
3677     BLOCK_COMMENT("Entry:");
3678     __ enter(); // save rbp
3679 
3680     // save rbx, because we want to use that value.
3681     // We could do without it but then we depend on the number of slots used by pusha
3682     __ push(rbx);
3683 
3684     __ lea(rbx, Address(rsp, wordSize * 3)); // 1 for cookie, 1 for rbp, 1 for rbx - this should be the return address
3685 
3686     __ pusha();
3687 
3688     // xmm0 and xmm1 may be used for passing float/double arguments
3689     const int xmm_size = wordSize * 2;
3690     const int xmm_spill_size = xmm_size * 2;
3691     __ subptr(rsp, xmm_spill_size);
3692     __ movdqu(Address(rsp, xmm_size * 1), xmm1);
3693     __ movdqu(Address(rsp, xmm_size * 0), xmm0);
3694 
3695     __ call_VM_leaf(CAST_FROM_FN_PTR(address, static_cast<int (*)(address*)>(BarrierSetNMethod::nmethod_stub_entry_barrier)), rbx);
3696 
3697     __ movdqu(xmm0, Address(rsp, xmm_size * 0));
3698     __ movdqu(xmm1, Address(rsp, xmm_size * 1));
3699     __ addptr(rsp, xmm_spill_size);
3700 
3701     __ cmpl(rax, 1); // 1 means deoptimize
3702     __ jcc(Assembler::equal, deoptimize_label);
3703 
3704     __ popa();
3705     __ pop(rbx);
3706 
3707     __ leave();
3708 
3709     __ addptr(rsp, 1 * wordSize); // cookie
3710     __ ret(0);
3711 
3712     __ BIND(deoptimize_label);
3713 
3714     __ popa();
3715     __ pop(rbx);
3716 
3717     __ leave();
3718 
3719     // this can be taken out, but is good for verification purposes. getting a SIGSEGV
3720     // here while still having a correct stack is valuable
3721     __ testptr(rsp, Address(rsp, 0));
3722 
3723     __ movptr(rsp, Address(rsp, 0)); // new rsp was written in the barrier
3724     __ jmp(Address(rsp, -1 * wordSize)); // jmp target should be callers verified_entry_point
3725 
3726     return start;
3727   }
3728 
3729  public:
3730   // Information about frame layout at time of blocking runtime call.
3731   // Note that we only have to preserve callee-saved registers since
3732   // the compilers are responsible for supplying a continuation point
3733   // if they expect all registers to be preserved.
3734   enum layout {
3735     thread_off,    // last_java_sp
3736     arg1_off,
3737     arg2_off,
3738     rbp_off,       // callee saved register
3739     ret_pc,
3740     framesize
3741   };
3742 
3743  private:
3744 
3745 #undef  __
3746 #define __ masm->
3747 
3748   //------------------------------------------------------------------------------------------------------------------------
3749   // Continuation point for throwing of implicit exceptions that are not handled in
3750   // the current activation. Fabricates an exception oop and initiates normal
3751   // exception dispatching in this frame.
3752   //
3753   // Previously the compiler (c2) allowed for callee save registers on Java calls.
3754   // This is no longer true after adapter frames were removed but could possibly
3755   // be brought back in the future if the interpreter code was reworked and it
3756   // was deemed worthwhile. The comment below was left to describe what must
3757   // happen here if callee saves were resurrected. As it stands now this stub
3758   // could actually be a vanilla BufferBlob and have now oopMap at all.
3759   // Since it doesn't make much difference we've chosen to leave it the
3760   // way it was in the callee save days and keep the comment.
3761 
3762   // If we need to preserve callee-saved values we need a callee-saved oop map and
3763   // therefore have to make these stubs into RuntimeStubs rather than BufferBlobs.
3764   // If the compiler needs all registers to be preserved between the fault
3765   // point and the exception handler then it must assume responsibility for that in
3766   // AbstractCompiler::continuation_for_implicit_null_exception or
3767   // continuation_for_implicit_division_by_zero_exception. All other implicit
3768   // exceptions (e.g., NullPointerException or AbstractMethodError on entry) are
3769   // either at call sites or otherwise assume that stack unwinding will be initiated,
3770   // so caller saved registers were assumed volatile in the compiler.
3771   address generate_throw_exception(const char* name, address runtime_entry,
3772                                    Register arg1 = noreg, Register arg2 = noreg) {
3773 
3774     int insts_size = 256;
3775     int locs_size  = 32;
3776 
3777     CodeBuffer code(name, insts_size, locs_size);
3778     OopMapSet* oop_maps  = new OopMapSet();
3779     MacroAssembler* masm = new MacroAssembler(&code);
3780 
3781     address start = __ pc();
3782 
3783     // This is an inlined and slightly modified version of call_VM
3784     // which has the ability to fetch the return PC out of
3785     // thread-local storage and also sets up last_Java_sp slightly
3786     // differently than the real call_VM
3787     Register java_thread = rbx;
3788     __ get_thread(java_thread);
3789 
3790     __ enter(); // required for proper stackwalking of RuntimeStub frame
3791 
3792     // pc and rbp, already pushed
3793     __ subptr(rsp, (framesize-2) * wordSize); // prolog
3794 
3795     // Frame is now completed as far as size and linkage.
3796 
3797     int frame_complete = __ pc() - start;
3798 
3799     // push java thread (becomes first argument of C function)
3800     __ movptr(Address(rsp, thread_off * wordSize), java_thread);
3801     if (arg1 != noreg) {
3802       __ movptr(Address(rsp, arg1_off * wordSize), arg1);
3803     }
3804     if (arg2 != noreg) {
3805       assert(arg1 != noreg, "missing reg arg");
3806       __ movptr(Address(rsp, arg2_off * wordSize), arg2);
3807     }
3808 
3809     // Set up last_Java_sp and last_Java_fp
3810     __ set_last_Java_frame(java_thread, rsp, rbp, NULL);
3811 
3812     // Call runtime
3813     BLOCK_COMMENT("call runtime_entry");
3814     __ call(RuntimeAddress(runtime_entry));
3815     // Generate oop map
3816     OopMap* map =  new OopMap(framesize, 0);
3817     oop_maps->add_gc_map(__ pc() - start, map);
3818 
3819     // restore the thread (cannot use the pushed argument since arguments
3820     // may be overwritten by C code generated by an optimizing compiler);
3821     // however can use the register value directly if it is callee saved.
3822     __ get_thread(java_thread);
3823 
3824     __ reset_last_Java_frame(java_thread, true);
3825 
3826     __ leave(); // required for proper stackwalking of RuntimeStub frame
3827 
3828     // check for pending exceptions
3829 #ifdef ASSERT
3830     Label L;
3831     __ cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3832     __ jcc(Assembler::notEqual, L);
3833     __ should_not_reach_here();
3834     __ bind(L);
3835 #endif /* ASSERT */
3836     __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3837 
3838 
3839     RuntimeStub* stub = RuntimeStub::new_runtime_stub(name, &code, frame_complete, framesize, oop_maps, false);
3840     return stub->entry_point();
3841   }
3842 
3843 
3844   void create_control_words() {
3845     // Round to nearest, 53-bit mode, exceptions masked
3846     StubRoutines::_fpu_cntrl_wrd_std   = 0x027F;
3847     // Round to zero, 53-bit mode, exception mased
3848     StubRoutines::_fpu_cntrl_wrd_trunc = 0x0D7F;
3849     // Round to nearest, 24-bit mode, exceptions masked
3850     StubRoutines::_fpu_cntrl_wrd_24    = 0x007F;
3851     // Round to nearest, 64-bit mode, exceptions masked
3852     StubRoutines::_mxcsr_std           = 0x1F80;
3853     // Note: the following two constants are 80-bit values
3854     //       layout is critical for correct loading by FPU.
3855     // Bias for strict fp multiply/divide
3856     StubRoutines::_fpu_subnormal_bias1[0]= 0x00000000; // 2^(-15360) == 0x03ff 8000 0000 0000 0000
3857     StubRoutines::_fpu_subnormal_bias1[1]= 0x80000000;
3858     StubRoutines::_fpu_subnormal_bias1[2]= 0x03ff;
3859     // Un-Bias for strict fp multiply/divide
3860     StubRoutines::_fpu_subnormal_bias2[0]= 0x00000000; // 2^(+15360) == 0x7bff 8000 0000 0000 0000
3861     StubRoutines::_fpu_subnormal_bias2[1]= 0x80000000;
3862     StubRoutines::_fpu_subnormal_bias2[2]= 0x7bff;
3863   }
3864 
3865   //---------------------------------------------------------------------------
3866   // Initialization
3867 
3868   void generate_initial() {
3869     // Generates all stubs and initializes the entry points
3870 
3871     //------------------------------------------------------------------------------------------------------------------------
3872     // entry points that exist in all platforms
3873     // Note: This is code that could be shared among different platforms - however the benefit seems to be smaller than
3874     //       the disadvantage of having a much more complicated generator structure. See also comment in stubRoutines.hpp.
3875     StubRoutines::_forward_exception_entry      = generate_forward_exception();
3876 
3877     StubRoutines::_call_stub_entry              =
3878       generate_call_stub(StubRoutines::_call_stub_return_address);
3879     // is referenced by megamorphic call
3880     StubRoutines::_catch_exception_entry        = generate_catch_exception();
3881 
3882     // These are currently used by Solaris/Intel
3883     StubRoutines::_atomic_xchg_entry            = generate_atomic_xchg();
3884 
3885     // platform dependent
3886     create_control_words();
3887 
3888     StubRoutines::x86::_verify_mxcsr_entry                 = generate_verify_mxcsr();
3889     StubRoutines::x86::_verify_fpu_cntrl_wrd_entry         = generate_verify_fpu_cntrl_wrd();
3890     StubRoutines::_d2i_wrapper                              = generate_d2i_wrapper(T_INT,
3891                                                                                    CAST_FROM_FN_PTR(address, SharedRuntime::d2i));
3892     StubRoutines::_d2l_wrapper                              = generate_d2i_wrapper(T_LONG,
3893                                                                                    CAST_FROM_FN_PTR(address, SharedRuntime::d2l));
3894 
3895     // Build this early so it's available for the interpreter
3896     StubRoutines::_throw_StackOverflowError_entry          = generate_throw_exception("StackOverflowError throw_exception",
3897                                                                                       CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError));
3898     StubRoutines::_throw_delayed_StackOverflowError_entry  = generate_throw_exception("delayed StackOverflowError throw_exception",
3899                                                                                       CAST_FROM_FN_PTR(address, SharedRuntime::throw_delayed_StackOverflowError));
3900 
3901     if (UseCRC32Intrinsics) {
3902       // set table address before stub generation which use it
3903       StubRoutines::_crc_table_adr = (address)StubRoutines::x86::_crc_table;
3904       StubRoutines::_updateBytesCRC32 = generate_updateBytesCRC32();
3905     }
3906 
3907     if (UseCRC32CIntrinsics) {
3908       bool supports_clmul = VM_Version::supports_clmul();
3909       StubRoutines::x86::generate_CRC32C_table(supports_clmul);
3910       StubRoutines::_crc32c_table_addr = (address)StubRoutines::x86::_crc32c_table;
3911       StubRoutines::_updateBytesCRC32C = generate_updateBytesCRC32C(supports_clmul);
3912     }
3913     if (VM_Version::supports_sse2() && UseLibmIntrinsic && InlineIntrinsics) {
3914       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dsin) ||
3915           vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dcos) ||
3916           vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dtan)) {
3917         StubRoutines::x86::_L_2il0floatpacket_0_adr = (address)StubRoutines::x86::_L_2il0floatpacket_0;
3918         StubRoutines::x86::_Pi4Inv_adr = (address)StubRoutines::x86::_Pi4Inv;
3919         StubRoutines::x86::_Pi4x3_adr = (address)StubRoutines::x86::_Pi4x3;
3920         StubRoutines::x86::_Pi4x4_adr = (address)StubRoutines::x86::_Pi4x4;
3921         StubRoutines::x86::_ones_adr = (address)StubRoutines::x86::_ones;
3922       }
3923       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dexp)) {
3924         StubRoutines::_dexp = generate_libmExp();
3925       }
3926       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dlog)) {
3927         StubRoutines::_dlog = generate_libmLog();
3928       }
3929       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dlog10)) {
3930         StubRoutines::_dlog10 = generate_libmLog10();
3931       }
3932       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dpow)) {
3933         StubRoutines::_dpow = generate_libmPow();
3934       }
3935       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dsin) ||
3936         vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dcos) ||
3937         vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dtan)) {
3938         StubRoutines::_dlibm_reduce_pi04l = generate_libm_reduce_pi04l();
3939       }
3940       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dsin) ||
3941         vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dcos)) {
3942         StubRoutines::_dlibm_sin_cos_huge = generate_libm_sin_cos_huge();
3943       }
3944       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dsin)) {
3945         StubRoutines::_dsin = generate_libmSin();
3946       }
3947       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dcos)) {
3948         StubRoutines::_dcos = generate_libmCos();
3949       }
3950       if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_dtan)) {
3951         StubRoutines::_dlibm_tan_cot_huge = generate_libm_tan_cot_huge();
3952         StubRoutines::_dtan = generate_libmTan();
3953       }
3954     }
3955   }
3956 
3957   void generate_all() {
3958     // Generates all stubs and initializes the entry points
3959 
3960     // These entry points require SharedInfo::stack0 to be set up in non-core builds
3961     // and need to be relocatable, so they each fabricate a RuntimeStub internally.
3962     StubRoutines::_throw_AbstractMethodError_entry         = generate_throw_exception("AbstractMethodError throw_exception",          CAST_FROM_FN_PTR(address, SharedRuntime::throw_AbstractMethodError));
3963     StubRoutines::_throw_IncompatibleClassChangeError_entry= generate_throw_exception("IncompatibleClassChangeError throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_IncompatibleClassChangeError));
3964     StubRoutines::_throw_NullPointerException_at_call_entry= generate_throw_exception("NullPointerException at call throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException_at_call));
3965 
3966     //------------------------------------------------------------------------------------------------------------------------
3967     // entry points that are platform specific
3968 
3969     StubRoutines::x86::_vector_float_sign_mask = generate_vector_mask("vector_float_sign_mask", 0x7FFFFFFF);
3970     StubRoutines::x86::_vector_float_sign_flip = generate_vector_mask("vector_float_sign_flip", 0x80000000);
3971     StubRoutines::x86::_vector_double_sign_mask = generate_vector_mask_long_double("vector_double_sign_mask", 0x7FFFFFFF, 0xFFFFFFFF);
3972     StubRoutines::x86::_vector_double_sign_flip = generate_vector_mask_long_double("vector_double_sign_flip", 0x80000000, 0x00000000);
3973     StubRoutines::x86::_vector_short_to_byte_mask = generate_vector_mask("vector_short_to_byte_mask", 0x00ff00ff);
3974     StubRoutines::x86::_vector_byte_perm_mask = generate_vector_byte_perm_mask("vector_byte_perm_mask");
3975     StubRoutines::x86::_vector_long_sign_mask = generate_vector_mask_long_double("vector_long_sign_mask", 0x80000000, 0x00000000);
3976 
3977     // support for verify_oop (must happen after universe_init)
3978     StubRoutines::_verify_oop_subroutine_entry     = generate_verify_oop();
3979 
3980     // arraycopy stubs used by compilers
3981     generate_arraycopy_stubs();
3982 
3983     // don't bother generating these AES intrinsic stubs unless global flag is set
3984     if (UseAESIntrinsics) {
3985       StubRoutines::x86::_key_shuffle_mask_addr = generate_key_shuffle_mask();  // might be needed by the others
3986 
3987       StubRoutines::_aescrypt_encryptBlock = generate_aescrypt_encryptBlock();
3988       StubRoutines::_aescrypt_decryptBlock = generate_aescrypt_decryptBlock();
3989       StubRoutines::_cipherBlockChaining_encryptAESCrypt = generate_cipherBlockChaining_encryptAESCrypt();
3990       StubRoutines::_cipherBlockChaining_decryptAESCrypt = generate_cipherBlockChaining_decryptAESCrypt_Parallel();
3991     }
3992 
3993     if (UseAESCTRIntrinsics) {
3994       StubRoutines::x86::_counter_shuffle_mask_addr = generate_counter_shuffle_mask();
3995       StubRoutines::_counterMode_AESCrypt = generate_counterMode_AESCrypt_Parallel();
3996     }
3997 
3998     if (UseSHA1Intrinsics) {
3999       StubRoutines::x86::_upper_word_mask_addr = generate_upper_word_mask();
4000       StubRoutines::x86::_shuffle_byte_flip_mask_addr = generate_shuffle_byte_flip_mask();
4001       StubRoutines::_sha1_implCompress = generate_sha1_implCompress(false, "sha1_implCompress");
4002       StubRoutines::_sha1_implCompressMB = generate_sha1_implCompress(true, "sha1_implCompressMB");
4003     }
4004     if (UseSHA256Intrinsics) {
4005       StubRoutines::x86::_k256_adr = (address)StubRoutines::x86::_k256;
4006       StubRoutines::x86::_pshuffle_byte_flip_mask_addr = generate_pshuffle_byte_flip_mask();
4007       StubRoutines::_sha256_implCompress = generate_sha256_implCompress(false, "sha256_implCompress");
4008       StubRoutines::_sha256_implCompressMB = generate_sha256_implCompress(true, "sha256_implCompressMB");
4009     }
4010 
4011     // Generate GHASH intrinsics code
4012     if (UseGHASHIntrinsics) {
4013       StubRoutines::x86::_ghash_long_swap_mask_addr = generate_ghash_long_swap_mask();
4014       StubRoutines::x86::_ghash_byte_swap_mask_addr = generate_ghash_byte_swap_mask();
4015       StubRoutines::_ghash_processBlocks = generate_ghash_processBlocks();
4016     }
4017 
4018     // Safefetch stubs.
4019     generate_safefetch("SafeFetch32", sizeof(int), &StubRoutines::_safefetch32_entry,
4020                                                    &StubRoutines::_safefetch32_fault_pc,
4021                                                    &StubRoutines::_safefetch32_continuation_pc);
4022     StubRoutines::_safefetchN_entry           = StubRoutines::_safefetch32_entry;
4023     StubRoutines::_safefetchN_fault_pc        = StubRoutines::_safefetch32_fault_pc;
4024     StubRoutines::_safefetchN_continuation_pc = StubRoutines::_safefetch32_continuation_pc;
4025 
4026     BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
4027     if (bs_nm != NULL) {
4028       StubRoutines::x86::_method_entry_barrier = generate_method_entry_barrier();
4029     }
4030   }
4031 
4032 
4033  public:
4034   StubGenerator(CodeBuffer* code, bool all) : StubCodeGenerator(code) {
4035     if (all) {
4036       generate_all();
4037     } else {
4038       generate_initial();
4039     }
4040   }
4041 }; // end class declaration
4042 
4043 #define UCM_TABLE_MAX_ENTRIES 8
4044 void StubGenerator_generate(CodeBuffer* code, bool all) {
4045   if (UnsafeCopyMemory::_table == NULL) {
4046     UnsafeCopyMemory::create_table(UCM_TABLE_MAX_ENTRIES);
4047   }
4048   StubGenerator g(code, all);
4049 }