1 /*
   2  * Copyright (c) 1999, 2015, 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 "interpreter/interpreter.hpp"
  29 #include "nativeInst_x86.hpp"
  30 #include "oops/instanceOop.hpp"
  31 #include "oops/method.hpp"
  32 #include "oops/objArrayKlass.hpp"
  33 #include "oops/oop.inline.hpp"
  34 #include "prims/methodHandles.hpp"
  35 #include "runtime/frame.inline.hpp"
  36 #include "runtime/handles.inline.hpp"
  37 #include "runtime/sharedRuntime.hpp"
  38 #include "runtime/stubCodeGenerator.hpp"
  39 #include "runtime/stubRoutines.hpp"
  40 #include "runtime/thread.inline.hpp"
  41 #include "utilities/top.hpp"
  42 #ifdef COMPILER2
  43 #include "opto/runtime.hpp"
  44 #endif
  45 
  46 // Declaration and definition of StubGenerator (no .hpp file).
  47 // For a more detailed description of the stub routine structure
  48 // see the comment in stubRoutines.hpp
  49 
  50 #define __ _masm->
  51 #define a__ ((Assembler*)_masm)->
  52 
  53 #ifdef PRODUCT
  54 #define BLOCK_COMMENT(str) /* nothing */
  55 #else
  56 #define BLOCK_COMMENT(str) __ block_comment(str)
  57 #endif
  58 
  59 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  60 
  61 const int MXCSR_MASK  = 0xFFC0;  // Mask out any pending exceptions
  62 const int FPU_CNTRL_WRD_MASK = 0xFFFF;
  63 
  64 // -------------------------------------------------------------------------------------------------------------------------
  65 // Stub Code definitions
  66 
  67 static address handle_unsafe_access() {
  68   JavaThread* thread = JavaThread::current();
  69   address pc  = thread->saved_exception_pc();
  70   // pc is the instruction which we must emulate
  71   // doing a no-op is fine:  return garbage from the load
  72   // therefore, compute npc
  73   address npc = Assembler::locate_next_instruction(pc);
  74 
  75   // request an async exception
  76   thread->set_pending_unsafe_access_error();
  77 
  78   // return address of next instruction to execute
  79   return npc;
  80 }
  81 
  82 class StubGenerator: public StubCodeGenerator {
  83  private:
  84 
  85 #ifdef PRODUCT
  86 #define inc_counter_np(counter) ((void)0)
  87 #else
  88   void inc_counter_np_(int& counter) {
  89     __ incrementl(ExternalAddress((address)&counter));
  90   }
  91 #define inc_counter_np(counter) \
  92   BLOCK_COMMENT("inc_counter " #counter); \
  93   inc_counter_np_(counter);
  94 #endif //PRODUCT
  95 
  96   void inc_copy_counter_np(BasicType t) {
  97 #ifndef PRODUCT
  98     switch (t) {
  99     case T_BYTE:    inc_counter_np(SharedRuntime::_jbyte_array_copy_ctr); return;
 100     case T_SHORT:   inc_counter_np(SharedRuntime::_jshort_array_copy_ctr); return;
 101     case T_INT:     inc_counter_np(SharedRuntime::_jint_array_copy_ctr); return;
 102     case T_LONG:    inc_counter_np(SharedRuntime::_jlong_array_copy_ctr); return;
 103     case T_OBJECT:  inc_counter_np(SharedRuntime::_oop_array_copy_ctr); return;
 104     }
 105     ShouldNotReachHere();
 106 #endif //PRODUCT
 107   }
 108 
 109   //------------------------------------------------------------------------------------------------------------------------
 110   // Call stubs are used to call Java from C
 111   //
 112   //    [ return_from_Java     ] <--- rsp
 113   //    [ argument word n      ]
 114   //      ...
 115   // -N [ argument word 1      ]
 116   // -7 [ Possible padding for stack alignment ]
 117   // -6 [ Possible padding for stack alignment ]
 118   // -5 [ Possible padding for stack alignment ]
 119   // -4 [ mxcsr save           ] <--- rsp_after_call
 120   // -3 [ saved rbx,            ]
 121   // -2 [ saved rsi            ]
 122   // -1 [ saved rdi            ]
 123   //  0 [ saved rbp,            ] <--- rbp,
 124   //  1 [ return address       ]
 125   //  2 [ ptr. to call wrapper ]
 126   //  3 [ result               ]
 127   //  4 [ result_type          ]
 128   //  5 [ method               ]
 129   //  6 [ entry_point          ]
 130   //  7 [ parameters           ]
 131   //  8 [ parameter_size       ]
 132   //  9 [ thread               ]
 133 
 134 
 135   address generate_call_stub(address& return_address) {
 136     StubCodeMark mark(this, "StubRoutines", "call_stub");
 137     address start = __ pc();
 138 
 139     // stub code parameters / addresses
 140     assert(frame::entry_frame_call_wrapper_offset == 2, "adjust this code");
 141     bool  sse_save = false;
 142     const Address rsp_after_call(rbp, -4 * wordSize); // same as in generate_catch_exception()!
 143     const int     locals_count_in_bytes  (4*wordSize);
 144     const Address mxcsr_save    (rbp, -4 * wordSize);
 145     const Address saved_rbx     (rbp, -3 * wordSize);
 146     const Address saved_rsi     (rbp, -2 * wordSize);
 147     const Address saved_rdi     (rbp, -1 * wordSize);
 148     const Address result        (rbp,  3 * wordSize);
 149     const Address result_type   (rbp,  4 * wordSize);
 150     const Address method        (rbp,  5 * wordSize);
 151     const Address entry_point   (rbp,  6 * wordSize);
 152     const Address parameters    (rbp,  7 * wordSize);
 153     const Address parameter_size(rbp,  8 * wordSize);
 154     const Address thread        (rbp,  9 * wordSize); // same as in generate_catch_exception()!
 155     sse_save =  UseSSE > 0;
 156 
 157     // stub code
 158     __ enter();
 159     __ movptr(rcx, parameter_size);              // parameter counter
 160     __ shlptr(rcx, Interpreter::logStackElementSize); // convert parameter count to bytes
 161     __ addptr(rcx, locals_count_in_bytes);       // reserve space for register saves
 162     __ subptr(rsp, rcx);
 163     __ andptr(rsp, -(StackAlignmentInBytes));    // Align stack
 164 
 165     // save rdi, rsi, & rbx, according to C calling conventions
 166     __ movptr(saved_rdi, rdi);
 167     __ movptr(saved_rsi, rsi);
 168     __ movptr(saved_rbx, rbx);
 169 
 170     // provide initial value for required masks
 171     if (UseAVX > 2) {
 172       __ movl(rbx, 0xffff);
 173       __ kmovdl(k1, rbx);
 174     }
 175 
 176     // save and initialize %mxcsr
 177     if (sse_save) {
 178       Label skip_ldmx;
 179       __ stmxcsr(mxcsr_save);
 180       __ movl(rax, mxcsr_save);
 181       __ andl(rax, MXCSR_MASK);    // Only check control and mask bits
 182       ExternalAddress mxcsr_std(StubRoutines::addr_mxcsr_std());
 183       __ cmp32(rax, mxcsr_std);
 184       __ jcc(Assembler::equal, skip_ldmx);
 185       __ ldmxcsr(mxcsr_std);
 186       __ bind(skip_ldmx);
 187     }
 188 
 189     // make sure the control word is correct.
 190     __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
 191 
 192 #ifdef ASSERT
 193     // make sure we have no pending exceptions
 194     { Label L;
 195       __ movptr(rcx, thread);
 196       __ cmpptr(Address(rcx, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
 197       __ jcc(Assembler::equal, L);
 198       __ stop("StubRoutines::call_stub: entered with pending exception");
 199       __ bind(L);
 200     }
 201 #endif
 202 
 203     // pass parameters if any
 204     BLOCK_COMMENT("pass parameters if any");
 205     Label parameters_done;
 206     __ movl(rcx, parameter_size);  // parameter counter
 207     __ testl(rcx, rcx);
 208     __ jcc(Assembler::zero, parameters_done);
 209 
 210     // parameter passing loop
 211 
 212     Label loop;
 213     // Copy Java parameters in reverse order (receiver last)
 214     // Note that the argument order is inverted in the process
 215     // source is rdx[rcx: N-1..0]
 216     // dest   is rsp[rbx: 0..N-1]
 217 
 218     __ movptr(rdx, parameters);          // parameter pointer
 219     __ xorptr(rbx, rbx);
 220 
 221     __ BIND(loop);
 222 
 223     // get parameter
 224     __ movptr(rax, Address(rdx, rcx, Interpreter::stackElementScale(), -wordSize));
 225     __ movptr(Address(rsp, rbx, Interpreter::stackElementScale(),
 226                     Interpreter::expr_offset_in_bytes(0)), rax);          // store parameter
 227     __ increment(rbx);
 228     __ decrement(rcx);
 229     __ jcc(Assembler::notZero, loop);
 230 
 231     // call Java function
 232     __ BIND(parameters_done);
 233     __ movptr(rbx, method);           // get Method*
 234     __ movptr(rax, entry_point);      // get entry_point
 235     __ mov(rsi, rsp);                 // set sender sp
 236     BLOCK_COMMENT("call Java function");
 237     __ call(rax);
 238 
 239     BLOCK_COMMENT("call_stub_return_address:");
 240     return_address = __ pc();
 241 
 242 #ifdef COMPILER2
 243     {
 244       Label L_skip;
 245       if (UseSSE >= 2) {
 246         __ verify_FPU(0, "call_stub_return");
 247       } else {
 248         for (int i = 1; i < 8; i++) {
 249           __ ffree(i);
 250         }
 251 
 252         // UseSSE <= 1 so double result should be left on TOS
 253         __ movl(rsi, result_type);
 254         __ cmpl(rsi, T_DOUBLE);
 255         __ jcc(Assembler::equal, L_skip);
 256         if (UseSSE == 0) {
 257           // UseSSE == 0 so float result should be left on TOS
 258           __ cmpl(rsi, T_FLOAT);
 259           __ jcc(Assembler::equal, L_skip);
 260         }
 261         __ ffree(0);
 262       }
 263       __ BIND(L_skip);
 264     }
 265 #endif // COMPILER2
 266 
 267     // store result depending on type
 268     // (everything that is not T_LONG, T_FLOAT or T_DOUBLE is treated as T_INT)
 269     __ movptr(rdi, result);
 270     Label is_long, is_float, is_double, exit;
 271     __ movl(rsi, result_type);
 272     __ cmpl(rsi, T_LONG);
 273     __ jcc(Assembler::equal, is_long);
 274     __ cmpl(rsi, T_FLOAT);
 275     __ jcc(Assembler::equal, is_float);
 276     __ cmpl(rsi, T_DOUBLE);
 277     __ jcc(Assembler::equal, is_double);
 278 
 279     // handle T_INT case
 280     __ movl(Address(rdi, 0), rax);
 281     __ BIND(exit);
 282 
 283     // check that FPU stack is empty
 284     __ verify_FPU(0, "generate_call_stub");
 285 
 286     // pop parameters
 287     __ lea(rsp, rsp_after_call);
 288 
 289     // restore %mxcsr
 290     if (sse_save) {
 291       __ ldmxcsr(mxcsr_save);
 292     }
 293 
 294     // restore rdi, rsi and rbx,
 295     __ movptr(rbx, saved_rbx);
 296     __ movptr(rsi, saved_rsi);
 297     __ movptr(rdi, saved_rdi);
 298     __ addptr(rsp, 4*wordSize);
 299 
 300     // return
 301     __ pop(rbp);
 302     __ ret(0);
 303 
 304     // handle return types different from T_INT
 305     __ BIND(is_long);
 306     __ movl(Address(rdi, 0 * wordSize), rax);
 307     __ movl(Address(rdi, 1 * wordSize), rdx);
 308     __ jmp(exit);
 309 
 310     __ BIND(is_float);
 311     // interpreter uses xmm0 for return values
 312     if (UseSSE >= 1) {
 313       __ movflt(Address(rdi, 0), xmm0);
 314     } else {
 315       __ fstp_s(Address(rdi, 0));
 316     }
 317     __ jmp(exit);
 318 
 319     __ BIND(is_double);
 320     // interpreter uses xmm0 for return values
 321     if (UseSSE >= 2) {
 322       __ movdbl(Address(rdi, 0), xmm0);
 323     } else {
 324       __ fstp_d(Address(rdi, 0));
 325     }
 326     __ jmp(exit);
 327 
 328     return start;
 329   }
 330 
 331 
 332   //------------------------------------------------------------------------------------------------------------------------
 333   // Return point for a Java call if there's an exception thrown in Java code.
 334   // The exception is caught and transformed into a pending exception stored in
 335   // JavaThread that can be tested from within the VM.
 336   //
 337   // Note: Usually the parameters are removed by the callee. In case of an exception
 338   //       crossing an activation frame boundary, that is not the case if the callee
 339   //       is compiled code => need to setup the rsp.
 340   //
 341   // rax,: exception oop
 342 
 343   address generate_catch_exception() {
 344     StubCodeMark mark(this, "StubRoutines", "catch_exception");
 345     const Address rsp_after_call(rbp, -4 * wordSize); // same as in generate_call_stub()!
 346     const Address thread        (rbp,  9 * wordSize); // same as in generate_call_stub()!
 347     address start = __ pc();
 348 
 349     // get thread directly
 350     __ movptr(rcx, thread);
 351 #ifdef ASSERT
 352     // verify that threads correspond
 353     { Label L;
 354       __ get_thread(rbx);
 355       __ cmpptr(rbx, rcx);
 356       __ jcc(Assembler::equal, L);
 357       __ stop("StubRoutines::catch_exception: threads must correspond");
 358       __ bind(L);
 359     }
 360 #endif
 361     // set pending exception
 362     __ verify_oop(rax);
 363     __ movptr(Address(rcx, Thread::pending_exception_offset()), rax          );
 364     __ lea(Address(rcx, Thread::exception_file_offset   ()),
 365            ExternalAddress((address)__FILE__));
 366     __ movl(Address(rcx, Thread::exception_line_offset   ()), __LINE__ );
 367     // complete return to VM
 368     assert(StubRoutines::_call_stub_return_address != NULL, "_call_stub_return_address must have been generated before");
 369     __ jump(RuntimeAddress(StubRoutines::_call_stub_return_address));
 370 
 371     return start;
 372   }
 373 
 374 
 375   //------------------------------------------------------------------------------------------------------------------------
 376   // Continuation point for runtime calls returning with a pending exception.
 377   // The pending exception check happened in the runtime or native call stub.
 378   // The pending exception in Thread is converted into a Java-level exception.
 379   //
 380   // Contract with Java-level exception handlers:
 381   // rax: exception
 382   // rdx: throwing pc
 383   //
 384   // NOTE: At entry of this stub, exception-pc must be on stack !!
 385 
 386   address generate_forward_exception() {
 387     StubCodeMark mark(this, "StubRoutines", "forward exception");
 388     address start = __ pc();
 389     const Register thread = rcx;
 390 
 391     // other registers used in this stub
 392     const Register exception_oop = rax;
 393     const Register handler_addr  = rbx;
 394     const Register exception_pc  = rdx;
 395 
 396     // Upon entry, the sp points to the return address returning into Java
 397     // (interpreted or compiled) code; i.e., the return address becomes the
 398     // throwing pc.
 399     //
 400     // Arguments pushed before the runtime call are still on the stack but
 401     // the exception handler will reset the stack pointer -> ignore them.
 402     // A potential result in registers can be ignored as well.
 403 
 404 #ifdef ASSERT
 405     // make sure this code is only executed if there is a pending exception
 406     { Label L;
 407       __ get_thread(thread);
 408       __ cmpptr(Address(thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
 409       __ jcc(Assembler::notEqual, L);
 410       __ stop("StubRoutines::forward exception: no pending exception (1)");
 411       __ bind(L);
 412     }
 413 #endif
 414 
 415     // compute exception handler into rbx,
 416     __ get_thread(thread);
 417     __ movptr(exception_pc, Address(rsp, 0));
 418     BLOCK_COMMENT("call exception_handler_for_return_address");
 419     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address), thread, exception_pc);
 420     __ mov(handler_addr, rax);
 421 
 422     // setup rax & rdx, remove return address & clear pending exception
 423     __ get_thread(thread);
 424     __ pop(exception_pc);
 425     __ movptr(exception_oop, Address(thread, Thread::pending_exception_offset()));
 426     __ movptr(Address(thread, Thread::pending_exception_offset()), NULL_WORD);
 427 
 428 #ifdef ASSERT
 429     // make sure exception is set
 430     { Label L;
 431       __ testptr(exception_oop, exception_oop);
 432       __ jcc(Assembler::notEqual, L);
 433       __ stop("StubRoutines::forward exception: no pending exception (2)");
 434       __ bind(L);
 435     }
 436 #endif
 437 
 438     // Verify that there is really a valid exception in RAX.
 439     __ verify_oop(exception_oop);
 440 
 441     // continue at exception handler (return address removed)
 442     // rax: exception
 443     // rbx: exception handler
 444     // rdx: throwing pc
 445     __ jmp(handler_addr);
 446 
 447     return start;
 448   }
 449 
 450 
 451   //----------------------------------------------------------------------------------------------------
 452   // Support for jint Atomic::xchg(jint exchange_value, volatile jint* dest)
 453   //
 454   // xchg exists as far back as 8086, lock needed for MP only
 455   // Stack layout immediately after call:
 456   //
 457   // 0 [ret addr ] <--- rsp
 458   // 1 [  ex     ]
 459   // 2 [  dest   ]
 460   //
 461   // Result:   *dest <- ex, return (old *dest)
 462   //
 463   // Note: win32 does not currently use this code
 464 
 465   address generate_atomic_xchg() {
 466     StubCodeMark mark(this, "StubRoutines", "atomic_xchg");
 467     address start = __ pc();
 468 
 469     __ push(rdx);
 470     Address exchange(rsp, 2 * wordSize);
 471     Address dest_addr(rsp, 3 * wordSize);
 472     __ movl(rax, exchange);
 473     __ movptr(rdx, dest_addr);
 474     __ xchgl(rax, Address(rdx, 0));
 475     __ pop(rdx);
 476     __ ret(0);
 477 
 478     return start;
 479   }
 480 
 481   //----------------------------------------------------------------------------------------------------
 482   // Support for void verify_mxcsr()
 483   //
 484   // This routine is used with -Xcheck:jni to verify that native
 485   // JNI code does not return to Java code without restoring the
 486   // MXCSR register to our expected state.
 487 
 488 
 489   address generate_verify_mxcsr() {
 490     StubCodeMark mark(this, "StubRoutines", "verify_mxcsr");
 491     address start = __ pc();
 492 
 493     const Address mxcsr_save(rsp, 0);
 494 
 495     if (CheckJNICalls && UseSSE > 0 ) {
 496       Label ok_ret;
 497       ExternalAddress mxcsr_std(StubRoutines::addr_mxcsr_std());
 498       __ push(rax);
 499       __ subptr(rsp, wordSize);      // allocate a temp location
 500       __ stmxcsr(mxcsr_save);
 501       __ movl(rax, mxcsr_save);
 502       __ andl(rax, MXCSR_MASK);
 503       __ cmp32(rax, mxcsr_std);
 504       __ jcc(Assembler::equal, ok_ret);
 505 
 506       __ warn("MXCSR changed by native JNI code.");
 507 
 508       __ ldmxcsr(mxcsr_std);
 509 
 510       __ bind(ok_ret);
 511       __ addptr(rsp, wordSize);
 512       __ pop(rax);
 513     }
 514 
 515     __ ret(0);
 516 
 517     return start;
 518   }
 519 
 520 
 521   //---------------------------------------------------------------------------
 522   // Support for void verify_fpu_cntrl_wrd()
 523   //
 524   // This routine is used with -Xcheck:jni to verify that native
 525   // JNI code does not return to Java code without restoring the
 526   // FP control word to our expected state.
 527 
 528   address generate_verify_fpu_cntrl_wrd() {
 529     StubCodeMark mark(this, "StubRoutines", "verify_spcw");
 530     address start = __ pc();
 531 
 532     const Address fpu_cntrl_wrd_save(rsp, 0);
 533 
 534     if (CheckJNICalls) {
 535       Label ok_ret;
 536       __ push(rax);
 537       __ subptr(rsp, wordSize);      // allocate a temp location
 538       __ fnstcw(fpu_cntrl_wrd_save);
 539       __ movl(rax, fpu_cntrl_wrd_save);
 540       __ andl(rax, FPU_CNTRL_WRD_MASK);
 541       ExternalAddress fpu_std(StubRoutines::addr_fpu_cntrl_wrd_std());
 542       __ cmp32(rax, fpu_std);
 543       __ jcc(Assembler::equal, ok_ret);
 544 
 545       __ warn("Floating point control word changed by native JNI code.");
 546 
 547       __ fldcw(fpu_std);
 548 
 549       __ bind(ok_ret);
 550       __ addptr(rsp, wordSize);
 551       __ pop(rax);
 552     }
 553 
 554     __ ret(0);
 555 
 556     return start;
 557   }
 558 
 559   //---------------------------------------------------------------------------
 560   // Wrapper for slow-case handling of double-to-integer conversion
 561   // d2i or f2i fast case failed either because it is nan or because
 562   // of under/overflow.
 563   // Input:  FPU TOS: float value
 564   // Output: rax, (rdx): integer (long) result
 565 
 566   address generate_d2i_wrapper(BasicType t, address fcn) {
 567     StubCodeMark mark(this, "StubRoutines", "d2i_wrapper");
 568     address start = __ pc();
 569 
 570   // Capture info about frame layout
 571   enum layout { FPUState_off         = 0,
 572                 rbp_off              = FPUStateSizeInWords,
 573                 rdi_off,
 574                 rsi_off,
 575                 rcx_off,
 576                 rbx_off,
 577                 saved_argument_off,
 578                 saved_argument_off2, // 2nd half of double
 579                 framesize
 580   };
 581 
 582   assert(FPUStateSizeInWords == 27, "update stack layout");
 583 
 584     // Save outgoing argument to stack across push_FPU_state()
 585     __ subptr(rsp, wordSize * 2);
 586     __ fstp_d(Address(rsp, 0));
 587 
 588     // Save CPU & FPU state
 589     __ push(rbx);
 590     __ push(rcx);
 591     __ push(rsi);
 592     __ push(rdi);
 593     __ push(rbp);
 594     __ push_FPU_state();
 595 
 596     // push_FPU_state() resets the FP top of stack
 597     // Load original double into FP top of stack
 598     __ fld_d(Address(rsp, saved_argument_off * wordSize));
 599     // Store double into stack as outgoing argument
 600     __ subptr(rsp, wordSize*2);
 601     __ fst_d(Address(rsp, 0));
 602 
 603     // Prepare FPU for doing math in C-land
 604     __ empty_FPU_stack();
 605     // Call the C code to massage the double.  Result in EAX
 606     if (t == T_INT)
 607       { BLOCK_COMMENT("SharedRuntime::d2i"); }
 608     else if (t == T_LONG)
 609       { BLOCK_COMMENT("SharedRuntime::d2l"); }
 610     __ call_VM_leaf( fcn, 2 );
 611 
 612     // Restore CPU & FPU state
 613     __ pop_FPU_state();
 614     __ pop(rbp);
 615     __ pop(rdi);
 616     __ pop(rsi);
 617     __ pop(rcx);
 618     __ pop(rbx);
 619     __ addptr(rsp, wordSize * 2);
 620 
 621     __ ret(0);
 622 
 623     return start;
 624   }
 625 
 626 
 627   //---------------------------------------------------------------------------
 628   // The following routine generates a subroutine to throw an asynchronous
 629   // UnknownError when an unsafe access gets a fault that could not be
 630   // reasonably prevented by the programmer.  (Example: SIGBUS/OBJERR.)
 631   address generate_handler_for_unsafe_access() {
 632     StubCodeMark mark(this, "StubRoutines", "handler_for_unsafe_access");
 633     address start = __ pc();
 634 
 635     __ push(0);                       // hole for return address-to-be
 636     __ pusha();                       // push registers
 637     Address next_pc(rsp, RegisterImpl::number_of_registers * BytesPerWord);
 638     BLOCK_COMMENT("call handle_unsafe_access");
 639     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, handle_unsafe_access)));
 640     __ movptr(next_pc, rax);          // stuff next address
 641     __ popa();
 642     __ ret(0);                        // jump to next address
 643 
 644     return start;
 645   }
 646 
 647 
 648   //----------------------------------------------------------------------------------------------------
 649   // Non-destructive plausibility checks for oops
 650 
 651   address generate_verify_oop() {
 652     StubCodeMark mark(this, "StubRoutines", "verify_oop");
 653     address start = __ pc();
 654 
 655     // Incoming arguments on stack after saving rax,:
 656     //
 657     // [tos    ]: saved rdx
 658     // [tos + 1]: saved EFLAGS
 659     // [tos + 2]: return address
 660     // [tos + 3]: char* error message
 661     // [tos + 4]: oop   object to verify
 662     // [tos + 5]: saved rax, - saved by caller and bashed
 663 
 664     Label exit, error;
 665     __ pushf();
 666     __ incrementl(ExternalAddress((address) StubRoutines::verify_oop_count_addr()));
 667     __ push(rdx);                                // save rdx
 668     // make sure object is 'reasonable'
 669     __ movptr(rax, Address(rsp, 4 * wordSize));    // get object
 670     __ testptr(rax, rax);
 671     __ jcc(Assembler::zero, exit);               // if obj is NULL it is ok
 672 
 673     // Check if the oop is in the right area of memory
 674     const int oop_mask = Universe::verify_oop_mask();
 675     const int oop_bits = Universe::verify_oop_bits();
 676     __ mov(rdx, rax);
 677     __ andptr(rdx, oop_mask);
 678     __ cmpptr(rdx, oop_bits);
 679     __ jcc(Assembler::notZero, error);
 680 
 681     // make sure klass is 'reasonable', which is not zero.
 682     __ movptr(rax, Address(rax, oopDesc::klass_offset_in_bytes())); // get klass
 683     __ testptr(rax, rax);
 684     __ jcc(Assembler::zero, error);              // if klass is NULL it is broken
 685 
 686     // return if everything seems ok
 687     __ bind(exit);
 688     __ movptr(rax, Address(rsp, 5 * wordSize));  // get saved rax, back
 689     __ pop(rdx);                                 // restore rdx
 690     __ popf();                                   // restore EFLAGS
 691     __ ret(3 * wordSize);                        // pop arguments
 692 
 693     // handle errors
 694     __ bind(error);
 695     __ movptr(rax, Address(rsp, 5 * wordSize));  // get saved rax, back
 696     __ pop(rdx);                                 // get saved rdx back
 697     __ popf();                                   // get saved EFLAGS off stack -- will be ignored
 698     __ pusha();                                  // push registers (eip = return address & msg are already pushed)
 699     BLOCK_COMMENT("call MacroAssembler::debug");
 700     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 701     __ popa();
 702     __ ret(3 * wordSize);                        // pop arguments
 703     return start;
 704   }
 705 
 706   //
 707   //  Generate pre-barrier for array stores
 708   //
 709   //  Input:
 710   //     start   -  starting address
 711   //     count   -  element count
 712   void  gen_write_ref_array_pre_barrier(Register start, Register count, bool uninitialized_target) {
 713     assert_different_registers(start, count);
 714     BarrierSet* bs = Universe::heap()->barrier_set();
 715     switch (bs->kind()) {
 716       case BarrierSet::G1SATBCTLogging:
 717         // With G1, don't generate the call if we statically know that the target in uninitialized
 718         if (!uninitialized_target) {
 719            __ pusha();                      // push registers
 720            __ call_VM_leaf(CAST_FROM_FN_PTR(address, BarrierSet::static_write_ref_array_pre),
 721                            start, count);
 722            __ popa();
 723          }
 724         break;
 725       case BarrierSet::CardTableModRef:
 726       case BarrierSet::CardTableExtension:
 727       case BarrierSet::ModRef:
 728         break;
 729       default      :
 730         ShouldNotReachHere();
 731 
 732     }
 733   }
 734 
 735 
 736   //
 737   // Generate a post-barrier for an array store
 738   //
 739   //     start    -  starting address
 740   //     count    -  element count
 741   //
 742   //  The two input registers are overwritten.
 743   //
 744   void  gen_write_ref_array_post_barrier(Register start, Register count) {
 745     BarrierSet* bs = Universe::heap()->barrier_set();
 746     assert_different_registers(start, count);
 747     switch (bs->kind()) {
 748       case BarrierSet::G1SATBCTLogging:
 749         {
 750           __ pusha();                      // push registers
 751           __ call_VM_leaf(CAST_FROM_FN_PTR(address, BarrierSet::static_write_ref_array_post),
 752                           start, count);
 753           __ popa();
 754         }
 755         break;
 756 
 757       case BarrierSet::CardTableModRef:
 758       case BarrierSet::CardTableExtension:
 759         {
 760           CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
 761           assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
 762 
 763           Label L_loop;
 764           const Register end = count;  // elements count; end == start+count-1
 765           assert_different_registers(start, end);
 766 
 767           __ lea(end,  Address(start, count, Address::times_ptr, -wordSize));
 768           __ shrptr(start, CardTableModRefBS::card_shift);
 769           __ shrptr(end,   CardTableModRefBS::card_shift);
 770           __ subptr(end, start); // end --> count
 771         __ BIND(L_loop);
 772           intptr_t disp = (intptr_t) ct->byte_map_base;
 773           Address cardtable(start, count, Address::times_1, disp);
 774           __ movb(cardtable, 0);
 775           __ decrement(count);
 776           __ jcc(Assembler::greaterEqual, L_loop);
 777         }
 778         break;
 779       case BarrierSet::ModRef:
 780         break;
 781       default      :
 782         ShouldNotReachHere();
 783 
 784     }
 785   }
 786 
 787 
 788   // Copy 64 bytes chunks
 789   //
 790   // Inputs:
 791   //   from        - source array address
 792   //   to_from     - destination array address - from
 793   //   qword_count - 8-bytes element count, negative
 794   //
 795   void xmm_copy_forward(Register from, Register to_from, Register qword_count) {
 796     assert( UseSSE >= 2, "supported cpu only" );
 797     Label L_copy_64_bytes_loop, L_copy_64_bytes, L_copy_8_bytes, L_exit;
 798     // Copy 64-byte chunks
 799     __ jmpb(L_copy_64_bytes);
 800     __ align(OptoLoopAlignment);
 801   __ BIND(L_copy_64_bytes_loop);
 802 
 803     if (UseUnalignedLoadStores) {
 804       if (UseAVX > 2) {
 805         __ evmovdqu(xmm0, Address(from, 0), Assembler::AVX_512bit);
 806         __ evmovdqu(Address(from, to_from, Address::times_1, 0), xmm0, Assembler::AVX_512bit);
 807       } else if (UseAVX == 2) {
 808         __ vmovdqu(xmm0, Address(from,  0));
 809         __ vmovdqu(Address(from, to_from, Address::times_1,  0), xmm0);
 810         __ vmovdqu(xmm1, Address(from, 32));
 811         __ vmovdqu(Address(from, to_from, Address::times_1, 32), xmm1);
 812       } else {
 813         __ movdqu(xmm0, Address(from, 0));
 814         __ movdqu(Address(from, to_from, Address::times_1, 0), xmm0);
 815         __ movdqu(xmm1, Address(from, 16));
 816         __ movdqu(Address(from, to_from, Address::times_1, 16), xmm1);
 817         __ movdqu(xmm2, Address(from, 32));
 818         __ movdqu(Address(from, to_from, Address::times_1, 32), xmm2);
 819         __ movdqu(xmm3, Address(from, 48));
 820         __ movdqu(Address(from, to_from, Address::times_1, 48), xmm3);
 821       }
 822     } else {
 823       __ movq(xmm0, Address(from, 0));
 824       __ movq(Address(from, to_from, Address::times_1, 0), xmm0);
 825       __ movq(xmm1, Address(from, 8));
 826       __ movq(Address(from, to_from, Address::times_1, 8), xmm1);
 827       __ movq(xmm2, Address(from, 16));
 828       __ movq(Address(from, to_from, Address::times_1, 16), xmm2);
 829       __ movq(xmm3, Address(from, 24));
 830       __ movq(Address(from, to_from, Address::times_1, 24), xmm3);
 831       __ movq(xmm4, Address(from, 32));
 832       __ movq(Address(from, to_from, Address::times_1, 32), xmm4);
 833       __ movq(xmm5, Address(from, 40));
 834       __ movq(Address(from, to_from, Address::times_1, 40), xmm5);
 835       __ movq(xmm6, Address(from, 48));
 836       __ movq(Address(from, to_from, Address::times_1, 48), xmm6);
 837       __ movq(xmm7, Address(from, 56));
 838       __ movq(Address(from, to_from, Address::times_1, 56), xmm7);
 839     }
 840 
 841     __ addl(from, 64);
 842   __ BIND(L_copy_64_bytes);
 843     __ subl(qword_count, 8);
 844     __ jcc(Assembler::greaterEqual, L_copy_64_bytes_loop);
 845 
 846     if (UseUnalignedLoadStores && (UseAVX == 2)) {
 847       // clean upper bits of YMM registers
 848       __ vzeroupper();
 849     }
 850     __ addl(qword_count, 8);
 851     __ jccb(Assembler::zero, L_exit);
 852     //
 853     // length is too short, just copy qwords
 854     //
 855   __ BIND(L_copy_8_bytes);
 856     __ movq(xmm0, Address(from, 0));
 857     __ movq(Address(from, to_from, Address::times_1), xmm0);
 858     __ addl(from, 8);
 859     __ decrement(qword_count);
 860     __ jcc(Assembler::greater, L_copy_8_bytes);
 861   __ BIND(L_exit);
 862   }
 863 
 864   // Copy 64 bytes chunks
 865   //
 866   // Inputs:
 867   //   from        - source array address
 868   //   to_from     - destination array address - from
 869   //   qword_count - 8-bytes element count, negative
 870   //
 871   void mmx_copy_forward(Register from, Register to_from, Register qword_count) {
 872     assert( VM_Version::supports_mmx(), "supported cpu only" );
 873     Label L_copy_64_bytes_loop, L_copy_64_bytes, L_copy_8_bytes, L_exit;
 874     // Copy 64-byte chunks
 875     __ jmpb(L_copy_64_bytes);
 876     __ align(OptoLoopAlignment);
 877   __ BIND(L_copy_64_bytes_loop);
 878     __ movq(mmx0, Address(from, 0));
 879     __ movq(mmx1, Address(from, 8));
 880     __ movq(mmx2, Address(from, 16));
 881     __ movq(Address(from, to_from, Address::times_1, 0), mmx0);
 882     __ movq(mmx3, Address(from, 24));
 883     __ movq(Address(from, to_from, Address::times_1, 8), mmx1);
 884     __ movq(mmx4, Address(from, 32));
 885     __ movq(Address(from, to_from, Address::times_1, 16), mmx2);
 886     __ movq(mmx5, Address(from, 40));
 887     __ movq(Address(from, to_from, Address::times_1, 24), mmx3);
 888     __ movq(mmx6, Address(from, 48));
 889     __ movq(Address(from, to_from, Address::times_1, 32), mmx4);
 890     __ movq(mmx7, Address(from, 56));
 891     __ movq(Address(from, to_from, Address::times_1, 40), mmx5);
 892     __ movq(Address(from, to_from, Address::times_1, 48), mmx6);
 893     __ movq(Address(from, to_from, Address::times_1, 56), mmx7);
 894     __ addptr(from, 64);
 895   __ BIND(L_copy_64_bytes);
 896     __ subl(qword_count, 8);
 897     __ jcc(Assembler::greaterEqual, L_copy_64_bytes_loop);
 898     __ addl(qword_count, 8);
 899     __ jccb(Assembler::zero, L_exit);
 900     //
 901     // length is too short, just copy qwords
 902     //
 903   __ BIND(L_copy_8_bytes);
 904     __ movq(mmx0, Address(from, 0));
 905     __ movq(Address(from, to_from, Address::times_1), mmx0);
 906     __ addptr(from, 8);
 907     __ decrement(qword_count);
 908     __ jcc(Assembler::greater, L_copy_8_bytes);
 909   __ BIND(L_exit);
 910     __ emms();
 911   }
 912 
 913   address generate_disjoint_copy(BasicType t, bool aligned,
 914                                  Address::ScaleFactor sf,
 915                                  address* entry, const char *name,
 916                                  bool dest_uninitialized = false) {
 917     __ align(CodeEntryAlignment);
 918     StubCodeMark mark(this, "StubRoutines", name);
 919     address start = __ pc();
 920 
 921     Label L_0_count, L_exit, L_skip_align1, L_skip_align2, L_copy_byte;
 922     Label L_copy_2_bytes, L_copy_4_bytes, L_copy_64_bytes;
 923 
 924     int shift = Address::times_ptr - sf;
 925 
 926     const Register from     = rsi;  // source array address
 927     const Register to       = rdi;  // destination array address
 928     const Register count    = rcx;  // elements count
 929     const Register to_from  = to;   // (to - from)
 930     const Register saved_to = rdx;  // saved destination array address
 931 
 932     __ enter(); // required for proper stackwalking of RuntimeStub frame
 933     __ push(rsi);
 934     __ push(rdi);
 935     __ movptr(from , Address(rsp, 12+ 4));
 936     __ movptr(to   , Address(rsp, 12+ 8));
 937     __ movl(count, Address(rsp, 12+ 12));
 938 
 939     if (entry != NULL) {
 940       *entry = __ pc(); // Entry point from conjoint arraycopy stub.
 941       BLOCK_COMMENT("Entry:");
 942     }
 943 
 944     if (t == T_OBJECT) {
 945       __ testl(count, count);
 946       __ jcc(Assembler::zero, L_0_count);
 947       gen_write_ref_array_pre_barrier(to, count, dest_uninitialized);
 948       __ mov(saved_to, to);          // save 'to'
 949     }
 950 
 951     __ subptr(to, from); // to --> to_from
 952     __ cmpl(count, 2<<shift); // Short arrays (< 8 bytes) copy by element
 953     __ jcc(Assembler::below, L_copy_4_bytes); // use unsigned cmp
 954     if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
 955       // align source address at 4 bytes address boundary
 956       if (t == T_BYTE) {
 957         // One byte misalignment happens only for byte arrays
 958         __ testl(from, 1);
 959         __ jccb(Assembler::zero, L_skip_align1);
 960         __ movb(rax, Address(from, 0));
 961         __ movb(Address(from, to_from, Address::times_1, 0), rax);
 962         __ increment(from);
 963         __ decrement(count);
 964       __ BIND(L_skip_align1);
 965       }
 966       // Two bytes misalignment happens only for byte and short (char) arrays
 967       __ testl(from, 2);
 968       __ jccb(Assembler::zero, L_skip_align2);
 969       __ movw(rax, Address(from, 0));
 970       __ movw(Address(from, to_from, Address::times_1, 0), rax);
 971       __ addptr(from, 2);
 972       __ subl(count, 1<<(shift-1));
 973     __ BIND(L_skip_align2);
 974     }
 975     if (!VM_Version::supports_mmx()) {
 976       __ mov(rax, count);      // save 'count'
 977       __ shrl(count, shift); // bytes count
 978       __ addptr(to_from, from);// restore 'to'
 979       __ rep_mov();
 980       __ subptr(to_from, from);// restore 'to_from'
 981       __ mov(count, rax);      // restore 'count'
 982       __ jmpb(L_copy_2_bytes); // all dwords were copied
 983     } else {
 984       if (!UseUnalignedLoadStores) {
 985         // align to 8 bytes, we know we are 4 byte aligned to start
 986         __ testptr(from, 4);
 987         __ jccb(Assembler::zero, L_copy_64_bytes);
 988         __ movl(rax, Address(from, 0));
 989         __ movl(Address(from, to_from, Address::times_1, 0), rax);
 990         __ addptr(from, 4);
 991         __ subl(count, 1<<shift);
 992       }
 993     __ BIND(L_copy_64_bytes);
 994       __ mov(rax, count);
 995       __ shrl(rax, shift+1);  // 8 bytes chunk count
 996       //
 997       // Copy 8-byte chunks through MMX registers, 8 per iteration of the loop
 998       //
 999       if (UseXMMForArrayCopy) {
1000         xmm_copy_forward(from, to_from, rax);
1001       } else {
1002         mmx_copy_forward(from, to_from, rax);
1003       }
1004     }
1005     // copy tailing dword
1006   __ BIND(L_copy_4_bytes);
1007     __ testl(count, 1<<shift);
1008     __ jccb(Assembler::zero, L_copy_2_bytes);
1009     __ movl(rax, Address(from, 0));
1010     __ movl(Address(from, to_from, Address::times_1, 0), rax);
1011     if (t == T_BYTE || t == T_SHORT) {
1012       __ addptr(from, 4);
1013     __ BIND(L_copy_2_bytes);
1014       // copy tailing word
1015       __ testl(count, 1<<(shift-1));
1016       __ jccb(Assembler::zero, L_copy_byte);
1017       __ movw(rax, Address(from, 0));
1018       __ movw(Address(from, to_from, Address::times_1, 0), rax);
1019       if (t == T_BYTE) {
1020         __ addptr(from, 2);
1021       __ BIND(L_copy_byte);
1022         // copy tailing byte
1023         __ testl(count, 1);
1024         __ jccb(Assembler::zero, L_exit);
1025         __ movb(rax, Address(from, 0));
1026         __ movb(Address(from, to_from, Address::times_1, 0), rax);
1027       __ BIND(L_exit);
1028       } else {
1029       __ BIND(L_copy_byte);
1030       }
1031     } else {
1032     __ BIND(L_copy_2_bytes);
1033     }
1034 
1035     if (t == T_OBJECT) {
1036       __ movl(count, Address(rsp, 12+12)); // reread 'count'
1037       __ mov(to, saved_to); // restore 'to'
1038       gen_write_ref_array_post_barrier(to, count);
1039     __ BIND(L_0_count);
1040     }
1041     inc_copy_counter_np(t);
1042     __ pop(rdi);
1043     __ pop(rsi);
1044     __ leave(); // required for proper stackwalking of RuntimeStub frame
1045     __ xorptr(rax, rax); // return 0
1046     __ ret(0);
1047     return start;
1048   }
1049 
1050 
1051   address generate_fill(BasicType t, bool aligned, const char *name) {
1052     __ align(CodeEntryAlignment);
1053     StubCodeMark mark(this, "StubRoutines", name);
1054     address start = __ pc();
1055 
1056     BLOCK_COMMENT("Entry:");
1057 
1058     const Register to       = rdi;  // source array address
1059     const Register value    = rdx;  // value
1060     const Register count    = rsi;  // elements count
1061 
1062     __ enter(); // required for proper stackwalking of RuntimeStub frame
1063     __ push(rsi);
1064     __ push(rdi);
1065     __ movptr(to   , Address(rsp, 12+ 4));
1066     __ movl(value, Address(rsp, 12+ 8));
1067     __ movl(count, Address(rsp, 12+ 12));
1068 
1069     __ generate_fill(t, aligned, to, value, count, rax, xmm0);
1070 
1071     __ pop(rdi);
1072     __ pop(rsi);
1073     __ leave(); // required for proper stackwalking of RuntimeStub frame
1074     __ ret(0);
1075     return start;
1076   }
1077 
1078   address generate_conjoint_copy(BasicType t, bool aligned,
1079                                  Address::ScaleFactor sf,
1080                                  address nooverlap_target,
1081                                  address* entry, const char *name,
1082                                  bool dest_uninitialized = false) {
1083     __ align(CodeEntryAlignment);
1084     StubCodeMark mark(this, "StubRoutines", name);
1085     address start = __ pc();
1086 
1087     Label L_0_count, L_exit, L_skip_align1, L_skip_align2, L_copy_byte;
1088     Label L_copy_2_bytes, L_copy_4_bytes, L_copy_8_bytes, L_copy_8_bytes_loop;
1089 
1090     int shift = Address::times_ptr - sf;
1091 
1092     const Register src   = rax;  // source array address
1093     const Register dst   = rdx;  // destination array address
1094     const Register from  = rsi;  // source array address
1095     const Register to    = rdi;  // destination array address
1096     const Register count = rcx;  // elements count
1097     const Register end   = rax;  // array end address
1098 
1099     __ enter(); // required for proper stackwalking of RuntimeStub frame
1100     __ push(rsi);
1101     __ push(rdi);
1102     __ movptr(src  , Address(rsp, 12+ 4));   // from
1103     __ movptr(dst  , Address(rsp, 12+ 8));   // to
1104     __ movl2ptr(count, Address(rsp, 12+12)); // count
1105 
1106     if (entry != NULL) {
1107       *entry = __ pc(); // Entry point from generic arraycopy stub.
1108       BLOCK_COMMENT("Entry:");
1109     }
1110 
1111     // nooverlap_target expects arguments in rsi and rdi.
1112     __ mov(from, src);
1113     __ mov(to  , dst);
1114 
1115     // arrays overlap test: dispatch to disjoint stub if necessary.
1116     RuntimeAddress nooverlap(nooverlap_target);
1117     __ cmpptr(dst, src);
1118     __ lea(end, Address(src, count, sf, 0)); // src + count * elem_size
1119     __ jump_cc(Assembler::belowEqual, nooverlap);
1120     __ cmpptr(dst, end);
1121     __ jump_cc(Assembler::aboveEqual, nooverlap);
1122 
1123     if (t == T_OBJECT) {
1124       __ testl(count, count);
1125       __ jcc(Assembler::zero, L_0_count);
1126       gen_write_ref_array_pre_barrier(dst, count, dest_uninitialized);
1127     }
1128 
1129     // copy from high to low
1130     __ cmpl(count, 2<<shift); // Short arrays (< 8 bytes) copy by element
1131     __ jcc(Assembler::below, L_copy_4_bytes); // use unsigned cmp
1132     if (t == T_BYTE || t == T_SHORT) {
1133       // Align the end of destination array at 4 bytes address boundary
1134       __ lea(end, Address(dst, count, sf, 0));
1135       if (t == T_BYTE) {
1136         // One byte misalignment happens only for byte arrays
1137         __ testl(end, 1);
1138         __ jccb(Assembler::zero, L_skip_align1);
1139         __ decrement(count);
1140         __ movb(rdx, Address(from, count, sf, 0));
1141         __ movb(Address(to, count, sf, 0), rdx);
1142       __ BIND(L_skip_align1);
1143       }
1144       // Two bytes misalignment happens only for byte and short (char) arrays
1145       __ testl(end, 2);
1146       __ jccb(Assembler::zero, L_skip_align2);
1147       __ subptr(count, 1<<(shift-1));
1148       __ movw(rdx, Address(from, count, sf, 0));
1149       __ movw(Address(to, count, sf, 0), rdx);
1150     __ BIND(L_skip_align2);
1151       __ cmpl(count, 2<<shift); // Short arrays (< 8 bytes) copy by element
1152       __ jcc(Assembler::below, L_copy_4_bytes);
1153     }
1154 
1155     if (!VM_Version::supports_mmx()) {
1156       __ std();
1157       __ mov(rax, count); // Save 'count'
1158       __ mov(rdx, to);    // Save 'to'
1159       __ lea(rsi, Address(from, count, sf, -4));
1160       __ lea(rdi, Address(to  , count, sf, -4));
1161       __ shrptr(count, shift); // bytes count
1162       __ rep_mov();
1163       __ cld();
1164       __ mov(count, rax); // restore 'count'
1165       __ andl(count, (1<<shift)-1);      // mask the number of rest elements
1166       __ movptr(from, Address(rsp, 12+4)); // reread 'from'
1167       __ mov(to, rdx);   // restore 'to'
1168       __ jmpb(L_copy_2_bytes); // all dword were copied
1169    } else {
1170       // Align to 8 bytes the end of array. It is aligned to 4 bytes already.
1171       __ testptr(end, 4);
1172       __ jccb(Assembler::zero, L_copy_8_bytes);
1173       __ subl(count, 1<<shift);
1174       __ movl(rdx, Address(from, count, sf, 0));
1175       __ movl(Address(to, count, sf, 0), rdx);
1176       __ jmpb(L_copy_8_bytes);
1177 
1178       __ align(OptoLoopAlignment);
1179       // Move 8 bytes
1180     __ BIND(L_copy_8_bytes_loop);
1181       if (UseXMMForArrayCopy) {
1182         __ movq(xmm0, Address(from, count, sf, 0));
1183         __ movq(Address(to, count, sf, 0), xmm0);
1184       } else {
1185         __ movq(mmx0, Address(from, count, sf, 0));
1186         __ movq(Address(to, count, sf, 0), mmx0);
1187       }
1188     __ BIND(L_copy_8_bytes);
1189       __ subl(count, 2<<shift);
1190       __ jcc(Assembler::greaterEqual, L_copy_8_bytes_loop);
1191       __ addl(count, 2<<shift);
1192       if (!UseXMMForArrayCopy) {
1193         __ emms();
1194       }
1195     }
1196   __ BIND(L_copy_4_bytes);
1197     // copy prefix qword
1198     __ testl(count, 1<<shift);
1199     __ jccb(Assembler::zero, L_copy_2_bytes);
1200     __ movl(rdx, Address(from, count, sf, -4));
1201     __ movl(Address(to, count, sf, -4), rdx);
1202 
1203     if (t == T_BYTE || t == T_SHORT) {
1204         __ subl(count, (1<<shift));
1205       __ BIND(L_copy_2_bytes);
1206         // copy prefix dword
1207         __ testl(count, 1<<(shift-1));
1208         __ jccb(Assembler::zero, L_copy_byte);
1209         __ movw(rdx, Address(from, count, sf, -2));
1210         __ movw(Address(to, count, sf, -2), rdx);
1211         if (t == T_BYTE) {
1212           __ subl(count, 1<<(shift-1));
1213         __ BIND(L_copy_byte);
1214           // copy prefix byte
1215           __ testl(count, 1);
1216           __ jccb(Assembler::zero, L_exit);
1217           __ movb(rdx, Address(from, 0));
1218           __ movb(Address(to, 0), rdx);
1219         __ BIND(L_exit);
1220         } else {
1221         __ BIND(L_copy_byte);
1222         }
1223     } else {
1224     __ BIND(L_copy_2_bytes);
1225     }
1226     if (t == T_OBJECT) {
1227       __ movl2ptr(count, Address(rsp, 12+12)); // reread count
1228       gen_write_ref_array_post_barrier(to, count);
1229     __ BIND(L_0_count);
1230     }
1231     inc_copy_counter_np(t);
1232     __ pop(rdi);
1233     __ pop(rsi);
1234     __ leave(); // required for proper stackwalking of RuntimeStub frame
1235     __ xorptr(rax, rax); // return 0
1236     __ ret(0);
1237     return start;
1238   }
1239 
1240 
1241   address generate_disjoint_long_copy(address* entry, const char *name) {
1242     __ align(CodeEntryAlignment);
1243     StubCodeMark mark(this, "StubRoutines", name);
1244     address start = __ pc();
1245 
1246     Label L_copy_8_bytes, L_copy_8_bytes_loop;
1247     const Register from       = rax;  // source array address
1248     const Register to         = rdx;  // destination array address
1249     const Register count      = rcx;  // elements count
1250     const Register to_from    = rdx;  // (to - from)
1251 
1252     __ enter(); // required for proper stackwalking of RuntimeStub frame
1253     __ movptr(from , Address(rsp, 8+0));       // from
1254     __ movptr(to   , Address(rsp, 8+4));       // to
1255     __ movl2ptr(count, Address(rsp, 8+8));     // count
1256 
1257     *entry = __ pc(); // Entry point from conjoint arraycopy stub.
1258     BLOCK_COMMENT("Entry:");
1259 
1260     __ subptr(to, from); // to --> to_from
1261     if (VM_Version::supports_mmx()) {
1262       if (UseXMMForArrayCopy) {
1263         xmm_copy_forward(from, to_from, count);
1264       } else {
1265         mmx_copy_forward(from, to_from, count);
1266       }
1267     } else {
1268       __ jmpb(L_copy_8_bytes);
1269       __ align(OptoLoopAlignment);
1270     __ BIND(L_copy_8_bytes_loop);
1271       __ fild_d(Address(from, 0));
1272       __ fistp_d(Address(from, to_from, Address::times_1));
1273       __ addptr(from, 8);
1274     __ BIND(L_copy_8_bytes);
1275       __ decrement(count);
1276       __ jcc(Assembler::greaterEqual, L_copy_8_bytes_loop);
1277     }
1278     inc_copy_counter_np(T_LONG);
1279     __ leave(); // required for proper stackwalking of RuntimeStub frame
1280     __ xorptr(rax, rax); // return 0
1281     __ ret(0);
1282     return start;
1283   }
1284 
1285   address generate_conjoint_long_copy(address nooverlap_target,
1286                                       address* entry, const char *name) {
1287     __ align(CodeEntryAlignment);
1288     StubCodeMark mark(this, "StubRoutines", name);
1289     address start = __ pc();
1290 
1291     Label L_copy_8_bytes, L_copy_8_bytes_loop;
1292     const Register from       = rax;  // source array address
1293     const Register to         = rdx;  // destination array address
1294     const Register count      = rcx;  // elements count
1295     const Register end_from   = rax;  // source array end address
1296 
1297     __ enter(); // required for proper stackwalking of RuntimeStub frame
1298     __ movptr(from , Address(rsp, 8+0));       // from
1299     __ movptr(to   , Address(rsp, 8+4));       // to
1300     __ movl2ptr(count, Address(rsp, 8+8));     // count
1301 
1302     *entry = __ pc(); // Entry point from generic arraycopy stub.
1303     BLOCK_COMMENT("Entry:");
1304 
1305     // arrays overlap test
1306     __ cmpptr(to, from);
1307     RuntimeAddress nooverlap(nooverlap_target);
1308     __ jump_cc(Assembler::belowEqual, nooverlap);
1309     __ lea(end_from, Address(from, count, Address::times_8, 0));
1310     __ cmpptr(to, end_from);
1311     __ movptr(from, Address(rsp, 8));  // from
1312     __ jump_cc(Assembler::aboveEqual, nooverlap);
1313 
1314     __ jmpb(L_copy_8_bytes);
1315 
1316     __ align(OptoLoopAlignment);
1317   __ BIND(L_copy_8_bytes_loop);
1318     if (VM_Version::supports_mmx()) {
1319       if (UseXMMForArrayCopy) {
1320         __ movq(xmm0, Address(from, count, Address::times_8));
1321         __ movq(Address(to, count, Address::times_8), xmm0);
1322       } else {
1323         __ movq(mmx0, Address(from, count, Address::times_8));
1324         __ movq(Address(to, count, Address::times_8), mmx0);
1325       }
1326     } else {
1327       __ fild_d(Address(from, count, Address::times_8));
1328       __ fistp_d(Address(to, count, Address::times_8));
1329     }
1330   __ BIND(L_copy_8_bytes);
1331     __ decrement(count);
1332     __ jcc(Assembler::greaterEqual, L_copy_8_bytes_loop);
1333 
1334     if (VM_Version::supports_mmx() && !UseXMMForArrayCopy) {
1335       __ emms();
1336     }
1337     inc_copy_counter_np(T_LONG);
1338     __ leave(); // required for proper stackwalking of RuntimeStub frame
1339     __ xorptr(rax, rax); // return 0
1340     __ ret(0);
1341     return start;
1342   }
1343 
1344 
1345   // Helper for generating a dynamic type check.
1346   // The sub_klass must be one of {rbx, rdx, rsi}.
1347   // The temp is killed.
1348   void generate_type_check(Register sub_klass,
1349                            Address& super_check_offset_addr,
1350                            Address& super_klass_addr,
1351                            Register temp,
1352                            Label* L_success, Label* L_failure) {
1353     BLOCK_COMMENT("type_check:");
1354 
1355     Label L_fallthrough;
1356 #define LOCAL_JCC(assembler_con, label_ptr)                             \
1357     if (label_ptr != NULL)  __ jcc(assembler_con, *(label_ptr));        \
1358     else                    __ jcc(assembler_con, L_fallthrough) /*omit semi*/
1359 
1360     // The following is a strange variation of the fast path which requires
1361     // one less register, because needed values are on the argument stack.
1362     // __ check_klass_subtype_fast_path(sub_klass, *super_klass*, temp,
1363     //                                  L_success, L_failure, NULL);
1364     assert_different_registers(sub_klass, temp);
1365 
1366     int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
1367 
1368     // if the pointers are equal, we are done (e.g., String[] elements)
1369     __ cmpptr(sub_klass, super_klass_addr);
1370     LOCAL_JCC(Assembler::equal, L_success);
1371 
1372     // check the supertype display:
1373     __ movl2ptr(temp, super_check_offset_addr);
1374     Address super_check_addr(sub_klass, temp, Address::times_1, 0);
1375     __ movptr(temp, super_check_addr); // load displayed supertype
1376     __ cmpptr(temp, super_klass_addr); // test the super type
1377     LOCAL_JCC(Assembler::equal, L_success);
1378 
1379     // if it was a primary super, we can just fail immediately
1380     __ cmpl(super_check_offset_addr, sc_offset);
1381     LOCAL_JCC(Assembler::notEqual, L_failure);
1382 
1383     // The repne_scan instruction uses fixed registers, which will get spilled.
1384     // We happen to know this works best when super_klass is in rax.
1385     Register super_klass = temp;
1386     __ movptr(super_klass, super_klass_addr);
1387     __ check_klass_subtype_slow_path(sub_klass, super_klass, noreg, noreg,
1388                                      L_success, L_failure);
1389 
1390     __ bind(L_fallthrough);
1391 
1392     if (L_success == NULL) { BLOCK_COMMENT("L_success:"); }
1393     if (L_failure == NULL) { BLOCK_COMMENT("L_failure:"); }
1394 
1395 #undef LOCAL_JCC
1396   }
1397 
1398   //
1399   //  Generate checkcasting array copy stub
1400   //
1401   //  Input:
1402   //    4(rsp)   - source array address
1403   //    8(rsp)   - destination array address
1404   //   12(rsp)   - element count, can be zero
1405   //   16(rsp)   - size_t ckoff (super_check_offset)
1406   //   20(rsp)   - oop ckval (super_klass)
1407   //
1408   //  Output:
1409   //    rax, ==  0  -  success
1410   //    rax, == -1^K - failure, where K is partial transfer count
1411   //
1412   address generate_checkcast_copy(const char *name, address* entry, bool dest_uninitialized = false) {
1413     __ align(CodeEntryAlignment);
1414     StubCodeMark mark(this, "StubRoutines", name);
1415     address start = __ pc();
1416 
1417     Label L_load_element, L_store_element, L_do_card_marks, L_done;
1418 
1419     // register use:
1420     //  rax, rdx, rcx -- loop control (end_from, end_to, count)
1421     //  rdi, rsi      -- element access (oop, klass)
1422     //  rbx,           -- temp
1423     const Register from       = rax;    // source array address
1424     const Register to         = rdx;    // destination array address
1425     const Register length     = rcx;    // elements count
1426     const Register elem       = rdi;    // each oop copied
1427     const Register elem_klass = rsi;    // each elem._klass (sub_klass)
1428     const Register temp       = rbx;    // lone remaining temp
1429 
1430     __ enter(); // required for proper stackwalking of RuntimeStub frame
1431 
1432     __ push(rsi);
1433     __ push(rdi);
1434     __ push(rbx);
1435 
1436     Address   from_arg(rsp, 16+ 4);     // from
1437     Address     to_arg(rsp, 16+ 8);     // to
1438     Address length_arg(rsp, 16+12);     // elements count
1439     Address  ckoff_arg(rsp, 16+16);     // super_check_offset
1440     Address  ckval_arg(rsp, 16+20);     // super_klass
1441 
1442     // Load up:
1443     __ movptr(from,     from_arg);
1444     __ movptr(to,         to_arg);
1445     __ movl2ptr(length, length_arg);
1446 
1447     if (entry != NULL) {
1448       *entry = __ pc(); // Entry point from generic arraycopy stub.
1449       BLOCK_COMMENT("Entry:");
1450     }
1451 
1452     //---------------------------------------------------------------
1453     // Assembler stub will be used for this call to arraycopy
1454     // if the two arrays are subtypes of Object[] but the
1455     // destination array type is not equal to or a supertype
1456     // of the source type.  Each element must be separately
1457     // checked.
1458 
1459     // Loop-invariant addresses.  They are exclusive end pointers.
1460     Address end_from_addr(from, length, Address::times_ptr, 0);
1461     Address   end_to_addr(to,   length, Address::times_ptr, 0);
1462 
1463     Register end_from = from;           // re-use
1464     Register end_to   = to;             // re-use
1465     Register count    = length;         // re-use
1466 
1467     // Loop-variant addresses.  They assume post-incremented count < 0.
1468     Address from_element_addr(end_from, count, Address::times_ptr, 0);
1469     Address   to_element_addr(end_to,   count, Address::times_ptr, 0);
1470     Address elem_klass_addr(elem, oopDesc::klass_offset_in_bytes());
1471 
1472     // Copy from low to high addresses, indexed from the end of each array.
1473     gen_write_ref_array_pre_barrier(to, count, dest_uninitialized);
1474     __ lea(end_from, end_from_addr);
1475     __ lea(end_to,   end_to_addr);
1476     assert(length == count, "");        // else fix next line:
1477     __ negptr(count);                   // negate and test the length
1478     __ jccb(Assembler::notZero, L_load_element);
1479 
1480     // Empty array:  Nothing to do.
1481     __ xorptr(rax, rax);                  // return 0 on (trivial) success
1482     __ jmp(L_done);
1483 
1484     // ======== begin loop ========
1485     // (Loop is rotated; its entry is L_load_element.)
1486     // Loop control:
1487     //   for (count = -count; count != 0; count++)
1488     // Base pointers src, dst are biased by 8*count,to last element.
1489     __ align(OptoLoopAlignment);
1490 
1491     __ BIND(L_store_element);
1492     __ movptr(to_element_addr, elem);     // store the oop
1493     __ increment(count);                // increment the count toward zero
1494     __ jccb(Assembler::zero, L_do_card_marks);
1495 
1496     // ======== loop entry is here ========
1497     __ BIND(L_load_element);
1498     __ movptr(elem, from_element_addr);   // load the oop
1499     __ testptr(elem, elem);
1500     __ jccb(Assembler::zero, L_store_element);
1501 
1502     // (Could do a trick here:  Remember last successful non-null
1503     // element stored and make a quick oop equality check on it.)
1504 
1505     __ movptr(elem_klass, elem_klass_addr); // query the object klass
1506     generate_type_check(elem_klass, ckoff_arg, ckval_arg, temp,
1507                         &L_store_element, NULL);
1508     // (On fall-through, we have failed the element type check.)
1509     // ======== end loop ========
1510 
1511     // It was a real error; we must depend on the caller to finish the job.
1512     // Register "count" = -1 * number of *remaining* oops, length_arg = *total* oops.
1513     // Emit GC store barriers for the oops we have copied (length_arg + count),
1514     // and report their number to the caller.
1515     assert_different_registers(to, count, rax);
1516     Label L_post_barrier;
1517     __ addl(count, length_arg);         // transfers = (length - remaining)
1518     __ movl2ptr(rax, count);            // save the value
1519     __ notptr(rax);                     // report (-1^K) to caller (does not affect flags)
1520     __ jccb(Assembler::notZero, L_post_barrier);
1521     __ jmp(L_done); // K == 0, nothing was copied, skip post barrier
1522 
1523     // Come here on success only.
1524     __ BIND(L_do_card_marks);
1525     __ xorptr(rax, rax);                // return 0 on success
1526     __ movl2ptr(count, length_arg);
1527 
1528     __ BIND(L_post_barrier);
1529     __ movptr(to, to_arg);              // reload
1530     gen_write_ref_array_post_barrier(to, count);
1531 
1532     // Common exit point (success or failure).
1533     __ BIND(L_done);
1534     __ pop(rbx);
1535     __ pop(rdi);
1536     __ pop(rsi);
1537     inc_counter_np(SharedRuntime::_checkcast_array_copy_ctr);
1538     __ leave(); // required for proper stackwalking of RuntimeStub frame
1539     __ ret(0);
1540 
1541     return start;
1542   }
1543 
1544   //
1545   //  Generate 'unsafe' array copy stub
1546   //  Though just as safe as the other stubs, it takes an unscaled
1547   //  size_t argument instead of an element count.
1548   //
1549   //  Input:
1550   //    4(rsp)   - source array address
1551   //    8(rsp)   - destination array address
1552   //   12(rsp)   - byte count, can be zero
1553   //
1554   //  Output:
1555   //    rax, ==  0  -  success
1556   //    rax, == -1  -  need to call System.arraycopy
1557   //
1558   // Examines the alignment of the operands and dispatches
1559   // to a long, int, short, or byte copy loop.
1560   //
1561   address generate_unsafe_copy(const char *name,
1562                                address byte_copy_entry,
1563                                address short_copy_entry,
1564                                address int_copy_entry,
1565                                address long_copy_entry) {
1566 
1567     Label L_long_aligned, L_int_aligned, L_short_aligned;
1568 
1569     __ align(CodeEntryAlignment);
1570     StubCodeMark mark(this, "StubRoutines", name);
1571     address start = __ pc();
1572 
1573     const Register from       = rax;  // source array address
1574     const Register to         = rdx;  // destination array address
1575     const Register count      = rcx;  // elements count
1576 
1577     __ enter(); // required for proper stackwalking of RuntimeStub frame
1578     __ push(rsi);
1579     __ push(rdi);
1580     Address  from_arg(rsp, 12+ 4);      // from
1581     Address    to_arg(rsp, 12+ 8);      // to
1582     Address count_arg(rsp, 12+12);      // byte count
1583 
1584     // Load up:
1585     __ movptr(from ,  from_arg);
1586     __ movptr(to   ,    to_arg);
1587     __ movl2ptr(count, count_arg);
1588 
1589     // bump this on entry, not on exit:
1590     inc_counter_np(SharedRuntime::_unsafe_array_copy_ctr);
1591 
1592     const Register bits = rsi;
1593     __ mov(bits, from);
1594     __ orptr(bits, to);
1595     __ orptr(bits, count);
1596 
1597     __ testl(bits, BytesPerLong-1);
1598     __ jccb(Assembler::zero, L_long_aligned);
1599 
1600     __ testl(bits, BytesPerInt-1);
1601     __ jccb(Assembler::zero, L_int_aligned);
1602 
1603     __ testl(bits, BytesPerShort-1);
1604     __ jump_cc(Assembler::notZero, RuntimeAddress(byte_copy_entry));
1605 
1606     __ BIND(L_short_aligned);
1607     __ shrptr(count, LogBytesPerShort); // size => short_count
1608     __ movl(count_arg, count);          // update 'count'
1609     __ jump(RuntimeAddress(short_copy_entry));
1610 
1611     __ BIND(L_int_aligned);
1612     __ shrptr(count, LogBytesPerInt); // size => int_count
1613     __ movl(count_arg, count);          // update 'count'
1614     __ jump(RuntimeAddress(int_copy_entry));
1615 
1616     __ BIND(L_long_aligned);
1617     __ shrptr(count, LogBytesPerLong); // size => qword_count
1618     __ movl(count_arg, count);          // update 'count'
1619     __ pop(rdi); // Do pops here since jlong_arraycopy stub does not do it.
1620     __ pop(rsi);
1621     __ jump(RuntimeAddress(long_copy_entry));
1622 
1623     return start;
1624   }
1625 
1626 
1627   // Perform range checks on the proposed arraycopy.
1628   // Smashes src_pos and dst_pos.  (Uses them up for temps.)
1629   void arraycopy_range_checks(Register src,
1630                               Register src_pos,
1631                               Register dst,
1632                               Register dst_pos,
1633                               Address& length,
1634                               Label& L_failed) {
1635     BLOCK_COMMENT("arraycopy_range_checks:");
1636     const Register src_end = src_pos;   // source array end position
1637     const Register dst_end = dst_pos;   // destination array end position
1638     __ addl(src_end, length); // src_pos + length
1639     __ addl(dst_end, length); // dst_pos + length
1640 
1641     //  if (src_pos + length > arrayOop(src)->length() ) FAIL;
1642     __ cmpl(src_end, Address(src, arrayOopDesc::length_offset_in_bytes()));
1643     __ jcc(Assembler::above, L_failed);
1644 
1645     //  if (dst_pos + length > arrayOop(dst)->length() ) FAIL;
1646     __ cmpl(dst_end, Address(dst, arrayOopDesc::length_offset_in_bytes()));
1647     __ jcc(Assembler::above, L_failed);
1648 
1649     BLOCK_COMMENT("arraycopy_range_checks done");
1650   }
1651 
1652 
1653   //
1654   //  Generate generic array copy stubs
1655   //
1656   //  Input:
1657   //     4(rsp)    -  src oop
1658   //     8(rsp)    -  src_pos
1659   //    12(rsp)    -  dst oop
1660   //    16(rsp)    -  dst_pos
1661   //    20(rsp)    -  element count
1662   //
1663   //  Output:
1664   //    rax, ==  0  -  success
1665   //    rax, == -1^K - failure, where K is partial transfer count
1666   //
1667   address generate_generic_copy(const char *name,
1668                                 address entry_jbyte_arraycopy,
1669                                 address entry_jshort_arraycopy,
1670                                 address entry_jint_arraycopy,
1671                                 address entry_oop_arraycopy,
1672                                 address entry_jlong_arraycopy,
1673                                 address entry_checkcast_arraycopy) {
1674     Label L_failed, L_failed_0, L_objArray;
1675 
1676     { int modulus = CodeEntryAlignment;
1677       int target  = modulus - 5; // 5 = sizeof jmp(L_failed)
1678       int advance = target - (__ offset() % modulus);
1679       if (advance < 0)  advance += modulus;
1680       if (advance > 0)  __ nop(advance);
1681     }
1682     StubCodeMark mark(this, "StubRoutines", name);
1683 
1684     // Short-hop target to L_failed.  Makes for denser prologue code.
1685     __ BIND(L_failed_0);
1686     __ jmp(L_failed);
1687     assert(__ offset() % CodeEntryAlignment == 0, "no further alignment needed");
1688 
1689     __ align(CodeEntryAlignment);
1690     address start = __ pc();
1691 
1692     __ enter(); // required for proper stackwalking of RuntimeStub frame
1693     __ push(rsi);
1694     __ push(rdi);
1695 
1696     // bump this on entry, not on exit:
1697     inc_counter_np(SharedRuntime::_generic_array_copy_ctr);
1698 
1699     // Input values
1700     Address SRC     (rsp, 12+ 4);
1701     Address SRC_POS (rsp, 12+ 8);
1702     Address DST     (rsp, 12+12);
1703     Address DST_POS (rsp, 12+16);
1704     Address LENGTH  (rsp, 12+20);
1705 
1706     //-----------------------------------------------------------------------
1707     // Assembler stub will be used for this call to arraycopy
1708     // if the following conditions are met:
1709     //
1710     // (1) src and dst must not be null.
1711     // (2) src_pos must not be negative.
1712     // (3) dst_pos must not be negative.
1713     // (4) length  must not be negative.
1714     // (5) src klass and dst klass should be the same and not NULL.
1715     // (6) src and dst should be arrays.
1716     // (7) src_pos + length must not exceed length of src.
1717     // (8) dst_pos + length must not exceed length of dst.
1718     //
1719 
1720     const Register src     = rax;       // source array oop
1721     const Register src_pos = rsi;
1722     const Register dst     = rdx;       // destination array oop
1723     const Register dst_pos = rdi;
1724     const Register length  = rcx;       // transfer count
1725 
1726     //  if (src == NULL) return -1;
1727     __ movptr(src, SRC);      // src oop
1728     __ testptr(src, src);
1729     __ jccb(Assembler::zero, L_failed_0);
1730 
1731     //  if (src_pos < 0) return -1;
1732     __ movl2ptr(src_pos, SRC_POS);  // src_pos
1733     __ testl(src_pos, src_pos);
1734     __ jccb(Assembler::negative, L_failed_0);
1735 
1736     //  if (dst == NULL) return -1;
1737     __ movptr(dst, DST);      // dst oop
1738     __ testptr(dst, dst);
1739     __ jccb(Assembler::zero, L_failed_0);
1740 
1741     //  if (dst_pos < 0) return -1;
1742     __ movl2ptr(dst_pos, DST_POS);  // dst_pos
1743     __ testl(dst_pos, dst_pos);
1744     __ jccb(Assembler::negative, L_failed_0);
1745 
1746     //  if (length < 0) return -1;
1747     __ movl2ptr(length, LENGTH);   // length
1748     __ testl(length, length);
1749     __ jccb(Assembler::negative, L_failed_0);
1750 
1751     //  if (src->klass() == NULL) return -1;
1752     Address src_klass_addr(src, oopDesc::klass_offset_in_bytes());
1753     Address dst_klass_addr(dst, oopDesc::klass_offset_in_bytes());
1754     const Register rcx_src_klass = rcx;    // array klass
1755     __ movptr(rcx_src_klass, Address(src, oopDesc::klass_offset_in_bytes()));
1756 
1757 #ifdef ASSERT
1758     //  assert(src->klass() != NULL);
1759     BLOCK_COMMENT("assert klasses not null");
1760     { Label L1, L2;
1761       __ testptr(rcx_src_klass, rcx_src_klass);
1762       __ jccb(Assembler::notZero, L2);   // it is broken if klass is NULL
1763       __ bind(L1);
1764       __ stop("broken null klass");
1765       __ bind(L2);
1766       __ cmpptr(dst_klass_addr, (int32_t)NULL_WORD);
1767       __ jccb(Assembler::equal, L1);      // this would be broken also
1768       BLOCK_COMMENT("assert done");
1769     }
1770 #endif //ASSERT
1771 
1772     // Load layout helper (32-bits)
1773     //
1774     //  |array_tag|     | header_size | element_type |     |log2_element_size|
1775     // 32        30    24            16              8     2                 0
1776     //
1777     //   array_tag: typeArray = 0x3, objArray = 0x2, non-array = 0x0
1778     //
1779 
1780     int lh_offset = in_bytes(Klass::layout_helper_offset());
1781     Address src_klass_lh_addr(rcx_src_klass, lh_offset);
1782 
1783     // Handle objArrays completely differently...
1784     jint objArray_lh = Klass::array_layout_helper(T_OBJECT);
1785     __ cmpl(src_klass_lh_addr, objArray_lh);
1786     __ jcc(Assembler::equal, L_objArray);
1787 
1788     //  if (src->klass() != dst->klass()) return -1;
1789     __ cmpptr(rcx_src_klass, dst_klass_addr);
1790     __ jccb(Assembler::notEqual, L_failed_0);
1791 
1792     const Register rcx_lh = rcx;  // layout helper
1793     assert(rcx_lh == rcx_src_klass, "known alias");
1794     __ movl(rcx_lh, src_klass_lh_addr);
1795 
1796     //  if (!src->is_Array()) return -1;
1797     __ cmpl(rcx_lh, Klass::_lh_neutral_value);
1798     __ jcc(Assembler::greaterEqual, L_failed_0); // signed cmp
1799 
1800     // At this point, it is known to be a typeArray (array_tag 0x3).
1801 #ifdef ASSERT
1802     { Label L;
1803       __ cmpl(rcx_lh, (Klass::_lh_array_tag_type_value << Klass::_lh_array_tag_shift));
1804       __ jcc(Assembler::greaterEqual, L); // signed cmp
1805       __ stop("must be a primitive array");
1806       __ bind(L);
1807     }
1808 #endif
1809 
1810     assert_different_registers(src, src_pos, dst, dst_pos, rcx_lh);
1811     arraycopy_range_checks(src, src_pos, dst, dst_pos, LENGTH, L_failed);
1812 
1813     // TypeArrayKlass
1814     //
1815     // src_addr = (src + array_header_in_bytes()) + (src_pos << log2elemsize);
1816     // dst_addr = (dst + array_header_in_bytes()) + (dst_pos << log2elemsize);
1817     //
1818     const Register rsi_offset = rsi; // array offset
1819     const Register src_array  = src; // src array offset
1820     const Register dst_array  = dst; // dst array offset
1821     const Register rdi_elsize = rdi; // log2 element size
1822 
1823     __ mov(rsi_offset, rcx_lh);
1824     __ shrptr(rsi_offset, Klass::_lh_header_size_shift);
1825     __ andptr(rsi_offset, Klass::_lh_header_size_mask);   // array_offset
1826     __ addptr(src_array, rsi_offset);  // src array offset
1827     __ addptr(dst_array, rsi_offset);  // dst array offset
1828     __ andptr(rcx_lh, Klass::_lh_log2_element_size_mask); // log2 elsize
1829 
1830     // next registers should be set before the jump to corresponding stub
1831     const Register from       = src; // source array address
1832     const Register to         = dst; // destination array address
1833     const Register count      = rcx; // elements count
1834     // some of them should be duplicated on stack
1835 #define FROM   Address(rsp, 12+ 4)
1836 #define TO     Address(rsp, 12+ 8)   // Not used now
1837 #define COUNT  Address(rsp, 12+12)   // Only for oop arraycopy
1838 
1839     BLOCK_COMMENT("scale indexes to element size");
1840     __ movl2ptr(rsi, SRC_POS);  // src_pos
1841     __ shlptr(rsi);             // src_pos << rcx (log2 elsize)
1842     assert(src_array == from, "");
1843     __ addptr(from, rsi);       // from = src_array + SRC_POS << log2 elsize
1844     __ movl2ptr(rdi, DST_POS);  // dst_pos
1845     __ shlptr(rdi);             // dst_pos << rcx (log2 elsize)
1846     assert(dst_array == to, "");
1847     __ addptr(to,  rdi);        // to   = dst_array + DST_POS << log2 elsize
1848     __ movptr(FROM, from);      // src_addr
1849     __ mov(rdi_elsize, rcx_lh); // log2 elsize
1850     __ movl2ptr(count, LENGTH); // elements count
1851 
1852     BLOCK_COMMENT("choose copy loop based on element size");
1853     __ cmpl(rdi_elsize, 0);
1854 
1855     __ jump_cc(Assembler::equal, RuntimeAddress(entry_jbyte_arraycopy));
1856     __ cmpl(rdi_elsize, LogBytesPerShort);
1857     __ jump_cc(Assembler::equal, RuntimeAddress(entry_jshort_arraycopy));
1858     __ cmpl(rdi_elsize, LogBytesPerInt);
1859     __ jump_cc(Assembler::equal, RuntimeAddress(entry_jint_arraycopy));
1860 #ifdef ASSERT
1861     __ cmpl(rdi_elsize, LogBytesPerLong);
1862     __ jccb(Assembler::notEqual, L_failed);
1863 #endif
1864     __ pop(rdi); // Do pops here since jlong_arraycopy stub does not do it.
1865     __ pop(rsi);
1866     __ jump(RuntimeAddress(entry_jlong_arraycopy));
1867 
1868   __ BIND(L_failed);
1869     __ xorptr(rax, rax);
1870     __ notptr(rax); // return -1
1871     __ pop(rdi);
1872     __ pop(rsi);
1873     __ leave(); // required for proper stackwalking of RuntimeStub frame
1874     __ ret(0);
1875 
1876     // ObjArrayKlass
1877   __ BIND(L_objArray);
1878     // live at this point:  rcx_src_klass, src[_pos], dst[_pos]
1879 
1880     Label L_plain_copy, L_checkcast_copy;
1881     //  test array classes for subtyping
1882     __ cmpptr(rcx_src_klass, dst_klass_addr); // usual case is exact equality
1883     __ jccb(Assembler::notEqual, L_checkcast_copy);
1884 
1885     // Identically typed arrays can be copied without element-wise checks.
1886     assert_different_registers(src, src_pos, dst, dst_pos, rcx_src_klass);
1887     arraycopy_range_checks(src, src_pos, dst, dst_pos, LENGTH, L_failed);
1888 
1889   __ BIND(L_plain_copy);
1890     __ movl2ptr(count, LENGTH); // elements count
1891     __ movl2ptr(src_pos, SRC_POS);  // reload src_pos
1892     __ lea(from, Address(src, src_pos, Address::times_ptr,
1893                  arrayOopDesc::base_offset_in_bytes(T_OBJECT))); // src_addr
1894     __ movl2ptr(dst_pos, DST_POS);  // reload dst_pos
1895     __ lea(to,   Address(dst, dst_pos, Address::times_ptr,
1896                  arrayOopDesc::base_offset_in_bytes(T_OBJECT))); // dst_addr
1897     __ movptr(FROM,  from);   // src_addr
1898     __ movptr(TO,    to);     // dst_addr
1899     __ movl(COUNT, count);  // count
1900     __ jump(RuntimeAddress(entry_oop_arraycopy));
1901 
1902   __ BIND(L_checkcast_copy);
1903     // live at this point:  rcx_src_klass, dst[_pos], src[_pos]
1904     {
1905       // Handy offsets:
1906       int  ek_offset = in_bytes(ObjArrayKlass::element_klass_offset());
1907       int sco_offset = in_bytes(Klass::super_check_offset_offset());
1908 
1909       Register rsi_dst_klass = rsi;
1910       Register rdi_temp      = rdi;
1911       assert(rsi_dst_klass == src_pos, "expected alias w/ src_pos");
1912       assert(rdi_temp      == dst_pos, "expected alias w/ dst_pos");
1913       Address dst_klass_lh_addr(rsi_dst_klass, lh_offset);
1914 
1915       // Before looking at dst.length, make sure dst is also an objArray.
1916       __ movptr(rsi_dst_klass, dst_klass_addr);
1917       __ cmpl(dst_klass_lh_addr, objArray_lh);
1918       __ jccb(Assembler::notEqual, L_failed);
1919 
1920       // It is safe to examine both src.length and dst.length.
1921       __ movl2ptr(src_pos, SRC_POS);        // reload rsi
1922       arraycopy_range_checks(src, src_pos, dst, dst_pos, LENGTH, L_failed);
1923       // (Now src_pos and dst_pos are killed, but not src and dst.)
1924 
1925       // We'll need this temp (don't forget to pop it after the type check).
1926       __ push(rbx);
1927       Register rbx_src_klass = rbx;
1928 
1929       __ mov(rbx_src_klass, rcx_src_klass); // spill away from rcx
1930       __ movptr(rsi_dst_klass, dst_klass_addr);
1931       Address super_check_offset_addr(rsi_dst_klass, sco_offset);
1932       Label L_fail_array_check;
1933       generate_type_check(rbx_src_klass,
1934                           super_check_offset_addr, dst_klass_addr,
1935                           rdi_temp, NULL, &L_fail_array_check);
1936       // (On fall-through, we have passed the array type check.)
1937       __ pop(rbx);
1938       __ jmp(L_plain_copy);
1939 
1940       __ BIND(L_fail_array_check);
1941       // Reshuffle arguments so we can call checkcast_arraycopy:
1942 
1943       // match initial saves for checkcast_arraycopy
1944       // push(rsi);    // already done; see above
1945       // push(rdi);    // already done; see above
1946       // push(rbx);    // already done; see above
1947 
1948       // Marshal outgoing arguments now, freeing registers.
1949       Address   from_arg(rsp, 16+ 4);   // from
1950       Address     to_arg(rsp, 16+ 8);   // to
1951       Address length_arg(rsp, 16+12);   // elements count
1952       Address  ckoff_arg(rsp, 16+16);   // super_check_offset
1953       Address  ckval_arg(rsp, 16+20);   // super_klass
1954 
1955       Address SRC_POS_arg(rsp, 16+ 8);
1956       Address DST_POS_arg(rsp, 16+16);
1957       Address  LENGTH_arg(rsp, 16+20);
1958       // push rbx, changed the incoming offsets (why not just use rbp,??)
1959       // assert(SRC_POS_arg.disp() == SRC_POS.disp() + 4, "");
1960 
1961       __ movptr(rbx, Address(rsi_dst_klass, ek_offset));
1962       __ movl2ptr(length, LENGTH_arg);    // reload elements count
1963       __ movl2ptr(src_pos, SRC_POS_arg);  // reload src_pos
1964       __ movl2ptr(dst_pos, DST_POS_arg);  // reload dst_pos
1965 
1966       __ movptr(ckval_arg, rbx);          // destination element type
1967       __ movl(rbx, Address(rbx, sco_offset));
1968       __ movl(ckoff_arg, rbx);          // corresponding class check offset
1969 
1970       __ movl(length_arg, length);      // outgoing length argument
1971 
1972       __ lea(from, Address(src, src_pos, Address::times_ptr,
1973                             arrayOopDesc::base_offset_in_bytes(T_OBJECT)));
1974       __ movptr(from_arg, from);
1975 
1976       __ lea(to, Address(dst, dst_pos, Address::times_ptr,
1977                           arrayOopDesc::base_offset_in_bytes(T_OBJECT)));
1978       __ movptr(to_arg, to);
1979       __ jump(RuntimeAddress(entry_checkcast_arraycopy));
1980     }
1981 
1982     return start;
1983   }
1984 
1985   void generate_arraycopy_stubs() {
1986     address entry;
1987     address entry_jbyte_arraycopy;
1988     address entry_jshort_arraycopy;
1989     address entry_jint_arraycopy;
1990     address entry_oop_arraycopy;
1991     address entry_jlong_arraycopy;
1992     address entry_checkcast_arraycopy;
1993 
1994     StubRoutines::_arrayof_jbyte_disjoint_arraycopy =
1995         generate_disjoint_copy(T_BYTE,  true, Address::times_1, &entry,
1996                                "arrayof_jbyte_disjoint_arraycopy");
1997     StubRoutines::_arrayof_jbyte_arraycopy =
1998         generate_conjoint_copy(T_BYTE,  true, Address::times_1,  entry,
1999                                NULL, "arrayof_jbyte_arraycopy");
2000     StubRoutines::_jbyte_disjoint_arraycopy =
2001         generate_disjoint_copy(T_BYTE, false, Address::times_1, &entry,
2002                                "jbyte_disjoint_arraycopy");
2003     StubRoutines::_jbyte_arraycopy =
2004         generate_conjoint_copy(T_BYTE, false, Address::times_1,  entry,
2005                                &entry_jbyte_arraycopy, "jbyte_arraycopy");
2006 
2007     StubRoutines::_arrayof_jshort_disjoint_arraycopy =
2008         generate_disjoint_copy(T_SHORT,  true, Address::times_2, &entry,
2009                                "arrayof_jshort_disjoint_arraycopy");
2010     StubRoutines::_arrayof_jshort_arraycopy =
2011         generate_conjoint_copy(T_SHORT,  true, Address::times_2,  entry,
2012                                NULL, "arrayof_jshort_arraycopy");
2013     StubRoutines::_jshort_disjoint_arraycopy =
2014         generate_disjoint_copy(T_SHORT, false, Address::times_2, &entry,
2015                                "jshort_disjoint_arraycopy");
2016     StubRoutines::_jshort_arraycopy =
2017         generate_conjoint_copy(T_SHORT, false, Address::times_2,  entry,
2018                                &entry_jshort_arraycopy, "jshort_arraycopy");
2019 
2020     // Next arrays are always aligned on 4 bytes at least.
2021     StubRoutines::_jint_disjoint_arraycopy =
2022         generate_disjoint_copy(T_INT, true, Address::times_4, &entry,
2023                                "jint_disjoint_arraycopy");
2024     StubRoutines::_jint_arraycopy =
2025         generate_conjoint_copy(T_INT, true, Address::times_4,  entry,
2026                                &entry_jint_arraycopy, "jint_arraycopy");
2027 
2028     StubRoutines::_oop_disjoint_arraycopy =
2029         generate_disjoint_copy(T_OBJECT, true, Address::times_ptr, &entry,
2030                                "oop_disjoint_arraycopy");
2031     StubRoutines::_oop_arraycopy =
2032         generate_conjoint_copy(T_OBJECT, true, Address::times_ptr,  entry,
2033                                &entry_oop_arraycopy, "oop_arraycopy");
2034 
2035     StubRoutines::_oop_disjoint_arraycopy_uninit =
2036         generate_disjoint_copy(T_OBJECT, true, Address::times_ptr, &entry,
2037                                "oop_disjoint_arraycopy_uninit",
2038                                /*dest_uninitialized*/true);
2039     StubRoutines::_oop_arraycopy_uninit =
2040         generate_conjoint_copy(T_OBJECT, true, Address::times_ptr,  entry,
2041                                NULL, "oop_arraycopy_uninit",
2042                                /*dest_uninitialized*/true);
2043 
2044     StubRoutines::_jlong_disjoint_arraycopy =
2045         generate_disjoint_long_copy(&entry, "jlong_disjoint_arraycopy");
2046     StubRoutines::_jlong_arraycopy =
2047         generate_conjoint_long_copy(entry, &entry_jlong_arraycopy,
2048                                     "jlong_arraycopy");
2049 
2050     StubRoutines::_jbyte_fill = generate_fill(T_BYTE, false, "jbyte_fill");
2051     StubRoutines::_jshort_fill = generate_fill(T_SHORT, false, "jshort_fill");
2052     StubRoutines::_jint_fill = generate_fill(T_INT, false, "jint_fill");
2053     StubRoutines::_arrayof_jbyte_fill = generate_fill(T_BYTE, true, "arrayof_jbyte_fill");
2054     StubRoutines::_arrayof_jshort_fill = generate_fill(T_SHORT, true, "arrayof_jshort_fill");
2055     StubRoutines::_arrayof_jint_fill = generate_fill(T_INT, true, "arrayof_jint_fill");
2056 
2057     StubRoutines::_arrayof_jint_disjoint_arraycopy       = StubRoutines::_jint_disjoint_arraycopy;
2058     StubRoutines::_arrayof_oop_disjoint_arraycopy        = StubRoutines::_oop_disjoint_arraycopy;
2059     StubRoutines::_arrayof_oop_disjoint_arraycopy_uninit = StubRoutines::_oop_disjoint_arraycopy_uninit;
2060     StubRoutines::_arrayof_jlong_disjoint_arraycopy      = StubRoutines::_jlong_disjoint_arraycopy;
2061 
2062     StubRoutines::_arrayof_jint_arraycopy       = StubRoutines::_jint_arraycopy;
2063     StubRoutines::_arrayof_oop_arraycopy        = StubRoutines::_oop_arraycopy;
2064     StubRoutines::_arrayof_oop_arraycopy_uninit = StubRoutines::_oop_arraycopy_uninit;
2065     StubRoutines::_arrayof_jlong_arraycopy      = StubRoutines::_jlong_arraycopy;
2066 
2067     StubRoutines::_checkcast_arraycopy =
2068         generate_checkcast_copy("checkcast_arraycopy", &entry_checkcast_arraycopy);
2069     StubRoutines::_checkcast_arraycopy_uninit =
2070         generate_checkcast_copy("checkcast_arraycopy_uninit", NULL, /*dest_uninitialized*/true);
2071 
2072     StubRoutines::_unsafe_arraycopy =
2073         generate_unsafe_copy("unsafe_arraycopy",
2074                                entry_jbyte_arraycopy,
2075                                entry_jshort_arraycopy,
2076                                entry_jint_arraycopy,
2077                                entry_jlong_arraycopy);
2078 
2079     StubRoutines::_generic_arraycopy =
2080         generate_generic_copy("generic_arraycopy",
2081                                entry_jbyte_arraycopy,
2082                                entry_jshort_arraycopy,
2083                                entry_jint_arraycopy,
2084                                entry_oop_arraycopy,
2085                                entry_jlong_arraycopy,
2086                                entry_checkcast_arraycopy);
2087   }
2088 
2089   void generate_math_stubs() {
2090     {
2091       StubCodeMark mark(this, "StubRoutines", "log");
2092       StubRoutines::_intrinsic_log = (double (*)(double)) __ pc();
2093 
2094       __ fld_d(Address(rsp, 4));
2095       __ flog();
2096       __ ret(0);
2097     }
2098     {
2099       StubCodeMark mark(this, "StubRoutines", "log10");
2100       StubRoutines::_intrinsic_log10 = (double (*)(double)) __ pc();
2101 
2102       __ fld_d(Address(rsp, 4));
2103       __ flog10();
2104       __ ret(0);
2105     }
2106     {
2107       StubCodeMark mark(this, "StubRoutines", "sin");
2108       StubRoutines::_intrinsic_sin = (double (*)(double))  __ pc();
2109 
2110       __ fld_d(Address(rsp, 4));
2111       __ trigfunc('s');
2112       __ ret(0);
2113     }
2114     {
2115       StubCodeMark mark(this, "StubRoutines", "cos");
2116       StubRoutines::_intrinsic_cos = (double (*)(double)) __ pc();
2117 
2118       __ fld_d(Address(rsp, 4));
2119       __ trigfunc('c');
2120       __ ret(0);
2121     }
2122     {
2123       StubCodeMark mark(this, "StubRoutines", "tan");
2124       StubRoutines::_intrinsic_tan = (double (*)(double)) __ pc();
2125 
2126       __ fld_d(Address(rsp, 4));
2127       __ trigfunc('t');
2128       __ ret(0);
2129     }
2130     {
2131       StubCodeMark mark(this, "StubRoutines", "exp");
2132       StubRoutines::_intrinsic_exp = (double (*)(double)) __ pc();
2133 
2134       __ fld_d(Address(rsp, 4));
2135       __ exp_with_fallback(0);
2136       __ ret(0);
2137     }
2138     {
2139       StubCodeMark mark(this, "StubRoutines", "pow");
2140       StubRoutines::_intrinsic_pow = (double (*)(double,double)) __ pc();
2141 
2142       __ fld_d(Address(rsp, 12));
2143       __ fld_d(Address(rsp, 4));
2144       __ pow_with_fallback(0);
2145       __ ret(0);
2146     }
2147   }
2148 
2149   // AES intrinsic stubs
2150   enum {AESBlockSize = 16};
2151 
2152   address generate_key_shuffle_mask() {
2153     __ align(16);
2154     StubCodeMark mark(this, "StubRoutines", "key_shuffle_mask");
2155     address start = __ pc();
2156     __ emit_data(0x00010203, relocInfo::none, 0 );
2157     __ emit_data(0x04050607, relocInfo::none, 0 );
2158     __ emit_data(0x08090a0b, relocInfo::none, 0 );
2159     __ emit_data(0x0c0d0e0f, relocInfo::none, 0 );
2160     return start;
2161   }
2162 
2163   // Utility routine for loading a 128-bit key word in little endian format
2164   // can optionally specify that the shuffle mask is already in an xmmregister
2165   void load_key(XMMRegister xmmdst, Register key, int offset, XMMRegister xmm_shuf_mask=NULL) {
2166     __ movdqu(xmmdst, Address(key, offset));
2167     if (xmm_shuf_mask != NULL) {
2168       __ pshufb(xmmdst, xmm_shuf_mask);
2169     } else {
2170       __ pshufb(xmmdst, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2171     }
2172   }
2173 
2174   // aesenc using specified key+offset
2175   // can optionally specify that the shuffle mask is already in an xmmregister
2176   void aes_enc_key(XMMRegister xmmdst, XMMRegister xmmtmp, Register key, int offset, XMMRegister xmm_shuf_mask=NULL) {
2177     load_key(xmmtmp, key, offset, xmm_shuf_mask);
2178     __ aesenc(xmmdst, xmmtmp);
2179   }
2180 
2181   // aesdec using specified key+offset
2182   // can optionally specify that the shuffle mask is already in an xmmregister
2183   void aes_dec_key(XMMRegister xmmdst, XMMRegister xmmtmp, Register key, int offset, XMMRegister xmm_shuf_mask=NULL) {
2184     load_key(xmmtmp, key, offset, xmm_shuf_mask);
2185     __ aesdec(xmmdst, xmmtmp);
2186   }
2187 
2188 
2189   // Arguments:
2190   //
2191   // Inputs:
2192   //   c_rarg0   - source byte array address
2193   //   c_rarg1   - destination byte array address
2194   //   c_rarg2   - K (key) in little endian int array
2195   //
2196   address generate_aescrypt_encryptBlock() {
2197     assert(UseAES, "need AES instructions and misaligned SSE support");
2198     __ align(CodeEntryAlignment);
2199     StubCodeMark mark(this, "StubRoutines", "aescrypt_encryptBlock");
2200     Label L_doLast;
2201     address start = __ pc();
2202 
2203     const Register from        = rdx;      // source array address
2204     const Register to          = rdx;      // destination array address
2205     const Register key         = rcx;      // key array address
2206     const Register keylen      = rax;
2207     const Address  from_param(rbp, 8+0);
2208     const Address  to_param  (rbp, 8+4);
2209     const Address  key_param (rbp, 8+8);
2210 
2211     const XMMRegister xmm_result = xmm0;
2212     const XMMRegister xmm_key_shuf_mask = xmm1;
2213     const XMMRegister xmm_temp1  = xmm2;
2214     const XMMRegister xmm_temp2  = xmm3;
2215     const XMMRegister xmm_temp3  = xmm4;
2216     const XMMRegister xmm_temp4  = xmm5;
2217 
2218     __ enter();   // required for proper stackwalking of RuntimeStub frame
2219     __ movptr(from, from_param);
2220     __ movptr(key, key_param);
2221 
2222     // keylen could be only {11, 13, 15} * 4 = {44, 52, 60}
2223     __ movl(keylen, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
2224 
2225     __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2226     __ movdqu(xmm_result, Address(from, 0));  // get 16 bytes of input
2227     __ movptr(to, to_param);
2228 
2229     // For encryption, the java expanded key ordering is just what we need
2230 
2231     load_key(xmm_temp1, key, 0x00, xmm_key_shuf_mask);
2232     __ pxor(xmm_result, xmm_temp1);
2233 
2234     load_key(xmm_temp1, key, 0x10, xmm_key_shuf_mask);
2235     load_key(xmm_temp2, key, 0x20, xmm_key_shuf_mask);
2236     load_key(xmm_temp3, key, 0x30, xmm_key_shuf_mask);
2237     load_key(xmm_temp4, key, 0x40, xmm_key_shuf_mask);
2238 
2239     __ aesenc(xmm_result, xmm_temp1);
2240     __ aesenc(xmm_result, xmm_temp2);
2241     __ aesenc(xmm_result, xmm_temp3);
2242     __ aesenc(xmm_result, xmm_temp4);
2243 
2244     load_key(xmm_temp1, key, 0x50, xmm_key_shuf_mask);
2245     load_key(xmm_temp2, key, 0x60, xmm_key_shuf_mask);
2246     load_key(xmm_temp3, key, 0x70, xmm_key_shuf_mask);
2247     load_key(xmm_temp4, key, 0x80, xmm_key_shuf_mask);
2248 
2249     __ aesenc(xmm_result, xmm_temp1);
2250     __ aesenc(xmm_result, xmm_temp2);
2251     __ aesenc(xmm_result, xmm_temp3);
2252     __ aesenc(xmm_result, xmm_temp4);
2253 
2254     load_key(xmm_temp1, key, 0x90, xmm_key_shuf_mask);
2255     load_key(xmm_temp2, key, 0xa0, xmm_key_shuf_mask);
2256 
2257     __ cmpl(keylen, 44);
2258     __ jccb(Assembler::equal, L_doLast);
2259 
2260     __ aesenc(xmm_result, xmm_temp1);
2261     __ aesenc(xmm_result, xmm_temp2);
2262 
2263     load_key(xmm_temp1, key, 0xb0, xmm_key_shuf_mask);
2264     load_key(xmm_temp2, key, 0xc0, xmm_key_shuf_mask);
2265 
2266     __ cmpl(keylen, 52);
2267     __ jccb(Assembler::equal, L_doLast);
2268 
2269     __ aesenc(xmm_result, xmm_temp1);
2270     __ aesenc(xmm_result, xmm_temp2);
2271 
2272     load_key(xmm_temp1, key, 0xd0, xmm_key_shuf_mask);
2273     load_key(xmm_temp2, key, 0xe0, xmm_key_shuf_mask);
2274 
2275     __ BIND(L_doLast);
2276     __ aesenc(xmm_result, xmm_temp1);
2277     __ aesenclast(xmm_result, xmm_temp2);
2278     __ movdqu(Address(to, 0), xmm_result);        // store the result
2279     __ xorptr(rax, rax); // return 0
2280     __ leave(); // required for proper stackwalking of RuntimeStub frame
2281     __ ret(0);
2282 
2283     return start;
2284   }
2285 
2286 
2287   // Arguments:
2288   //
2289   // Inputs:
2290   //   c_rarg0   - source byte array address
2291   //   c_rarg1   - destination byte array address
2292   //   c_rarg2   - K (key) in little endian int array
2293   //
2294   address generate_aescrypt_decryptBlock() {
2295     assert(UseAES, "need AES instructions and misaligned SSE support");
2296     __ align(CodeEntryAlignment);
2297     StubCodeMark mark(this, "StubRoutines", "aescrypt_decryptBlock");
2298     Label L_doLast;
2299     address start = __ pc();
2300 
2301     const Register from        = rdx;      // source array address
2302     const Register to          = rdx;      // destination array address
2303     const Register key         = rcx;      // key array address
2304     const Register keylen      = rax;
2305     const Address  from_param(rbp, 8+0);
2306     const Address  to_param  (rbp, 8+4);
2307     const Address  key_param (rbp, 8+8);
2308 
2309     const XMMRegister xmm_result = xmm0;
2310     const XMMRegister xmm_key_shuf_mask = xmm1;
2311     const XMMRegister xmm_temp1  = xmm2;
2312     const XMMRegister xmm_temp2  = xmm3;
2313     const XMMRegister xmm_temp3  = xmm4;
2314     const XMMRegister xmm_temp4  = xmm5;
2315 
2316     __ enter(); // required for proper stackwalking of RuntimeStub frame
2317     __ movptr(from, from_param);
2318     __ movptr(key, key_param);
2319 
2320     // keylen could be only {11, 13, 15} * 4 = {44, 52, 60}
2321     __ movl(keylen, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
2322 
2323     __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2324     __ movdqu(xmm_result, Address(from, 0));
2325     __ movptr(to, to_param);
2326 
2327     // for decryption java expanded key ordering is rotated one position from what we want
2328     // so we start from 0x10 here and hit 0x00 last
2329     // we don't know if the key is aligned, hence not using load-execute form
2330     load_key(xmm_temp1, key, 0x10, xmm_key_shuf_mask);
2331     load_key(xmm_temp2, key, 0x20, xmm_key_shuf_mask);
2332     load_key(xmm_temp3, key, 0x30, xmm_key_shuf_mask);
2333     load_key(xmm_temp4, key, 0x40, xmm_key_shuf_mask);
2334 
2335     __ pxor  (xmm_result, xmm_temp1);
2336     __ aesdec(xmm_result, xmm_temp2);
2337     __ aesdec(xmm_result, xmm_temp3);
2338     __ aesdec(xmm_result, xmm_temp4);
2339 
2340     load_key(xmm_temp1, key, 0x50, xmm_key_shuf_mask);
2341     load_key(xmm_temp2, key, 0x60, xmm_key_shuf_mask);
2342     load_key(xmm_temp3, key, 0x70, xmm_key_shuf_mask);
2343     load_key(xmm_temp4, key, 0x80, xmm_key_shuf_mask);
2344 
2345     __ aesdec(xmm_result, xmm_temp1);
2346     __ aesdec(xmm_result, xmm_temp2);
2347     __ aesdec(xmm_result, xmm_temp3);
2348     __ aesdec(xmm_result, xmm_temp4);
2349 
2350     load_key(xmm_temp1, key, 0x90, xmm_key_shuf_mask);
2351     load_key(xmm_temp2, key, 0xa0, xmm_key_shuf_mask);
2352     load_key(xmm_temp3, key, 0x00, xmm_key_shuf_mask);
2353 
2354     __ cmpl(keylen, 44);
2355     __ jccb(Assembler::equal, L_doLast);
2356 
2357     __ aesdec(xmm_result, xmm_temp1);
2358     __ aesdec(xmm_result, xmm_temp2);
2359 
2360     load_key(xmm_temp1, key, 0xb0, xmm_key_shuf_mask);
2361     load_key(xmm_temp2, key, 0xc0, xmm_key_shuf_mask);
2362 
2363     __ cmpl(keylen, 52);
2364     __ jccb(Assembler::equal, L_doLast);
2365 
2366     __ aesdec(xmm_result, xmm_temp1);
2367     __ aesdec(xmm_result, xmm_temp2);
2368 
2369     load_key(xmm_temp1, key, 0xd0, xmm_key_shuf_mask);
2370     load_key(xmm_temp2, key, 0xe0, xmm_key_shuf_mask);
2371 
2372     __ BIND(L_doLast);
2373     __ aesdec(xmm_result, xmm_temp1);
2374     __ aesdec(xmm_result, xmm_temp2);
2375 
2376     // for decryption the aesdeclast operation is always on key+0x00
2377     __ aesdeclast(xmm_result, xmm_temp3);
2378     __ movdqu(Address(to, 0), xmm_result);  // store the result
2379     __ xorptr(rax, rax); // return 0
2380     __ leave(); // required for proper stackwalking of RuntimeStub frame
2381     __ ret(0);
2382 
2383     return start;
2384   }
2385 
2386   void handleSOERegisters(bool saving) {
2387     const int saveFrameSizeInBytes = 4 * wordSize;
2388     const Address saved_rbx     (rbp, -3 * wordSize);
2389     const Address saved_rsi     (rbp, -2 * wordSize);
2390     const Address saved_rdi     (rbp, -1 * wordSize);
2391 
2392     if (saving) {
2393       __ subptr(rsp, saveFrameSizeInBytes);
2394       __ movptr(saved_rsi, rsi);
2395       __ movptr(saved_rdi, rdi);
2396       __ movptr(saved_rbx, rbx);
2397     } else {
2398       // restoring
2399       __ movptr(rsi, saved_rsi);
2400       __ movptr(rdi, saved_rdi);
2401       __ movptr(rbx, saved_rbx);
2402     }
2403   }
2404 
2405   // Arguments:
2406   //
2407   // Inputs:
2408   //   c_rarg0   - source byte array address
2409   //   c_rarg1   - destination byte array address
2410   //   c_rarg2   - K (key) in little endian int array
2411   //   c_rarg3   - r vector byte array address
2412   //   c_rarg4   - input length
2413   //
2414   // Output:
2415   //   rax       - input length
2416   //
2417   address generate_cipherBlockChaining_encryptAESCrypt() {
2418     assert(UseAES, "need AES instructions and misaligned SSE support");
2419     __ align(CodeEntryAlignment);
2420     StubCodeMark mark(this, "StubRoutines", "cipherBlockChaining_encryptAESCrypt");
2421     address start = __ pc();
2422 
2423     Label L_exit, L_key_192_256, L_key_256, L_loopTop_128, L_loopTop_192, L_loopTop_256;
2424     const Register from        = rsi;      // source array address
2425     const Register to          = rdx;      // destination array address
2426     const Register key         = rcx;      // key array address
2427     const Register rvec        = rdi;      // r byte array initialized from initvector array address
2428                                            // and left with the results of the last encryption block
2429     const Register len_reg     = rbx;      // src len (must be multiple of blocksize 16)
2430     const Register pos         = rax;
2431 
2432     // xmm register assignments for the loops below
2433     const XMMRegister xmm_result = xmm0;
2434     const XMMRegister xmm_temp   = xmm1;
2435     // first 6 keys preloaded into xmm2-xmm7
2436     const int XMM_REG_NUM_KEY_FIRST = 2;
2437     const int XMM_REG_NUM_KEY_LAST  = 7;
2438     const XMMRegister xmm_key0   = as_XMMRegister(XMM_REG_NUM_KEY_FIRST);
2439 
2440     __ enter(); // required for proper stackwalking of RuntimeStub frame
2441     handleSOERegisters(true /*saving*/);
2442 
2443     // load registers from incoming parameters
2444     const Address  from_param(rbp, 8+0);
2445     const Address  to_param  (rbp, 8+4);
2446     const Address  key_param (rbp, 8+8);
2447     const Address  rvec_param (rbp, 8+12);
2448     const Address  len_param  (rbp, 8+16);
2449     __ movptr(from , from_param);
2450     __ movptr(to   , to_param);
2451     __ movptr(key  , key_param);
2452     __ movptr(rvec , rvec_param);
2453     __ movptr(len_reg , len_param);
2454 
2455     const XMMRegister xmm_key_shuf_mask = xmm_temp;  // used temporarily to swap key bytes up front
2456     __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2457     // load up xmm regs 2 thru 7 with keys 0-5
2458     for (int rnum = XMM_REG_NUM_KEY_FIRST, offset = 0x00; rnum  <= XMM_REG_NUM_KEY_LAST; rnum++) {
2459       load_key(as_XMMRegister(rnum), key, offset, xmm_key_shuf_mask);
2460       offset += 0x10;
2461     }
2462 
2463     __ movdqu(xmm_result, Address(rvec, 0x00));   // initialize xmm_result with r vec
2464 
2465     // now split to different paths depending on the keylen (len in ints of AESCrypt.KLE array (52=192, or 60=256))
2466     __ movl(rax, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
2467     __ cmpl(rax, 44);
2468     __ jcc(Assembler::notEqual, L_key_192_256);
2469 
2470     // 128 bit code follows here
2471     __ movl(pos, 0);
2472     __ align(OptoLoopAlignment);
2473     __ BIND(L_loopTop_128);
2474     __ movdqu(xmm_temp, Address(from, pos, Address::times_1, 0));   // get next 16 bytes of input
2475     __ pxor  (xmm_result, xmm_temp);                                // xor with the current r vector
2476 
2477     __ pxor  (xmm_result, xmm_key0);                                // do the aes rounds
2478     for (int rnum = XMM_REG_NUM_KEY_FIRST + 1; rnum  <= XMM_REG_NUM_KEY_LAST; rnum++) {
2479       __ aesenc(xmm_result, as_XMMRegister(rnum));
2480     }
2481     for (int key_offset = 0x60; key_offset <= 0x90; key_offset += 0x10) {
2482       aes_enc_key(xmm_result, xmm_temp, key, key_offset);
2483     }
2484     load_key(xmm_temp, key, 0xa0);
2485     __ aesenclast(xmm_result, xmm_temp);
2486 
2487     __ movdqu(Address(to, pos, Address::times_1, 0), xmm_result);     // store into the next 16 bytes of output
2488     // no need to store r to memory until we exit
2489     __ addptr(pos, AESBlockSize);
2490     __ subptr(len_reg, AESBlockSize);
2491     __ jcc(Assembler::notEqual, L_loopTop_128);
2492 
2493     __ BIND(L_exit);
2494     __ movdqu(Address(rvec, 0), xmm_result);     // final value of r stored in rvec of CipherBlockChaining object
2495 
2496     handleSOERegisters(false /*restoring*/);
2497     __ movptr(rax, len_param); // return length
2498     __ leave();                                  // required for proper stackwalking of RuntimeStub frame
2499     __ ret(0);
2500 
2501     __ BIND(L_key_192_256);
2502     // here rax = len in ints of AESCrypt.KLE array (52=192, or 60=256)
2503     __ cmpl(rax, 52);
2504     __ jcc(Assembler::notEqual, L_key_256);
2505 
2506     // 192-bit code follows here (could be changed to use more xmm registers)
2507     __ movl(pos, 0);
2508     __ align(OptoLoopAlignment);
2509     __ BIND(L_loopTop_192);
2510     __ movdqu(xmm_temp, Address(from, pos, Address::times_1, 0));   // get next 16 bytes of input
2511     __ pxor  (xmm_result, xmm_temp);                                // xor with the current r vector
2512 
2513     __ pxor  (xmm_result, xmm_key0);                                // do the aes rounds
2514     for (int rnum = XMM_REG_NUM_KEY_FIRST + 1; rnum  <= XMM_REG_NUM_KEY_LAST; rnum++) {
2515       __ aesenc(xmm_result, as_XMMRegister(rnum));
2516     }
2517     for (int key_offset = 0x60; key_offset <= 0xb0; key_offset += 0x10) {
2518       aes_enc_key(xmm_result, xmm_temp, key, key_offset);
2519     }
2520     load_key(xmm_temp, key, 0xc0);
2521     __ aesenclast(xmm_result, xmm_temp);
2522 
2523     __ movdqu(Address(to, pos, Address::times_1, 0), xmm_result);   // store into the next 16 bytes of output
2524     // no need to store r to memory until we exit
2525     __ addptr(pos, AESBlockSize);
2526     __ subptr(len_reg, AESBlockSize);
2527     __ jcc(Assembler::notEqual, L_loopTop_192);
2528     __ jmp(L_exit);
2529 
2530     __ BIND(L_key_256);
2531     // 256-bit code follows here (could be changed to use more xmm registers)
2532     __ movl(pos, 0);
2533     __ align(OptoLoopAlignment);
2534     __ BIND(L_loopTop_256);
2535     __ movdqu(xmm_temp, Address(from, pos, Address::times_1, 0));   // get next 16 bytes of input
2536     __ pxor  (xmm_result, xmm_temp);                                // xor with the current r vector
2537 
2538     __ pxor  (xmm_result, xmm_key0);                                // do the aes rounds
2539     for (int rnum = XMM_REG_NUM_KEY_FIRST + 1; rnum  <= XMM_REG_NUM_KEY_LAST; rnum++) {
2540       __ aesenc(xmm_result, as_XMMRegister(rnum));
2541     }
2542     for (int key_offset = 0x60; key_offset <= 0xd0; key_offset += 0x10) {
2543       aes_enc_key(xmm_result, xmm_temp, key, key_offset);
2544     }
2545     load_key(xmm_temp, key, 0xe0);
2546     __ aesenclast(xmm_result, xmm_temp);
2547 
2548     __ movdqu(Address(to, pos, Address::times_1, 0), xmm_result);   // store into the next 16 bytes of output
2549     // no need to store r to memory until we exit
2550     __ addptr(pos, AESBlockSize);
2551     __ subptr(len_reg, AESBlockSize);
2552     __ jcc(Assembler::notEqual, L_loopTop_256);
2553     __ jmp(L_exit);
2554 
2555     return start;
2556   }
2557 
2558 
2559   // CBC AES Decryption.
2560   // In 32-bit stub, because of lack of registers we do not try to parallelize 4 blocks at a time.
2561   //
2562   // Arguments:
2563   //
2564   // Inputs:
2565   //   c_rarg0   - source byte array address
2566   //   c_rarg1   - destination byte array address
2567   //   c_rarg2   - K (key) in little endian int array
2568   //   c_rarg3   - r vector byte array address
2569   //   c_rarg4   - input length
2570   //
2571   // Output:
2572   //   rax       - input length
2573   //
2574 
2575   address generate_cipherBlockChaining_decryptAESCrypt() {
2576     assert(UseAES, "need AES instructions and misaligned SSE support");
2577     __ align(CodeEntryAlignment);
2578     StubCodeMark mark(this, "StubRoutines", "cipherBlockChaining_decryptAESCrypt");
2579     address start = __ pc();
2580 
2581     Label L_exit, L_key_192_256, L_key_256;
2582     Label L_singleBlock_loopTop_128;
2583     Label L_singleBlock_loopTop_192, L_singleBlock_loopTop_256;
2584     const Register from        = rsi;      // source array address
2585     const Register to          = rdx;      // destination array address
2586     const Register key         = rcx;      // key array address
2587     const Register rvec        = rdi;      // r byte array initialized from initvector array address
2588                                            // and left with the results of the last encryption block
2589     const Register len_reg     = rbx;      // src len (must be multiple of blocksize 16)
2590     const Register pos         = rax;
2591 
2592     // xmm register assignments for the loops below
2593     const XMMRegister xmm_result = xmm0;
2594     const XMMRegister xmm_temp   = xmm1;
2595     // first 6 keys preloaded into xmm2-xmm7
2596     const int XMM_REG_NUM_KEY_FIRST = 2;
2597     const int XMM_REG_NUM_KEY_LAST  = 7;
2598     const int FIRST_NON_REG_KEY_offset = 0x70;
2599     const XMMRegister xmm_key_first   = as_XMMRegister(XMM_REG_NUM_KEY_FIRST);
2600 
2601     __ enter(); // required for proper stackwalking of RuntimeStub frame
2602     handleSOERegisters(true /*saving*/);
2603 
2604     // load registers from incoming parameters
2605     const Address  from_param(rbp, 8+0);
2606     const Address  to_param  (rbp, 8+4);
2607     const Address  key_param (rbp, 8+8);
2608     const Address  rvec_param (rbp, 8+12);
2609     const Address  len_param  (rbp, 8+16);
2610     __ movptr(from , from_param);
2611     __ movptr(to   , to_param);
2612     __ movptr(key  , key_param);
2613     __ movptr(rvec , rvec_param);
2614     __ movptr(len_reg , len_param);
2615 
2616     // the java expanded key ordering is rotated one position from what we want
2617     // so we start from 0x10 here and hit 0x00 last
2618     const XMMRegister xmm_key_shuf_mask = xmm1;  // used temporarily to swap key bytes up front
2619     __ movdqu(xmm_key_shuf_mask, ExternalAddress(StubRoutines::x86::key_shuffle_mask_addr()));
2620     // load up xmm regs 2 thru 6 with first 5 keys
2621     for (int rnum = XMM_REG_NUM_KEY_FIRST, offset = 0x10; rnum  <= XMM_REG_NUM_KEY_LAST; rnum++) {
2622       load_key(as_XMMRegister(rnum), key, offset, xmm_key_shuf_mask);
2623       offset += 0x10;
2624     }
2625 
2626     // inside here, use the rvec register to point to previous block cipher
2627     // with which we xor at the end of each newly decrypted block
2628     const Register  prev_block_cipher_ptr = rvec;
2629 
2630     // now split to different paths depending on the keylen (len in ints of AESCrypt.KLE array (52=192, or 60=256))
2631     __ movl(rax, Address(key, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT)));
2632     __ cmpl(rax, 44);
2633     __ jcc(Assembler::notEqual, L_key_192_256);
2634 
2635 
2636     // 128-bit code follows here, parallelized
2637     __ movl(pos, 0);
2638     __ align(OptoLoopAlignment);
2639     __ BIND(L_singleBlock_loopTop_128);
2640     __ cmpptr(len_reg, 0);           // any blocks left??
2641     __ jcc(Assembler::equal, L_exit);
2642     __ movdqu(xmm_result, Address(from, pos, Address::times_1, 0));   // get next 16 bytes of cipher input
2643     __ pxor  (xmm_result, xmm_key_first);                             // do the aes dec rounds
2644     for (int rnum = XMM_REG_NUM_KEY_FIRST + 1; rnum  <= XMM_REG_NUM_KEY_LAST; rnum++) {
2645       __ aesdec(xmm_result, as_XMMRegister(rnum));
2646     }
2647     for (int key_offset = FIRST_NON_REG_KEY_offset; key_offset <= 0xa0; key_offset += 0x10) {   // 128-bit runs up to key offset a0
2648       aes_dec_key(xmm_result, xmm_temp, key, key_offset);
2649     }
2650     load_key(xmm_temp, key, 0x00);                                     // final key is stored in java expanded array at offset 0
2651     __ aesdeclast(xmm_result, xmm_temp);
2652     __ movdqu(xmm_temp, Address(prev_block_cipher_ptr, 0x00));
2653     __ pxor  (xmm_result, xmm_temp);                                  // xor with the current r vector
2654     __ movdqu(Address(to, pos, Address::times_1, 0), xmm_result);     // store into the next 16 bytes of output
2655     // no need to store r to memory until we exit
2656     __ lea(prev_block_cipher_ptr, Address(from, pos, Address::times_1, 0));     // set up new ptr
2657     __ addptr(pos, AESBlockSize);
2658     __ subptr(len_reg, AESBlockSize);
2659     __ jmp(L_singleBlock_loopTop_128);
2660 
2661 
2662     __ BIND(L_exit);
2663     __ movdqu(xmm_temp, Address(prev_block_cipher_ptr, 0x00));
2664     __ movptr(rvec , rvec_param);                                     // restore this since used in loop
2665     __ movdqu(Address(rvec, 0), xmm_temp);                            // final value of r stored in rvec of CipherBlockChaining object
2666     handleSOERegisters(false /*restoring*/);
2667     __ movptr(rax, len_param); // return length
2668     __ leave();                                                       // required for proper stackwalking of RuntimeStub frame
2669     __ ret(0);
2670 
2671 
2672     __ BIND(L_key_192_256);
2673     // here rax = len in ints of AESCrypt.KLE array (52=192, or 60=256)
2674     __ cmpl(rax, 52);
2675     __ jcc(Assembler::notEqual, L_key_256);
2676 
2677     // 192-bit code follows here (could be optimized to use parallelism)
2678     __ movl(pos, 0);
2679     __ align(OptoLoopAlignment);
2680     __ BIND(L_singleBlock_loopTop_192);
2681     __ movdqu(xmm_result, Address(from, pos, Address::times_1, 0));   // get next 16 bytes of cipher input
2682     __ pxor  (xmm_result, xmm_key_first);                             // do the aes dec rounds
2683     for (int rnum = XMM_REG_NUM_KEY_FIRST + 1; rnum <= XMM_REG_NUM_KEY_LAST; rnum++) {
2684       __ aesdec(xmm_result, as_XMMRegister(rnum));
2685     }
2686     for (int key_offset = FIRST_NON_REG_KEY_offset; key_offset <= 0xc0; key_offset += 0x10) {   // 192-bit runs up to key offset c0
2687       aes_dec_key(xmm_result, xmm_temp, key, key_offset);
2688     }
2689     load_key(xmm_temp, key, 0x00);                                     // final key is stored in java expanded array at offset 0
2690     __ aesdeclast(xmm_result, xmm_temp);
2691     __ movdqu(xmm_temp, Address(prev_block_cipher_ptr, 0x00));
2692     __ pxor  (xmm_result, xmm_temp);                                  // xor with the current r vector
2693     __ movdqu(Address(to, pos, Address::times_1, 0), xmm_result);     // store into the next 16 bytes of output
2694     // no need to store r to memory until we exit
2695     __ lea(prev_block_cipher_ptr, Address(from, pos, Address::times_1, 0));     // set up new ptr
2696     __ addptr(pos, AESBlockSize);
2697     __ subptr(len_reg, AESBlockSize);
2698     __ jcc(Assembler::notEqual,L_singleBlock_loopTop_192);
2699     __ jmp(L_exit);
2700 
2701     __ BIND(L_key_256);
2702     // 256-bit code follows here (could be optimized to use parallelism)
2703     __ movl(pos, 0);
2704     __ align(OptoLoopAlignment);
2705     __ BIND(L_singleBlock_loopTop_256);
2706     __ movdqu(xmm_result, Address(from, pos, Address::times_1, 0));   // get next 16 bytes of cipher input
2707     __ pxor  (xmm_result, xmm_key_first);                             // do the aes dec rounds
2708     for (int rnum = XMM_REG_NUM_KEY_FIRST + 1; rnum <= XMM_REG_NUM_KEY_LAST; rnum++) {
2709       __ aesdec(xmm_result, as_XMMRegister(rnum));
2710     }
2711     for (int key_offset = FIRST_NON_REG_KEY_offset; key_offset <= 0xe0; key_offset += 0x10) {   // 256-bit runs up to key offset e0
2712       aes_dec_key(xmm_result, xmm_temp, key, key_offset);
2713     }
2714     load_key(xmm_temp, key, 0x00);                                     // final key is stored in java expanded array at offset 0
2715     __ aesdeclast(xmm_result, xmm_temp);
2716     __ movdqu(xmm_temp, Address(prev_block_cipher_ptr, 0x00));
2717     __ pxor  (xmm_result, xmm_temp);                                  // xor with the current r vector
2718     __ movdqu(Address(to, pos, Address::times_1, 0), xmm_result);     // store into the next 16 bytes of output
2719     // no need to store r to memory until we exit
2720     __ lea(prev_block_cipher_ptr, Address(from, pos, Address::times_1, 0));     // set up new ptr
2721     __ addptr(pos, AESBlockSize);
2722     __ subptr(len_reg, AESBlockSize);
2723     __ jcc(Assembler::notEqual,L_singleBlock_loopTop_256);
2724     __ jmp(L_exit);
2725 
2726     return start;
2727   }
2728 
2729   /**
2730    *  Arguments:
2731    *
2732    * Inputs:
2733    *   rsp(4)   - int crc
2734    *   rsp(8)   - byte* buf
2735    *   rsp(12)  - int length
2736    *
2737    * Ouput:
2738    *       rax   - int crc result
2739    */
2740   address generate_updateBytesCRC32() {
2741     assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions");
2742 
2743     __ align(CodeEntryAlignment);
2744     StubCodeMark mark(this, "StubRoutines", "updateBytesCRC32");
2745 
2746     address start = __ pc();
2747 
2748     const Register crc   = rdx;  // crc
2749     const Register buf   = rsi;  // source java byte array address
2750     const Register len   = rcx;  // length
2751     const Register table = rdi;  // crc_table address (reuse register)
2752     const Register tmp   = rbx;
2753     assert_different_registers(crc, buf, len, table, tmp, rax);
2754 
2755     BLOCK_COMMENT("Entry:");
2756     __ enter(); // required for proper stackwalking of RuntimeStub frame
2757     __ push(rsi);
2758     __ push(rdi);
2759     __ push(rbx);
2760 
2761     Address crc_arg(rbp, 8 + 0);
2762     Address buf_arg(rbp, 8 + 4);
2763     Address len_arg(rbp, 8 + 8);
2764 
2765     // Load up:
2766     __ movl(crc,   crc_arg);
2767     __ movptr(buf, buf_arg);
2768     __ movl(len,   len_arg);
2769 
2770     __ kernel_crc32(crc, buf, len, table, tmp);
2771 
2772     __ movl(rax, crc);
2773     __ pop(rbx);
2774     __ pop(rdi);
2775     __ pop(rsi);
2776     __ leave(); // required for proper stackwalking of RuntimeStub frame
2777     __ ret(0);
2778 
2779     return start;
2780   }
2781 
2782   // Safefetch stubs.
2783   void generate_safefetch(const char* name, int size, address* entry,
2784                           address* fault_pc, address* continuation_pc) {
2785     // safefetch signatures:
2786     //   int      SafeFetch32(int*      adr, int      errValue);
2787     //   intptr_t SafeFetchN (intptr_t* adr, intptr_t errValue);
2788 
2789     StubCodeMark mark(this, "StubRoutines", name);
2790 
2791     // Entry point, pc or function descriptor.
2792     *entry = __ pc();
2793 
2794     __ movl(rax, Address(rsp, 0x8));
2795     __ movl(rcx, Address(rsp, 0x4));
2796     // Load *adr into eax, may fault.
2797     *fault_pc = __ pc();
2798     switch (size) {
2799       case 4:
2800         // int32_t
2801         __ movl(rax, Address(rcx, 0));
2802         break;
2803       case 8:
2804         // int64_t
2805         Unimplemented();
2806         break;
2807       default:
2808         ShouldNotReachHere();
2809     }
2810 
2811     // Return errValue or *adr.
2812     *continuation_pc = __ pc();
2813     __ ret(0);
2814   }
2815 
2816  public:
2817   // Information about frame layout at time of blocking runtime call.
2818   // Note that we only have to preserve callee-saved registers since
2819   // the compilers are responsible for supplying a continuation point
2820   // if they expect all registers to be preserved.
2821   enum layout {
2822     thread_off,    // last_java_sp
2823     arg1_off,
2824     arg2_off,
2825     rbp_off,       // callee saved register
2826     ret_pc,
2827     framesize
2828   };
2829 
2830  private:
2831 
2832 #undef  __
2833 #define __ masm->
2834 
2835   //------------------------------------------------------------------------------------------------------------------------
2836   // Continuation point for throwing of implicit exceptions that are not handled in
2837   // the current activation. Fabricates an exception oop and initiates normal
2838   // exception dispatching in this frame.
2839   //
2840   // Previously the compiler (c2) allowed for callee save registers on Java calls.
2841   // This is no longer true after adapter frames were removed but could possibly
2842   // be brought back in the future if the interpreter code was reworked and it
2843   // was deemed worthwhile. The comment below was left to describe what must
2844   // happen here if callee saves were resurrected. As it stands now this stub
2845   // could actually be a vanilla BufferBlob and have now oopMap at all.
2846   // Since it doesn't make much difference we've chosen to leave it the
2847   // way it was in the callee save days and keep the comment.
2848 
2849   // If we need to preserve callee-saved values we need a callee-saved oop map and
2850   // therefore have to make these stubs into RuntimeStubs rather than BufferBlobs.
2851   // If the compiler needs all registers to be preserved between the fault
2852   // point and the exception handler then it must assume responsibility for that in
2853   // AbstractCompiler::continuation_for_implicit_null_exception or
2854   // continuation_for_implicit_division_by_zero_exception. All other implicit
2855   // exceptions (e.g., NullPointerException or AbstractMethodError on entry) are
2856   // either at call sites or otherwise assume that stack unwinding will be initiated,
2857   // so caller saved registers were assumed volatile in the compiler.
2858   address generate_throw_exception(const char* name, address runtime_entry,
2859                                    Register arg1 = noreg, Register arg2 = noreg) {
2860 
2861     int insts_size = 256;
2862     int locs_size  = 32;
2863 
2864     CodeBuffer code(name, insts_size, locs_size);
2865     OopMapSet* oop_maps  = new OopMapSet();
2866     MacroAssembler* masm = new MacroAssembler(&code);
2867 
2868     address start = __ pc();
2869 
2870     // This is an inlined and slightly modified version of call_VM
2871     // which has the ability to fetch the return PC out of
2872     // thread-local storage and also sets up last_Java_sp slightly
2873     // differently than the real call_VM
2874     Register java_thread = rbx;
2875     __ get_thread(java_thread);
2876 
2877     __ enter(); // required for proper stackwalking of RuntimeStub frame
2878 
2879     // pc and rbp, already pushed
2880     __ subptr(rsp, (framesize-2) * wordSize); // prolog
2881 
2882     // Frame is now completed as far as size and linkage.
2883 
2884     int frame_complete = __ pc() - start;
2885 
2886     // push java thread (becomes first argument of C function)
2887     __ movptr(Address(rsp, thread_off * wordSize), java_thread);
2888     if (arg1 != noreg) {
2889       __ movptr(Address(rsp, arg1_off * wordSize), arg1);
2890     }
2891     if (arg2 != noreg) {
2892       assert(arg1 != noreg, "missing reg arg");
2893       __ movptr(Address(rsp, arg2_off * wordSize), arg2);
2894     }
2895 
2896     // Set up last_Java_sp and last_Java_fp
2897     __ set_last_Java_frame(java_thread, rsp, rbp, NULL);
2898 
2899     // Call runtime
2900     BLOCK_COMMENT("call runtime_entry");
2901     __ call(RuntimeAddress(runtime_entry));
2902     // Generate oop map
2903     OopMap* map =  new OopMap(framesize, 0);
2904     oop_maps->add_gc_map(__ pc() - start, map);
2905 
2906     // restore the thread (cannot use the pushed argument since arguments
2907     // may be overwritten by C code generated by an optimizing compiler);
2908     // however can use the register value directly if it is callee saved.
2909     __ get_thread(java_thread);
2910 
2911     __ reset_last_Java_frame(java_thread, true, false);
2912 
2913     __ leave(); // required for proper stackwalking of RuntimeStub frame
2914 
2915     // check for pending exceptions
2916 #ifdef ASSERT
2917     Label L;
2918     __ cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
2919     __ jcc(Assembler::notEqual, L);
2920     __ should_not_reach_here();
2921     __ bind(L);
2922 #endif /* ASSERT */
2923     __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2924 
2925 
2926     RuntimeStub* stub = RuntimeStub::new_runtime_stub(name, &code, frame_complete, framesize, oop_maps, false);
2927     return stub->entry_point();
2928   }
2929 
2930 
2931   void create_control_words() {
2932     // Round to nearest, 53-bit mode, exceptions masked
2933     StubRoutines::_fpu_cntrl_wrd_std   = 0x027F;
2934     // Round to zero, 53-bit mode, exception mased
2935     StubRoutines::_fpu_cntrl_wrd_trunc = 0x0D7F;
2936     // Round to nearest, 24-bit mode, exceptions masked
2937     StubRoutines::_fpu_cntrl_wrd_24    = 0x007F;
2938     // Round to nearest, 64-bit mode, exceptions masked
2939     StubRoutines::_fpu_cntrl_wrd_64    = 0x037F;
2940     // Round to nearest, 64-bit mode, exceptions masked
2941     StubRoutines::_mxcsr_std           = 0x1F80;
2942     // Note: the following two constants are 80-bit values
2943     //       layout is critical for correct loading by FPU.
2944     // Bias for strict fp multiply/divide
2945     StubRoutines::_fpu_subnormal_bias1[0]= 0x00000000; // 2^(-15360) == 0x03ff 8000 0000 0000 0000
2946     StubRoutines::_fpu_subnormal_bias1[1]= 0x80000000;
2947     StubRoutines::_fpu_subnormal_bias1[2]= 0x03ff;
2948     // Un-Bias for strict fp multiply/divide
2949     StubRoutines::_fpu_subnormal_bias2[0]= 0x00000000; // 2^(+15360) == 0x7bff 8000 0000 0000 0000
2950     StubRoutines::_fpu_subnormal_bias2[1]= 0x80000000;
2951     StubRoutines::_fpu_subnormal_bias2[2]= 0x7bff;
2952   }
2953 
2954   //---------------------------------------------------------------------------
2955   // Initialization
2956 
2957   void generate_initial() {
2958     // Generates all stubs and initializes the entry points
2959 
2960     //------------------------------------------------------------------------------------------------------------------------
2961     // entry points that exist in all platforms
2962     // Note: This is code that could be shared among different platforms - however the benefit seems to be smaller than
2963     //       the disadvantage of having a much more complicated generator structure. See also comment in stubRoutines.hpp.
2964     StubRoutines::_forward_exception_entry      = generate_forward_exception();
2965 
2966     StubRoutines::_call_stub_entry              =
2967       generate_call_stub(StubRoutines::_call_stub_return_address);
2968     // is referenced by megamorphic call
2969     StubRoutines::_catch_exception_entry        = generate_catch_exception();
2970 
2971     // These are currently used by Solaris/Intel
2972     StubRoutines::_atomic_xchg_entry            = generate_atomic_xchg();
2973 
2974     StubRoutines::_handler_for_unsafe_access_entry =
2975       generate_handler_for_unsafe_access();
2976 
2977     // platform dependent
2978     create_control_words();
2979 
2980     StubRoutines::x86::_verify_mxcsr_entry                 = generate_verify_mxcsr();
2981     StubRoutines::x86::_verify_fpu_cntrl_wrd_entry         = generate_verify_fpu_cntrl_wrd();
2982     StubRoutines::_d2i_wrapper                              = generate_d2i_wrapper(T_INT,
2983                                                                                    CAST_FROM_FN_PTR(address, SharedRuntime::d2i));
2984     StubRoutines::_d2l_wrapper                              = generate_d2i_wrapper(T_LONG,
2985                                                                                    CAST_FROM_FN_PTR(address, SharedRuntime::d2l));
2986 
2987     // Build this early so it's available for the interpreter
2988     StubRoutines::_throw_StackOverflowError_entry          = generate_throw_exception("StackOverflowError throw_exception",           CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError));
2989 
2990     if (UseCRC32Intrinsics) {
2991       // set table address before stub generation which use it
2992       StubRoutines::_crc_table_adr = (address)StubRoutines::x86::_crc_table;
2993       StubRoutines::_updateBytesCRC32 = generate_updateBytesCRC32();
2994     }
2995   }
2996 
2997 
2998   void generate_all() {
2999     // Generates all stubs and initializes the entry points
3000 
3001     // These entry points require SharedInfo::stack0 to be set up in non-core builds
3002     // and need to be relocatable, so they each fabricate a RuntimeStub internally.
3003     StubRoutines::_throw_AbstractMethodError_entry         = generate_throw_exception("AbstractMethodError throw_exception",          CAST_FROM_FN_PTR(address, SharedRuntime::throw_AbstractMethodError));
3004     StubRoutines::_throw_IncompatibleClassChangeError_entry= generate_throw_exception("IncompatibleClassChangeError throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_IncompatibleClassChangeError));
3005     StubRoutines::_throw_NullPointerException_at_call_entry= generate_throw_exception("NullPointerException at call throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException_at_call));
3006 
3007     //------------------------------------------------------------------------------------------------------------------------
3008     // entry points that are platform specific
3009 
3010     // support for verify_oop (must happen after universe_init)
3011     StubRoutines::_verify_oop_subroutine_entry     = generate_verify_oop();
3012 
3013     // arraycopy stubs used by compilers
3014     generate_arraycopy_stubs();
3015 
3016     generate_math_stubs();
3017 
3018     // don't bother generating these AES intrinsic stubs unless global flag is set
3019     if (UseAESIntrinsics) {
3020       StubRoutines::x86::_key_shuffle_mask_addr = generate_key_shuffle_mask();  // might be needed by the others
3021 
3022       StubRoutines::_aescrypt_encryptBlock = generate_aescrypt_encryptBlock();
3023       StubRoutines::_aescrypt_decryptBlock = generate_aescrypt_decryptBlock();
3024       StubRoutines::_cipherBlockChaining_encryptAESCrypt = generate_cipherBlockChaining_encryptAESCrypt();
3025       StubRoutines::_cipherBlockChaining_decryptAESCrypt = generate_cipherBlockChaining_decryptAESCrypt();
3026     }
3027 
3028     // Safefetch stubs.
3029     generate_safefetch("SafeFetch32", sizeof(int), &StubRoutines::_safefetch32_entry,
3030                                                    &StubRoutines::_safefetch32_fault_pc,
3031                                                    &StubRoutines::_safefetch32_continuation_pc);
3032     StubRoutines::_safefetchN_entry           = StubRoutines::_safefetch32_entry;
3033     StubRoutines::_safefetchN_fault_pc        = StubRoutines::_safefetch32_fault_pc;
3034     StubRoutines::_safefetchN_continuation_pc = StubRoutines::_safefetch32_continuation_pc;
3035   }
3036 
3037 
3038  public:
3039   StubGenerator(CodeBuffer* code, bool all) : StubCodeGenerator(code) {
3040     if (all) {
3041       generate_all();
3042     } else {
3043       generate_initial();
3044     }
3045   }
3046 }; // end class declaration
3047 
3048 
3049 void StubGenerator_generate(CodeBuffer* code, bool all) {
3050   StubGenerator g(code, all);
3051 }