library_call.cpp revision 8722:564b61ae7dc8
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 "classfile/systemDictionary.hpp"
28#include "classfile/vmSymbols.hpp"
29#include "compiler/compileBroker.hpp"
30#include "compiler/compileLog.hpp"
31#include "oops/objArrayKlass.hpp"
32#include "opto/addnode.hpp"
33#include "opto/arraycopynode.hpp"
34#include "opto/callGenerator.hpp"
35#include "opto/castnode.hpp"
36#include "opto/cfgnode.hpp"
37#include "opto/convertnode.hpp"
38#include "opto/countbitsnode.hpp"
39#include "opto/intrinsicnode.hpp"
40#include "opto/idealKit.hpp"
41#include "opto/mathexactnode.hpp"
42#include "opto/movenode.hpp"
43#include "opto/mulnode.hpp"
44#include "opto/narrowptrnode.hpp"
45#include "opto/opaquenode.hpp"
46#include "opto/parse.hpp"
47#include "opto/runtime.hpp"
48#include "opto/subnode.hpp"
49#include "prims/nativeLookup.hpp"
50#include "runtime/sharedRuntime.hpp"
51#include "trace/traceMacros.hpp"
52
53class LibraryIntrinsic : public InlineCallGenerator {
54  // Extend the set of intrinsics known to the runtime:
55 public:
56 private:
57  bool             _is_virtual;
58  bool             _does_virtual_dispatch;
59  int8_t           _predicates_count;  // Intrinsic is predicated by several conditions
60  int8_t           _last_predicate; // Last generated predicate
61  vmIntrinsics::ID _intrinsic_id;
62
63 public:
64  LibraryIntrinsic(ciMethod* m, bool is_virtual, int predicates_count, bool does_virtual_dispatch, vmIntrinsics::ID id)
65    : InlineCallGenerator(m),
66      _is_virtual(is_virtual),
67      _does_virtual_dispatch(does_virtual_dispatch),
68      _predicates_count((int8_t)predicates_count),
69      _last_predicate((int8_t)-1),
70      _intrinsic_id(id)
71  {
72  }
73  virtual bool is_intrinsic() const { return true; }
74  virtual bool is_virtual()   const { return _is_virtual; }
75  virtual bool is_predicated() const { return _predicates_count > 0; }
76  virtual int  predicates_count() const { return _predicates_count; }
77  virtual bool does_virtual_dispatch()   const { return _does_virtual_dispatch; }
78  virtual JVMState* generate(JVMState* jvms);
79  virtual Node* generate_predicate(JVMState* jvms, int predicate);
80  vmIntrinsics::ID intrinsic_id() const { return _intrinsic_id; }
81};
82
83
84// Local helper class for LibraryIntrinsic:
85class LibraryCallKit : public GraphKit {
86 private:
87  LibraryIntrinsic* _intrinsic;     // the library intrinsic being called
88  Node*             _result;        // the result node, if any
89  int               _reexecute_sp;  // the stack pointer when bytecode needs to be reexecuted
90
91  const TypeOopPtr* sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr = false);
92
93 public:
94  LibraryCallKit(JVMState* jvms, LibraryIntrinsic* intrinsic)
95    : GraphKit(jvms),
96      _intrinsic(intrinsic),
97      _result(NULL)
98  {
99    // Check if this is a root compile.  In that case we don't have a caller.
100    if (!jvms->has_method()) {
101      _reexecute_sp = sp();
102    } else {
103      // Find out how many arguments the interpreter needs when deoptimizing
104      // and save the stack pointer value so it can used by uncommon_trap.
105      // We find the argument count by looking at the declared signature.
106      bool ignored_will_link;
107      ciSignature* declared_signature = NULL;
108      ciMethod* ignored_callee = caller()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
109      const int nargs = declared_signature->arg_size_for_bc(caller()->java_code_at_bci(bci()));
110      _reexecute_sp = sp() + nargs;  // "push" arguments back on stack
111    }
112  }
113
114  virtual LibraryCallKit* is_LibraryCallKit() const { return (LibraryCallKit*)this; }
115
116  ciMethod*         caller()    const    { return jvms()->method(); }
117  int               bci()       const    { return jvms()->bci(); }
118  LibraryIntrinsic* intrinsic() const    { return _intrinsic; }
119  vmIntrinsics::ID  intrinsic_id() const { return _intrinsic->intrinsic_id(); }
120  ciMethod*         callee()    const    { return _intrinsic->method(); }
121
122  bool  try_to_inline(int predicate);
123  Node* try_to_predicate(int predicate);
124
125  void push_result() {
126    // Push the result onto the stack.
127    if (!stopped() && result() != NULL) {
128      BasicType bt = result()->bottom_type()->basic_type();
129      push_node(bt, result());
130    }
131  }
132
133 private:
134  void fatal_unexpected_iid(vmIntrinsics::ID iid) {
135    fatal(err_msg_res("unexpected intrinsic %d: %s", iid, vmIntrinsics::name_at(iid)));
136  }
137
138  void  set_result(Node* n) { assert(_result == NULL, "only set once"); _result = n; }
139  void  set_result(RegionNode* region, PhiNode* value);
140  Node*     result() { return _result; }
141
142  virtual int reexecute_sp() { return _reexecute_sp; }
143
144  // Helper functions to inline natives
145  Node* generate_guard(Node* test, RegionNode* region, float true_prob);
146  Node* generate_slow_guard(Node* test, RegionNode* region);
147  Node* generate_fair_guard(Node* test, RegionNode* region);
148  Node* generate_negative_guard(Node* index, RegionNode* region,
149                                // resulting CastII of index:
150                                Node* *pos_index = NULL);
151  Node* generate_limit_guard(Node* offset, Node* subseq_length,
152                             Node* array_length,
153                             RegionNode* region);
154  Node* generate_current_thread(Node* &tls_output);
155  Node* load_mirror_from_klass(Node* klass);
156  Node* load_klass_from_mirror_common(Node* mirror, bool never_see_null,
157                                      RegionNode* region, int null_path,
158                                      int offset);
159  Node* load_klass_from_mirror(Node* mirror, bool never_see_null,
160                               RegionNode* region, int null_path) {
161    int offset = java_lang_Class::klass_offset_in_bytes();
162    return load_klass_from_mirror_common(mirror, never_see_null,
163                                         region, null_path,
164                                         offset);
165  }
166  Node* load_array_klass_from_mirror(Node* mirror, bool never_see_null,
167                                     RegionNode* region, int null_path) {
168    int offset = java_lang_Class::array_klass_offset_in_bytes();
169    return load_klass_from_mirror_common(mirror, never_see_null,
170                                         region, null_path,
171                                         offset);
172  }
173  Node* generate_access_flags_guard(Node* kls,
174                                    int modifier_mask, int modifier_bits,
175                                    RegionNode* region);
176  Node* generate_interface_guard(Node* kls, RegionNode* region);
177  Node* generate_array_guard(Node* kls, RegionNode* region) {
178    return generate_array_guard_common(kls, region, false, false);
179  }
180  Node* generate_non_array_guard(Node* kls, RegionNode* region) {
181    return generate_array_guard_common(kls, region, false, true);
182  }
183  Node* generate_objArray_guard(Node* kls, RegionNode* region) {
184    return generate_array_guard_common(kls, region, true, false);
185  }
186  Node* generate_non_objArray_guard(Node* kls, RegionNode* region) {
187    return generate_array_guard_common(kls, region, true, true);
188  }
189  Node* generate_array_guard_common(Node* kls, RegionNode* region,
190                                    bool obj_array, bool not_array);
191  Node* generate_virtual_guard(Node* obj_klass, RegionNode* slow_region);
192  CallJavaNode* generate_method_call(vmIntrinsics::ID method_id,
193                                     bool is_virtual = false, bool is_static = false);
194  CallJavaNode* generate_method_call_static(vmIntrinsics::ID method_id) {
195    return generate_method_call(method_id, false, true);
196  }
197  CallJavaNode* generate_method_call_virtual(vmIntrinsics::ID method_id) {
198    return generate_method_call(method_id, true, false);
199  }
200  Node * load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString, bool is_exact, bool is_static, ciInstanceKlass * fromKls);
201
202  Node* make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2);
203  Node* make_string_method_node(int opcode, Node* str1, Node* str2);
204  bool inline_string_compareTo();
205  bool inline_string_indexOf();
206  Node* string_indexOf(Node* string_object, ciTypeArray* target_array, jint offset, jint cache_i, jint md2_i);
207  bool inline_string_equals();
208  Node* round_double_node(Node* n);
209  bool runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName);
210  bool inline_math_native(vmIntrinsics::ID id);
211  bool inline_trig(vmIntrinsics::ID id);
212  bool inline_math(vmIntrinsics::ID id);
213  template <typename OverflowOp>
214  bool inline_math_overflow(Node* arg1, Node* arg2);
215  void inline_math_mathExact(Node* math, Node* test);
216  bool inline_math_addExactI(bool is_increment);
217  bool inline_math_addExactL(bool is_increment);
218  bool inline_math_multiplyExactI();
219  bool inline_math_multiplyExactL();
220  bool inline_math_negateExactI();
221  bool inline_math_negateExactL();
222  bool inline_math_subtractExactI(bool is_decrement);
223  bool inline_math_subtractExactL(bool is_decrement);
224  bool inline_exp();
225  bool inline_pow();
226  Node* finish_pow_exp(Node* result, Node* x, Node* y, const TypeFunc* call_type, address funcAddr, const char* funcName);
227  bool inline_min_max(vmIntrinsics::ID id);
228  bool inline_notify(vmIntrinsics::ID id);
229  Node* generate_min_max(vmIntrinsics::ID id, Node* x, Node* y);
230  // This returns Type::AnyPtr, RawPtr, or OopPtr.
231  int classify_unsafe_addr(Node* &base, Node* &offset);
232  Node* make_unsafe_address(Node* base, Node* offset);
233  // Helper for inline_unsafe_access.
234  // Generates the guards that check whether the result of
235  // Unsafe.getObject should be recorded in an SATB log buffer.
236  void insert_pre_barrier(Node* base_oop, Node* offset, Node* pre_val, bool need_mem_bar);
237  bool inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile);
238  static bool klass_needs_init_guard(Node* kls);
239  bool inline_unsafe_allocate();
240  bool inline_unsafe_copyMemory();
241  bool inline_native_currentThread();
242#ifdef TRACE_HAVE_INTRINSICS
243  bool inline_native_classID();
244  bool inline_native_threadID();
245#endif
246  bool inline_native_time_funcs(address method, const char* funcName);
247  bool inline_native_isInterrupted();
248  bool inline_native_Class_query(vmIntrinsics::ID id);
249  bool inline_native_subtype_check();
250
251  bool inline_native_newArray();
252  bool inline_native_getLength();
253  bool inline_array_copyOf(bool is_copyOfRange);
254  bool inline_array_equals();
255  void copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark);
256  bool inline_native_clone(bool is_virtual);
257  bool inline_native_Reflection_getCallerClass();
258  // Helper function for inlining native object hash method
259  bool inline_native_hashcode(bool is_virtual, bool is_static);
260  bool inline_native_getClass();
261
262  // Helper functions for inlining arraycopy
263  bool inline_arraycopy();
264  AllocateArrayNode* tightly_coupled_allocation(Node* ptr,
265                                                RegionNode* slow_region);
266  JVMState* arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp);
267  void arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms, int saved_reexecute_sp);
268
269  typedef enum { LS_xadd, LS_xchg, LS_cmpxchg } LoadStoreKind;
270  bool inline_unsafe_load_store(BasicType type,  LoadStoreKind kind);
271  bool inline_unsafe_ordered_store(BasicType type);
272  bool inline_unsafe_fence(vmIntrinsics::ID id);
273  bool inline_fp_conversions(vmIntrinsics::ID id);
274  bool inline_number_methods(vmIntrinsics::ID id);
275  bool inline_reference_get();
276  bool inline_Class_cast();
277  bool inline_aescrypt_Block(vmIntrinsics::ID id);
278  bool inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id);
279  Node* inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting);
280  Node* get_key_start_from_aescrypt_object(Node* aescrypt_object);
281  Node* get_original_key_start_from_aescrypt_object(Node* aescrypt_object);
282  bool inline_ghash_processBlocks();
283  bool inline_sha_implCompress(vmIntrinsics::ID id);
284  bool inline_digestBase_implCompressMB(int predicate);
285  bool inline_sha_implCompressMB(Node* digestBaseObj, ciInstanceKlass* instklass_SHA,
286                                 bool long_state, address stubAddr, const char *stubName,
287                                 Node* src_start, Node* ofs, Node* limit);
288  Node* get_state_from_sha_object(Node *sha_object);
289  Node* get_state_from_sha5_object(Node *sha_object);
290  Node* inline_digestBase_implCompressMB_predicate(int predicate);
291  bool inline_encodeISOArray();
292  bool inline_updateCRC32();
293  bool inline_updateBytesCRC32();
294  bool inline_updateByteBufferCRC32();
295  Node* get_table_from_crc32c_class(ciInstanceKlass *crc32c_class);
296  bool inline_updateBytesCRC32C();
297  bool inline_updateDirectByteBufferCRC32C();
298  bool inline_multiplyToLen();
299  bool inline_squareToLen();
300  bool inline_mulAdd();
301  bool inline_montgomeryMultiply();
302  bool inline_montgomerySquare();
303
304  bool inline_profileBoolean();
305  bool inline_isCompileConstant();
306};
307
308
309//---------------------------make_vm_intrinsic----------------------------
310CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
311  vmIntrinsics::ID id = m->intrinsic_id();
312  assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
313
314  ccstr disable_intr = NULL;
315
316  if ((DisableIntrinsic[0] != '\0'
317       && strstr(DisableIntrinsic, vmIntrinsics::name_at(id)) != NULL) ||
318      (method_has_option_value("DisableIntrinsic", disable_intr)
319       && strstr(disable_intr, vmIntrinsics::name_at(id)) != NULL)) {
320    // disabled by a user request on the command line:
321    // example: -XX:DisableIntrinsic=_hashCode,_getClass
322    return NULL;
323  }
324
325  if (!m->is_loaded()) {
326    // do not attempt to inline unloaded methods
327    return NULL;
328  }
329
330  // Only a few intrinsics implement a virtual dispatch.
331  // They are expensive calls which are also frequently overridden.
332  if (is_virtual) {
333    switch (id) {
334    case vmIntrinsics::_hashCode:
335    case vmIntrinsics::_clone:
336      // OK, Object.hashCode and Object.clone intrinsics come in both flavors
337      break;
338    default:
339      return NULL;
340    }
341  }
342
343  // -XX:-InlineNatives disables nearly all intrinsics:
344  if (!InlineNatives) {
345    switch (id) {
346    case vmIntrinsics::_indexOf:
347    case vmIntrinsics::_compareTo:
348    case vmIntrinsics::_equals:
349    case vmIntrinsics::_equalsC:
350    case vmIntrinsics::_getAndAddInt:
351    case vmIntrinsics::_getAndAddLong:
352    case vmIntrinsics::_getAndSetInt:
353    case vmIntrinsics::_getAndSetLong:
354    case vmIntrinsics::_getAndSetObject:
355    case vmIntrinsics::_loadFence:
356    case vmIntrinsics::_storeFence:
357    case vmIntrinsics::_fullFence:
358      break;  // InlineNatives does not control String.compareTo
359    case vmIntrinsics::_Reference_get:
360      break;  // InlineNatives does not control Reference.get
361    default:
362      return NULL;
363    }
364  }
365
366  int predicates = 0;
367  bool does_virtual_dispatch = false;
368
369  switch (id) {
370  case vmIntrinsics::_compareTo:
371    if (!SpecialStringCompareTo)  return NULL;
372    if (!Matcher::match_rule_supported(Op_StrComp))  return NULL;
373    break;
374  case vmIntrinsics::_indexOf:
375    if (!SpecialStringIndexOf)  return NULL;
376    break;
377  case vmIntrinsics::_equals:
378    if (!SpecialStringEquals)  return NULL;
379    if (!Matcher::match_rule_supported(Op_StrEquals))  return NULL;
380    break;
381  case vmIntrinsics::_equalsC:
382    if (!SpecialArraysEquals)  return NULL;
383    if (!Matcher::match_rule_supported(Op_AryEq))  return NULL;
384    break;
385  case vmIntrinsics::_arraycopy:
386    if (!InlineArrayCopy)  return NULL;
387    break;
388  case vmIntrinsics::_copyMemory:
389    if (StubRoutines::unsafe_arraycopy() == NULL)  return NULL;
390    if (!InlineArrayCopy)  return NULL;
391    break;
392  case vmIntrinsics::_hashCode:
393    if (!InlineObjectHash)  return NULL;
394    does_virtual_dispatch = true;
395    break;
396  case vmIntrinsics::_clone:
397    does_virtual_dispatch = true;
398  case vmIntrinsics::_copyOf:
399  case vmIntrinsics::_copyOfRange:
400    if (!InlineObjectCopy)  return NULL;
401    // These also use the arraycopy intrinsic mechanism:
402    if (!InlineArrayCopy)  return NULL;
403    break;
404  case vmIntrinsics::_encodeISOArray:
405    if (!SpecialEncodeISOArray)  return NULL;
406    if (!Matcher::match_rule_supported(Op_EncodeISOArray))  return NULL;
407    break;
408  case vmIntrinsics::_checkIndex:
409    // We do not intrinsify this.  The optimizer does fine with it.
410    return NULL;
411
412  case vmIntrinsics::_getCallerClass:
413    if (!InlineReflectionGetCallerClass)  return NULL;
414    if (SystemDictionary::reflect_CallerSensitive_klass() == NULL)  return NULL;
415    break;
416
417  case vmIntrinsics::_bitCount_i:
418    if (!Matcher::match_rule_supported(Op_PopCountI)) return NULL;
419    break;
420
421  case vmIntrinsics::_bitCount_l:
422    if (!Matcher::match_rule_supported(Op_PopCountL)) return NULL;
423    break;
424
425  case vmIntrinsics::_numberOfLeadingZeros_i:
426    if (!Matcher::match_rule_supported(Op_CountLeadingZerosI)) return NULL;
427    break;
428
429  case vmIntrinsics::_numberOfLeadingZeros_l:
430    if (!Matcher::match_rule_supported(Op_CountLeadingZerosL)) return NULL;
431    break;
432
433  case vmIntrinsics::_numberOfTrailingZeros_i:
434    if (!Matcher::match_rule_supported(Op_CountTrailingZerosI)) return NULL;
435    break;
436
437  case vmIntrinsics::_numberOfTrailingZeros_l:
438    if (!Matcher::match_rule_supported(Op_CountTrailingZerosL)) return NULL;
439    break;
440
441  case vmIntrinsics::_reverseBytes_c:
442    if (!Matcher::match_rule_supported(Op_ReverseBytesUS)) return NULL;
443    break;
444  case vmIntrinsics::_reverseBytes_s:
445    if (!Matcher::match_rule_supported(Op_ReverseBytesS))  return NULL;
446    break;
447  case vmIntrinsics::_reverseBytes_i:
448    if (!Matcher::match_rule_supported(Op_ReverseBytesI))  return NULL;
449    break;
450  case vmIntrinsics::_reverseBytes_l:
451    if (!Matcher::match_rule_supported(Op_ReverseBytesL))  return NULL;
452    break;
453
454  case vmIntrinsics::_Reference_get:
455    // Use the intrinsic version of Reference.get() so that the value in
456    // the referent field can be registered by the G1 pre-barrier code.
457    // Also add memory barrier to prevent commoning reads from this field
458    // across safepoint since GC can change it value.
459    break;
460
461  case vmIntrinsics::_compareAndSwapObject:
462#ifdef _LP64
463    if (!UseCompressedOops && !Matcher::match_rule_supported(Op_CompareAndSwapP)) return NULL;
464#endif
465    break;
466
467  case vmIntrinsics::_compareAndSwapLong:
468    if (!Matcher::match_rule_supported(Op_CompareAndSwapL)) return NULL;
469    break;
470
471  case vmIntrinsics::_getAndAddInt:
472    if (!Matcher::match_rule_supported(Op_GetAndAddI)) return NULL;
473    break;
474
475  case vmIntrinsics::_getAndAddLong:
476    if (!Matcher::match_rule_supported(Op_GetAndAddL)) return NULL;
477    break;
478
479  case vmIntrinsics::_getAndSetInt:
480    if (!Matcher::match_rule_supported(Op_GetAndSetI)) return NULL;
481    break;
482
483  case vmIntrinsics::_getAndSetLong:
484    if (!Matcher::match_rule_supported(Op_GetAndSetL)) return NULL;
485    break;
486
487  case vmIntrinsics::_getAndSetObject:
488#ifdef _LP64
489    if (!UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetP)) return NULL;
490    if (UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetN)) return NULL;
491    break;
492#else
493    if (!Matcher::match_rule_supported(Op_GetAndSetP)) return NULL;
494    break;
495#endif
496
497  case vmIntrinsics::_aescrypt_encryptBlock:
498  case vmIntrinsics::_aescrypt_decryptBlock:
499    if (!UseAESIntrinsics) return NULL;
500    break;
501
502  case vmIntrinsics::_multiplyToLen:
503    if (!UseMultiplyToLenIntrinsic) return NULL;
504    break;
505
506  case vmIntrinsics::_squareToLen:
507    if (!UseSquareToLenIntrinsic) return NULL;
508    break;
509
510  case vmIntrinsics::_mulAdd:
511    if (!UseMulAddIntrinsic) return NULL;
512    break;
513
514  case vmIntrinsics::_montgomeryMultiply:
515     if (!UseMontgomeryMultiplyIntrinsic) return NULL;
516    break;
517  case vmIntrinsics::_montgomerySquare:
518     if (!UseMontgomerySquareIntrinsic) return NULL;
519    break;
520
521  case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
522  case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
523    if (!UseAESIntrinsics) return NULL;
524    // these two require the predicated logic
525    predicates = 1;
526    break;
527
528  case vmIntrinsics::_sha_implCompress:
529    if (!UseSHA1Intrinsics) return NULL;
530    break;
531
532  case vmIntrinsics::_sha2_implCompress:
533    if (!UseSHA256Intrinsics) return NULL;
534    break;
535
536  case vmIntrinsics::_sha5_implCompress:
537    if (!UseSHA512Intrinsics) return NULL;
538    break;
539
540  case vmIntrinsics::_digestBase_implCompressMB:
541    if (!(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics)) return NULL;
542    predicates = 3;
543    break;
544
545  case vmIntrinsics::_ghash_processBlocks:
546    if (!UseGHASHIntrinsics) return NULL;
547    break;
548
549  case vmIntrinsics::_updateCRC32:
550  case vmIntrinsics::_updateBytesCRC32:
551  case vmIntrinsics::_updateByteBufferCRC32:
552    if (!UseCRC32Intrinsics) return NULL;
553    break;
554
555  case vmIntrinsics::_updateBytesCRC32C:
556  case vmIntrinsics::_updateDirectByteBufferCRC32C:
557    if (!UseCRC32CIntrinsics) return NULL;
558    break;
559
560  case vmIntrinsics::_incrementExactI:
561  case vmIntrinsics::_addExactI:
562    if (!Matcher::match_rule_supported(Op_OverflowAddI) || !UseMathExactIntrinsics) return NULL;
563    break;
564  case vmIntrinsics::_incrementExactL:
565  case vmIntrinsics::_addExactL:
566    if (!Matcher::match_rule_supported(Op_OverflowAddL) || !UseMathExactIntrinsics) return NULL;
567    break;
568  case vmIntrinsics::_decrementExactI:
569  case vmIntrinsics::_subtractExactI:
570    if (!Matcher::match_rule_supported(Op_OverflowSubI) || !UseMathExactIntrinsics) return NULL;
571    break;
572  case vmIntrinsics::_decrementExactL:
573  case vmIntrinsics::_subtractExactL:
574    if (!Matcher::match_rule_supported(Op_OverflowSubL) || !UseMathExactIntrinsics) return NULL;
575    break;
576  case vmIntrinsics::_negateExactI:
577    if (!Matcher::match_rule_supported(Op_OverflowSubI) || !UseMathExactIntrinsics) return NULL;
578    break;
579  case vmIntrinsics::_negateExactL:
580    if (!Matcher::match_rule_supported(Op_OverflowSubL) || !UseMathExactIntrinsics) return NULL;
581    break;
582  case vmIntrinsics::_multiplyExactI:
583    if (!Matcher::match_rule_supported(Op_OverflowMulI) || !UseMathExactIntrinsics) return NULL;
584    break;
585  case vmIntrinsics::_multiplyExactL:
586    if (!Matcher::match_rule_supported(Op_OverflowMulL) || !UseMathExactIntrinsics) return NULL;
587    break;
588
589  case vmIntrinsics::_getShortUnaligned:
590  case vmIntrinsics::_getCharUnaligned:
591  case vmIntrinsics::_getIntUnaligned:
592  case vmIntrinsics::_getLongUnaligned:
593  case vmIntrinsics::_putShortUnaligned:
594  case vmIntrinsics::_putCharUnaligned:
595  case vmIntrinsics::_putIntUnaligned:
596  case vmIntrinsics::_putLongUnaligned:
597    if (!UseUnalignedAccesses) return NULL;
598    break;
599
600 default:
601    assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
602    assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
603    break;
604  }
605
606  // -XX:-InlineClassNatives disables natives from the Class class.
607  // The flag applies to all reflective calls, notably Array.newArray
608  // (visible to Java programmers as Array.newInstance).
609  if (m->holder()->name() == ciSymbol::java_lang_Class() ||
610      m->holder()->name() == ciSymbol::java_lang_reflect_Array()) {
611    if (!InlineClassNatives)  return NULL;
612  }
613
614  // -XX:-InlineThreadNatives disables natives from the Thread class.
615  if (m->holder()->name() == ciSymbol::java_lang_Thread()) {
616    if (!InlineThreadNatives)  return NULL;
617  }
618
619  // -XX:-InlineMathNatives disables natives from the Math,Float and Double classes.
620  if (m->holder()->name() == ciSymbol::java_lang_Math() ||
621      m->holder()->name() == ciSymbol::java_lang_Float() ||
622      m->holder()->name() == ciSymbol::java_lang_Double()) {
623    if (!InlineMathNatives)  return NULL;
624  }
625
626  // -XX:-InlineUnsafeOps disables natives from the Unsafe class.
627  if (m->holder()->name() == ciSymbol::sun_misc_Unsafe()) {
628    if (!InlineUnsafeOps)  return NULL;
629  }
630
631  return new LibraryIntrinsic(m, is_virtual, predicates, does_virtual_dispatch, (vmIntrinsics::ID) id);
632}
633
634//----------------------register_library_intrinsics-----------------------
635// Initialize this file's data structures, for each Compile instance.
636void Compile::register_library_intrinsics() {
637  // Nothing to do here.
638}
639
640JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
641  LibraryCallKit kit(jvms, this);
642  Compile* C = kit.C;
643  int nodes = C->unique();
644#ifndef PRODUCT
645  if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
646    char buf[1000];
647    const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
648    tty->print_cr("Intrinsic %s", str);
649  }
650#endif
651  ciMethod* callee = kit.callee();
652  const int bci    = kit.bci();
653
654  // Try to inline the intrinsic.
655  if ((CheckIntrinsics ? callee->intrinsic_candidate() : true) &&
656      kit.try_to_inline(_last_predicate)) {
657    if (C->print_intrinsics() || C->print_inlining()) {
658      C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual)" : "(intrinsic)");
659    }
660    C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
661    if (C->log()) {
662      C->log()->elem("intrinsic id='%s'%s nodes='%d'",
663                     vmIntrinsics::name_at(intrinsic_id()),
664                     (is_virtual() ? " virtual='1'" : ""),
665                     C->unique() - nodes);
666    }
667    // Push the result from the inlined method onto the stack.
668    kit.push_result();
669    C->print_inlining_update(this);
670    return kit.transfer_exceptions_into_jvms();
671  }
672
673  // The intrinsic bailed out
674  if (C->print_intrinsics() || C->print_inlining()) {
675    if (jvms->has_method()) {
676      // Not a root compile.
677      const char* msg;
678      if (callee->intrinsic_candidate()) {
679        msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
680      } else {
681        msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
682                           : "failed to inline (intrinsic), method not annotated";
683      }
684      C->print_inlining(callee, jvms->depth() - 1, bci, msg);
685    } else {
686      // Root compile
687      tty->print("Did not generate intrinsic %s%s at bci:%d in",
688               vmIntrinsics::name_at(intrinsic_id()),
689               (is_virtual() ? " (virtual)" : ""), bci);
690    }
691  }
692  C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
693  C->print_inlining_update(this);
694  return NULL;
695}
696
697Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
698  LibraryCallKit kit(jvms, this);
699  Compile* C = kit.C;
700  int nodes = C->unique();
701  _last_predicate = predicate;
702#ifndef PRODUCT
703  assert(is_predicated() && predicate < predicates_count(), "sanity");
704  if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
705    char buf[1000];
706    const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
707    tty->print_cr("Predicate for intrinsic %s", str);
708  }
709#endif
710  ciMethod* callee = kit.callee();
711  const int bci    = kit.bci();
712
713  Node* slow_ctl = kit.try_to_predicate(predicate);
714  if (!kit.failing()) {
715    if (C->print_intrinsics() || C->print_inlining()) {
716      C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual, predicate)" : "(intrinsic, predicate)");
717    }
718    C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
719    if (C->log()) {
720      C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
721                     vmIntrinsics::name_at(intrinsic_id()),
722                     (is_virtual() ? " virtual='1'" : ""),
723                     C->unique() - nodes);
724    }
725    return slow_ctl; // Could be NULL if the check folds.
726  }
727
728  // The intrinsic bailed out
729  if (C->print_intrinsics() || C->print_inlining()) {
730    if (jvms->has_method()) {
731      // Not a root compile.
732      const char* msg = "failed to generate predicate for intrinsic";
733      C->print_inlining(kit.callee(), jvms->depth() - 1, bci, msg);
734    } else {
735      // Root compile
736      C->print_inlining_stream()->print("Did not generate predicate for intrinsic %s%s at bci:%d in",
737                                        vmIntrinsics::name_at(intrinsic_id()),
738                                        (is_virtual() ? " (virtual)" : ""), bci);
739    }
740  }
741  C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
742  return NULL;
743}
744
745bool LibraryCallKit::try_to_inline(int predicate) {
746  // Handle symbolic names for otherwise undistinguished boolean switches:
747  const bool is_store       = true;
748  const bool is_native_ptr  = true;
749  const bool is_static      = true;
750  const bool is_volatile    = true;
751
752  if (!jvms()->has_method()) {
753    // Root JVMState has a null method.
754    assert(map()->memory()->Opcode() == Op_Parm, "");
755    // Insert the memory aliasing node
756    set_all_memory(reset_memory());
757  }
758  assert(merged_memory(), "");
759
760
761  switch (intrinsic_id()) {
762  case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
763  case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
764  case vmIntrinsics::_getClass:                 return inline_native_getClass();
765
766  case vmIntrinsics::_dsin:
767  case vmIntrinsics::_dcos:
768  case vmIntrinsics::_dtan:
769  case vmIntrinsics::_dabs:
770  case vmIntrinsics::_datan2:
771  case vmIntrinsics::_dsqrt:
772  case vmIntrinsics::_dexp:
773  case vmIntrinsics::_dlog:
774  case vmIntrinsics::_dlog10:
775  case vmIntrinsics::_dpow:                     return inline_math_native(intrinsic_id());
776
777  case vmIntrinsics::_min:
778  case vmIntrinsics::_max:                      return inline_min_max(intrinsic_id());
779
780  case vmIntrinsics::_notify:
781  case vmIntrinsics::_notifyAll:
782    if (InlineNotify) {
783      return inline_notify(intrinsic_id());
784    }
785    return false;
786
787  case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
788  case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
789  case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
790  case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
791  case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
792  case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
793  case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
794  case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
795  case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
796  case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
797  case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
798  case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
799
800  case vmIntrinsics::_arraycopy:                return inline_arraycopy();
801
802  case vmIntrinsics::_compareTo:                return inline_string_compareTo();
803  case vmIntrinsics::_indexOf:                  return inline_string_indexOf();
804  case vmIntrinsics::_equals:                   return inline_string_equals();
805
806  case vmIntrinsics::_getObject:                return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,  !is_volatile);
807  case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, !is_volatile);
808  case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,    !is_volatile);
809  case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,   !is_volatile);
810  case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,    !is_volatile);
811  case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,     !is_volatile);
812  case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,    !is_volatile);
813  case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,   !is_volatile);
814  case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,  !is_volatile);
815
816  case vmIntrinsics::_putObject:                return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,  !is_volatile);
817  case vmIntrinsics::_putBoolean:               return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN, !is_volatile);
818  case vmIntrinsics::_putByte:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,    !is_volatile);
819  case vmIntrinsics::_putShort:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,   !is_volatile);
820  case vmIntrinsics::_putChar:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,    !is_volatile);
821  case vmIntrinsics::_putInt:                   return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,     !is_volatile);
822  case vmIntrinsics::_putLong:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,    !is_volatile);
823  case vmIntrinsics::_putFloat:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,   !is_volatile);
824  case vmIntrinsics::_putDouble:                return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,  !is_volatile);
825
826  case vmIntrinsics::_getByte_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_BYTE,    !is_volatile);
827  case vmIntrinsics::_getShort_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_SHORT,   !is_volatile);
828  case vmIntrinsics::_getChar_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_CHAR,    !is_volatile);
829  case vmIntrinsics::_getInt_raw:               return inline_unsafe_access( is_native_ptr, !is_store, T_INT,     !is_volatile);
830  case vmIntrinsics::_getLong_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_LONG,    !is_volatile);
831  case vmIntrinsics::_getFloat_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_FLOAT,   !is_volatile);
832  case vmIntrinsics::_getDouble_raw:            return inline_unsafe_access( is_native_ptr, !is_store, T_DOUBLE,  !is_volatile);
833  case vmIntrinsics::_getAddress_raw:           return inline_unsafe_access( is_native_ptr, !is_store, T_ADDRESS, !is_volatile);
834
835  case vmIntrinsics::_putByte_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_BYTE,    !is_volatile);
836  case vmIntrinsics::_putShort_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_SHORT,   !is_volatile);
837  case vmIntrinsics::_putChar_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_CHAR,    !is_volatile);
838  case vmIntrinsics::_putInt_raw:               return inline_unsafe_access( is_native_ptr,  is_store, T_INT,     !is_volatile);
839  case vmIntrinsics::_putLong_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_LONG,    !is_volatile);
840  case vmIntrinsics::_putFloat_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_FLOAT,   !is_volatile);
841  case vmIntrinsics::_putDouble_raw:            return inline_unsafe_access( is_native_ptr,  is_store, T_DOUBLE,  !is_volatile);
842  case vmIntrinsics::_putAddress_raw:           return inline_unsafe_access( is_native_ptr,  is_store, T_ADDRESS, !is_volatile);
843
844  case vmIntrinsics::_getObjectVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,   is_volatile);
845  case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN,  is_volatile);
846  case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,     is_volatile);
847  case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,    is_volatile);
848  case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,     is_volatile);
849  case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,      is_volatile);
850  case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,     is_volatile);
851  case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,    is_volatile);
852  case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,   is_volatile);
853
854  case vmIntrinsics::_putObjectVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,   is_volatile);
855  case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN,  is_volatile);
856  case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,     is_volatile);
857  case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,    is_volatile);
858  case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,     is_volatile);
859  case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,      is_volatile);
860  case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,     is_volatile);
861  case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,    is_volatile);
862  case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,   is_volatile);
863
864  case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,   !is_volatile);
865  case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,    !is_volatile);
866  case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,     !is_volatile);
867  case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,    !is_volatile);
868
869  case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,   !is_volatile);
870  case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,    !is_volatile);
871  case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,     !is_volatile);
872  case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,    !is_volatile);
873
874  case vmIntrinsics::_compareAndSwapObject:     return inline_unsafe_load_store(T_OBJECT, LS_cmpxchg);
875  case vmIntrinsics::_compareAndSwapInt:        return inline_unsafe_load_store(T_INT,    LS_cmpxchg);
876  case vmIntrinsics::_compareAndSwapLong:       return inline_unsafe_load_store(T_LONG,   LS_cmpxchg);
877
878  case vmIntrinsics::_putOrderedObject:         return inline_unsafe_ordered_store(T_OBJECT);
879  case vmIntrinsics::_putOrderedInt:            return inline_unsafe_ordered_store(T_INT);
880  case vmIntrinsics::_putOrderedLong:           return inline_unsafe_ordered_store(T_LONG);
881
882  case vmIntrinsics::_getAndAddInt:             return inline_unsafe_load_store(T_INT,    LS_xadd);
883  case vmIntrinsics::_getAndAddLong:            return inline_unsafe_load_store(T_LONG,   LS_xadd);
884  case vmIntrinsics::_getAndSetInt:             return inline_unsafe_load_store(T_INT,    LS_xchg);
885  case vmIntrinsics::_getAndSetLong:            return inline_unsafe_load_store(T_LONG,   LS_xchg);
886  case vmIntrinsics::_getAndSetObject:          return inline_unsafe_load_store(T_OBJECT, LS_xchg);
887
888  case vmIntrinsics::_loadFence:
889  case vmIntrinsics::_storeFence:
890  case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
891
892  case vmIntrinsics::_currentThread:            return inline_native_currentThread();
893  case vmIntrinsics::_isInterrupted:            return inline_native_isInterrupted();
894
895#ifdef TRACE_HAVE_INTRINSICS
896  case vmIntrinsics::_classID:                  return inline_native_classID();
897  case vmIntrinsics::_threadID:                 return inline_native_threadID();
898  case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, TRACE_TIME_METHOD), "counterTime");
899#endif
900  case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
901  case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
902  case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
903  case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
904  case vmIntrinsics::_newArray:                 return inline_native_newArray();
905  case vmIntrinsics::_getLength:                return inline_native_getLength();
906  case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
907  case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
908  case vmIntrinsics::_equalsC:                  return inline_array_equals();
909  case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
910
911  case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
912
913  case vmIntrinsics::_isInstance:
914  case vmIntrinsics::_getModifiers:
915  case vmIntrinsics::_isInterface:
916  case vmIntrinsics::_isArray:
917  case vmIntrinsics::_isPrimitive:
918  case vmIntrinsics::_getSuperclass:
919  case vmIntrinsics::_getClassAccessFlags:      return inline_native_Class_query(intrinsic_id());
920
921  case vmIntrinsics::_floatToRawIntBits:
922  case vmIntrinsics::_floatToIntBits:
923  case vmIntrinsics::_intBitsToFloat:
924  case vmIntrinsics::_doubleToRawLongBits:
925  case vmIntrinsics::_doubleToLongBits:
926  case vmIntrinsics::_longBitsToDouble:         return inline_fp_conversions(intrinsic_id());
927
928  case vmIntrinsics::_numberOfLeadingZeros_i:
929  case vmIntrinsics::_numberOfLeadingZeros_l:
930  case vmIntrinsics::_numberOfTrailingZeros_i:
931  case vmIntrinsics::_numberOfTrailingZeros_l:
932  case vmIntrinsics::_bitCount_i:
933  case vmIntrinsics::_bitCount_l:
934  case vmIntrinsics::_reverseBytes_i:
935  case vmIntrinsics::_reverseBytes_l:
936  case vmIntrinsics::_reverseBytes_s:
937  case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
938
939  case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
940
941  case vmIntrinsics::_Reference_get:            return inline_reference_get();
942
943  case vmIntrinsics::_Class_cast:               return inline_Class_cast();
944
945  case vmIntrinsics::_aescrypt_encryptBlock:
946  case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
947
948  case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
949  case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
950    return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
951
952  case vmIntrinsics::_sha_implCompress:
953  case vmIntrinsics::_sha2_implCompress:
954  case vmIntrinsics::_sha5_implCompress:
955    return inline_sha_implCompress(intrinsic_id());
956
957  case vmIntrinsics::_digestBase_implCompressMB:
958    return inline_digestBase_implCompressMB(predicate);
959
960  case vmIntrinsics::_multiplyToLen:
961    return inline_multiplyToLen();
962
963  case vmIntrinsics::_squareToLen:
964    return inline_squareToLen();
965
966  case vmIntrinsics::_mulAdd:
967    return inline_mulAdd();
968
969  case vmIntrinsics::_montgomeryMultiply:
970    return inline_montgomeryMultiply();
971  case vmIntrinsics::_montgomerySquare:
972    return inline_montgomerySquare();
973
974  case vmIntrinsics::_ghash_processBlocks:
975    return inline_ghash_processBlocks();
976
977  case vmIntrinsics::_encodeISOArray:
978    return inline_encodeISOArray();
979
980  case vmIntrinsics::_updateCRC32:
981    return inline_updateCRC32();
982  case vmIntrinsics::_updateBytesCRC32:
983    return inline_updateBytesCRC32();
984  case vmIntrinsics::_updateByteBufferCRC32:
985    return inline_updateByteBufferCRC32();
986
987  case vmIntrinsics::_updateBytesCRC32C:
988    return inline_updateBytesCRC32C();
989  case vmIntrinsics::_updateDirectByteBufferCRC32C:
990    return inline_updateDirectByteBufferCRC32C();
991
992  case vmIntrinsics::_profileBoolean:
993    return inline_profileBoolean();
994  case vmIntrinsics::_isCompileConstant:
995    return inline_isCompileConstant();
996
997  default:
998    // If you get here, it may be that someone has added a new intrinsic
999    // to the list in vmSymbols.hpp without implementing it here.
1000#ifndef PRODUCT
1001    if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
1002      tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
1003                    vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
1004    }
1005#endif
1006    return false;
1007  }
1008}
1009
1010Node* LibraryCallKit::try_to_predicate(int predicate) {
1011  if (!jvms()->has_method()) {
1012    // Root JVMState has a null method.
1013    assert(map()->memory()->Opcode() == Op_Parm, "");
1014    // Insert the memory aliasing node
1015    set_all_memory(reset_memory());
1016  }
1017  assert(merged_memory(), "");
1018
1019  switch (intrinsic_id()) {
1020  case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
1021    return inline_cipherBlockChaining_AESCrypt_predicate(false);
1022  case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
1023    return inline_cipherBlockChaining_AESCrypt_predicate(true);
1024  case vmIntrinsics::_digestBase_implCompressMB:
1025    return inline_digestBase_implCompressMB_predicate(predicate);
1026
1027  default:
1028    // If you get here, it may be that someone has added a new intrinsic
1029    // to the list in vmSymbols.hpp without implementing it here.
1030#ifndef PRODUCT
1031    if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
1032      tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
1033                    vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
1034    }
1035#endif
1036    Node* slow_ctl = control();
1037    set_control(top()); // No fast path instrinsic
1038    return slow_ctl;
1039  }
1040}
1041
1042//------------------------------set_result-------------------------------
1043// Helper function for finishing intrinsics.
1044void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
1045  record_for_igvn(region);
1046  set_control(_gvn.transform(region));
1047  set_result( _gvn.transform(value));
1048  assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
1049}
1050
1051//------------------------------generate_guard---------------------------
1052// Helper function for generating guarded fast-slow graph structures.
1053// The given 'test', if true, guards a slow path.  If the test fails
1054// then a fast path can be taken.  (We generally hope it fails.)
1055// In all cases, GraphKit::control() is updated to the fast path.
1056// The returned value represents the control for the slow path.
1057// The return value is never 'top'; it is either a valid control
1058// or NULL if it is obvious that the slow path can never be taken.
1059// Also, if region and the slow control are not NULL, the slow edge
1060// is appended to the region.
1061Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
1062  if (stopped()) {
1063    // Already short circuited.
1064    return NULL;
1065  }
1066
1067  // Build an if node and its projections.
1068  // If test is true we take the slow path, which we assume is uncommon.
1069  if (_gvn.type(test) == TypeInt::ZERO) {
1070    // The slow branch is never taken.  No need to build this guard.
1071    return NULL;
1072  }
1073
1074  IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
1075
1076  Node* if_slow = _gvn.transform(new IfTrueNode(iff));
1077  if (if_slow == top()) {
1078    // The slow branch is never taken.  No need to build this guard.
1079    return NULL;
1080  }
1081
1082  if (region != NULL)
1083    region->add_req(if_slow);
1084
1085  Node* if_fast = _gvn.transform(new IfFalseNode(iff));
1086  set_control(if_fast);
1087
1088  return if_slow;
1089}
1090
1091inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
1092  return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
1093}
1094inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
1095  return generate_guard(test, region, PROB_FAIR);
1096}
1097
1098inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
1099                                                     Node* *pos_index) {
1100  if (stopped())
1101    return NULL;                // already stopped
1102  if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
1103    return NULL;                // index is already adequately typed
1104  Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
1105  Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
1106  Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
1107  if (is_neg != NULL && pos_index != NULL) {
1108    // Emulate effect of Parse::adjust_map_after_if.
1109    Node* ccast = new CastIINode(index, TypeInt::POS);
1110    ccast->set_req(0, control());
1111    (*pos_index) = _gvn.transform(ccast);
1112  }
1113  return is_neg;
1114}
1115
1116// Make sure that 'position' is a valid limit index, in [0..length].
1117// There are two equivalent plans for checking this:
1118//   A. (offset + copyLength)  unsigned<=  arrayLength
1119//   B. offset  <=  (arrayLength - copyLength)
1120// We require that all of the values above, except for the sum and
1121// difference, are already known to be non-negative.
1122// Plan A is robust in the face of overflow, if offset and copyLength
1123// are both hugely positive.
1124//
1125// Plan B is less direct and intuitive, but it does not overflow at
1126// all, since the difference of two non-negatives is always
1127// representable.  Whenever Java methods must perform the equivalent
1128// check they generally use Plan B instead of Plan A.
1129// For the moment we use Plan A.
1130inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
1131                                                  Node* subseq_length,
1132                                                  Node* array_length,
1133                                                  RegionNode* region) {
1134  if (stopped())
1135    return NULL;                // already stopped
1136  bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
1137  if (zero_offset && subseq_length->eqv_uncast(array_length))
1138    return NULL;                // common case of whole-array copy
1139  Node* last = subseq_length;
1140  if (!zero_offset)             // last += offset
1141    last = _gvn.transform(new AddINode(last, offset));
1142  Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
1143  Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
1144  Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
1145  return is_over;
1146}
1147
1148
1149//--------------------------generate_current_thread--------------------
1150Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1151  ciKlass*    thread_klass = env()->Thread_klass();
1152  const Type* thread_type  = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1153  Node* thread = _gvn.transform(new ThreadLocalNode());
1154  Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::threadObj_offset()));
1155  Node* threadObj = make_load(NULL, p, thread_type, T_OBJECT, MemNode::unordered);
1156  tls_output = thread;
1157  return threadObj;
1158}
1159
1160
1161//------------------------------make_string_method_node------------------------
1162// Helper method for String intrinsic functions. This version is called
1163// with str1 and str2 pointing to String object nodes.
1164//
1165Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1, Node* str2) {
1166  Node* no_ctrl = NULL;
1167
1168  // Get start addr of string
1169  Node* str1_value   = load_String_value(no_ctrl, str1);
1170  Node* str1_offset  = load_String_offset(no_ctrl, str1);
1171  Node* str1_start   = array_element_address(str1_value, str1_offset, T_CHAR);
1172
1173  // Get length of string 1
1174  Node* str1_len  = load_String_length(no_ctrl, str1);
1175
1176  Node* str2_value   = load_String_value(no_ctrl, str2);
1177  Node* str2_offset  = load_String_offset(no_ctrl, str2);
1178  Node* str2_start   = array_element_address(str2_value, str2_offset, T_CHAR);
1179
1180  Node* str2_len = NULL;
1181  Node* result = NULL;
1182
1183  switch (opcode) {
1184  case Op_StrIndexOf:
1185    // Get length of string 2
1186    str2_len = load_String_length(no_ctrl, str2);
1187
1188    result = new StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),
1189                                str1_start, str1_len, str2_start, str2_len);
1190    break;
1191  case Op_StrComp:
1192    // Get length of string 2
1193    str2_len = load_String_length(no_ctrl, str2);
1194
1195    result = new StrCompNode(control(), memory(TypeAryPtr::CHARS),
1196                             str1_start, str1_len, str2_start, str2_len);
1197    break;
1198  case Op_StrEquals:
1199    result = new StrEqualsNode(control(), memory(TypeAryPtr::CHARS),
1200                               str1_start, str2_start, str1_len);
1201    break;
1202  default:
1203    ShouldNotReachHere();
1204    return NULL;
1205  }
1206
1207  // All these intrinsics have checks.
1208  C->set_has_split_ifs(true); // Has chance for split-if optimization
1209
1210  return _gvn.transform(result);
1211}
1212
1213// Helper method for String intrinsic functions. This version is called
1214// with str1 and str2 pointing to char[] nodes, with cnt1 and cnt2 pointing
1215// to Int nodes containing the lenghts of str1 and str2.
1216//
1217Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2) {
1218  Node* result = NULL;
1219  switch (opcode) {
1220  case Op_StrIndexOf:
1221    result = new StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),
1222                                str1_start, cnt1, str2_start, cnt2);
1223    break;
1224  case Op_StrComp:
1225    result = new StrCompNode(control(), memory(TypeAryPtr::CHARS),
1226                             str1_start, cnt1, str2_start, cnt2);
1227    break;
1228  case Op_StrEquals:
1229    result = new StrEqualsNode(control(), memory(TypeAryPtr::CHARS),
1230                               str1_start, str2_start, cnt1);
1231    break;
1232  default:
1233    ShouldNotReachHere();
1234    return NULL;
1235  }
1236
1237  // All these intrinsics have checks.
1238  C->set_has_split_ifs(true); // Has chance for split-if optimization
1239
1240  return _gvn.transform(result);
1241}
1242
1243//------------------------------inline_string_compareTo------------------------
1244// public int java.lang.String.compareTo(String anotherString);
1245bool LibraryCallKit::inline_string_compareTo() {
1246  Node* receiver = null_check(argument(0));
1247  Node* arg      = null_check(argument(1));
1248  if (stopped()) {
1249    return true;
1250  }
1251  set_result(make_string_method_node(Op_StrComp, receiver, arg));
1252  return true;
1253}
1254
1255//------------------------------inline_string_equals------------------------
1256bool LibraryCallKit::inline_string_equals() {
1257  Node* receiver = null_check_receiver();
1258  // NOTE: Do not null check argument for String.equals() because spec
1259  // allows to specify NULL as argument.
1260  Node* argument = this->argument(1);
1261  if (stopped()) {
1262    return true;
1263  }
1264
1265  // paths (plus control) merge
1266  RegionNode* region = new RegionNode(5);
1267  Node* phi = new PhiNode(region, TypeInt::BOOL);
1268
1269  // does source == target string?
1270  Node* cmp = _gvn.transform(new CmpPNode(receiver, argument));
1271  Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1272
1273  Node* if_eq = generate_slow_guard(bol, NULL);
1274  if (if_eq != NULL) {
1275    // receiver == argument
1276    phi->init_req(2, intcon(1));
1277    region->init_req(2, if_eq);
1278  }
1279
1280  // get String klass for instanceOf
1281  ciInstanceKlass* klass = env()->String_klass();
1282
1283  if (!stopped()) {
1284    Node* inst = gen_instanceof(argument, makecon(TypeKlassPtr::make(klass)));
1285    Node* cmp  = _gvn.transform(new CmpINode(inst, intcon(1)));
1286    Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1287
1288    Node* inst_false = generate_guard(bol, NULL, PROB_MIN);
1289    //instanceOf == true, fallthrough
1290
1291    if (inst_false != NULL) {
1292      phi->init_req(3, intcon(0));
1293      region->init_req(3, inst_false);
1294    }
1295  }
1296
1297  if (!stopped()) {
1298    const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
1299
1300    // Properly cast the argument to String
1301    argument = _gvn.transform(new CheckCastPPNode(control(), argument, string_type));
1302    // This path is taken only when argument's type is String:NotNull.
1303    argument = cast_not_null(argument, false);
1304
1305    Node* no_ctrl = NULL;
1306
1307    // Get start addr of receiver
1308    Node* receiver_val    = load_String_value(no_ctrl, receiver);
1309    Node* receiver_offset = load_String_offset(no_ctrl, receiver);
1310    Node* receiver_start = array_element_address(receiver_val, receiver_offset, T_CHAR);
1311
1312    // Get length of receiver
1313    Node* receiver_cnt  = load_String_length(no_ctrl, receiver);
1314
1315    // Get start addr of argument
1316    Node* argument_val    = load_String_value(no_ctrl, argument);
1317    Node* argument_offset = load_String_offset(no_ctrl, argument);
1318    Node* argument_start = array_element_address(argument_val, argument_offset, T_CHAR);
1319
1320    // Get length of argument
1321    Node* argument_cnt  = load_String_length(no_ctrl, argument);
1322
1323    // Check for receiver count != argument count
1324    Node* cmp = _gvn.transform(new CmpINode(receiver_cnt, argument_cnt));
1325    Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1326    Node* if_ne = generate_slow_guard(bol, NULL);
1327    if (if_ne != NULL) {
1328      phi->init_req(4, intcon(0));
1329      region->init_req(4, if_ne);
1330    }
1331
1332    // Check for count == 0 is done by assembler code for StrEquals.
1333
1334    if (!stopped()) {
1335      Node* equals = make_string_method_node(Op_StrEquals, receiver_start, receiver_cnt, argument_start, argument_cnt);
1336      phi->init_req(1, equals);
1337      region->init_req(1, control());
1338    }
1339  }
1340
1341  // post merge
1342  set_control(_gvn.transform(region));
1343  record_for_igvn(region);
1344
1345  set_result(_gvn.transform(phi));
1346  return true;
1347}
1348
1349//------------------------------inline_array_equals----------------------------
1350bool LibraryCallKit::inline_array_equals() {
1351  Node* arg1 = argument(0);
1352  Node* arg2 = argument(1);
1353  set_result(_gvn.transform(new AryEqNode(control(), memory(TypeAryPtr::CHARS), arg1, arg2)));
1354  return true;
1355}
1356
1357// Java version of String.indexOf(constant string)
1358// class StringDecl {
1359//   StringDecl(char[] ca) {
1360//     offset = 0;
1361//     count = ca.length;
1362//     value = ca;
1363//   }
1364//   int offset;
1365//   int count;
1366//   char[] value;
1367// }
1368//
1369// static int string_indexOf_J(StringDecl string_object, char[] target_object,
1370//                             int targetOffset, int cache_i, int md2) {
1371//   int cache = cache_i;
1372//   int sourceOffset = string_object.offset;
1373//   int sourceCount = string_object.count;
1374//   int targetCount = target_object.length;
1375//
1376//   int targetCountLess1 = targetCount - 1;
1377//   int sourceEnd = sourceOffset + sourceCount - targetCountLess1;
1378//
1379//   char[] source = string_object.value;
1380//   char[] target = target_object;
1381//   int lastChar = target[targetCountLess1];
1382//
1383//  outer_loop:
1384//   for (int i = sourceOffset; i < sourceEnd; ) {
1385//     int src = source[i + targetCountLess1];
1386//     if (src == lastChar) {
1387//       // With random strings and a 4-character alphabet,
1388//       // reverse matching at this point sets up 0.8% fewer
1389//       // frames, but (paradoxically) makes 0.3% more probes.
1390//       // Since those probes are nearer the lastChar probe,
1391//       // there is may be a net D$ win with reverse matching.
1392//       // But, reversing loop inhibits unroll of inner loop
1393//       // for unknown reason.  So, does running outer loop from
1394//       // (sourceOffset - targetCountLess1) to (sourceOffset + sourceCount)
1395//       for (int j = 0; j < targetCountLess1; j++) {
1396//         if (target[targetOffset + j] != source[i+j]) {
1397//           if ((cache & (1 << source[i+j])) == 0) {
1398//             if (md2 < j+1) {
1399//               i += j+1;
1400//               continue outer_loop;
1401//             }
1402//           }
1403//           i += md2;
1404//           continue outer_loop;
1405//         }
1406//       }
1407//       return i - sourceOffset;
1408//     }
1409//     if ((cache & (1 << src)) == 0) {
1410//       i += targetCountLess1;
1411//     } // using "i += targetCount;" and an "else i++;" causes a jump to jump.
1412//     i++;
1413//   }
1414//   return -1;
1415// }
1416
1417//------------------------------string_indexOf------------------------
1418Node* LibraryCallKit::string_indexOf(Node* string_object, ciTypeArray* target_array, jint targetOffset_i,
1419                                     jint cache_i, jint md2_i) {
1420
1421  Node* no_ctrl  = NULL;
1422  float likely   = PROB_LIKELY(0.9);
1423  float unlikely = PROB_UNLIKELY(0.9);
1424
1425  const int nargs = 0; // no arguments to push back for uncommon trap in predicate
1426
1427  Node* source        = load_String_value(no_ctrl, string_object);
1428  Node* sourceOffset  = load_String_offset(no_ctrl, string_object);
1429  Node* sourceCount   = load_String_length(no_ctrl, string_object);
1430
1431  Node* target = _gvn.transform( makecon(TypeOopPtr::make_from_constant(target_array, true)));
1432  jint target_length = target_array->length();
1433  const TypeAry* target_array_type = TypeAry::make(TypeInt::CHAR, TypeInt::make(0, target_length, Type::WidenMin));
1434  const TypeAryPtr* target_type = TypeAryPtr::make(TypePtr::BotPTR, target_array_type, target_array->klass(), true, Type::OffsetBot);
1435
1436  // String.value field is known to be @Stable.
1437  if (UseImplicitStableValues) {
1438    target = cast_array_to_stable(target, target_type);
1439  }
1440
1441  IdealKit kit(this, false, true);
1442#define __ kit.
1443  Node* zero             = __ ConI(0);
1444  Node* one              = __ ConI(1);
1445  Node* cache            = __ ConI(cache_i);
1446  Node* md2              = __ ConI(md2_i);
1447  Node* lastChar         = __ ConI(target_array->char_at(target_length - 1));
1448  Node* targetCountLess1 = __ ConI(target_length - 1);
1449  Node* targetOffset     = __ ConI(targetOffset_i);
1450  Node* sourceEnd        = __ SubI(__ AddI(sourceOffset, sourceCount), targetCountLess1);
1451
1452  IdealVariable rtn(kit), i(kit), j(kit); __ declarations_done();
1453  Node* outer_loop = __ make_label(2 /* goto */);
1454  Node* return_    = __ make_label(1);
1455
1456  __ set(rtn,__ ConI(-1));
1457  __ loop(this, nargs, i, sourceOffset, BoolTest::lt, sourceEnd); {
1458       Node* i2  = __ AddI(__ value(i), targetCountLess1);
1459       // pin to prohibit loading of "next iteration" value which may SEGV (rare)
1460       Node* src = load_array_element(__ ctrl(), source, i2, TypeAryPtr::CHARS);
1461       __ if_then(src, BoolTest::eq, lastChar, unlikely); {
1462         __ loop(this, nargs, j, zero, BoolTest::lt, targetCountLess1); {
1463              Node* tpj = __ AddI(targetOffset, __ value(j));
1464              Node* targ = load_array_element(no_ctrl, target, tpj, target_type);
1465              Node* ipj  = __ AddI(__ value(i), __ value(j));
1466              Node* src2 = load_array_element(no_ctrl, source, ipj, TypeAryPtr::CHARS);
1467              __ if_then(targ, BoolTest::ne, src2); {
1468                __ if_then(__ AndI(cache, __ LShiftI(one, src2)), BoolTest::eq, zero); {
1469                  __ if_then(md2, BoolTest::lt, __ AddI(__ value(j), one)); {
1470                    __ increment(i, __ AddI(__ value(j), one));
1471                    __ goto_(outer_loop);
1472                  } __ end_if(); __ dead(j);
1473                }__ end_if(); __ dead(j);
1474                __ increment(i, md2);
1475                __ goto_(outer_loop);
1476              }__ end_if();
1477              __ increment(j, one);
1478         }__ end_loop(); __ dead(j);
1479         __ set(rtn, __ SubI(__ value(i), sourceOffset)); __ dead(i);
1480         __ goto_(return_);
1481       }__ end_if();
1482       __ if_then(__ AndI(cache, __ LShiftI(one, src)), BoolTest::eq, zero, likely); {
1483         __ increment(i, targetCountLess1);
1484       }__ end_if();
1485       __ increment(i, one);
1486       __ bind(outer_loop);
1487  }__ end_loop(); __ dead(i);
1488  __ bind(return_);
1489
1490  // Final sync IdealKit and GraphKit.
1491  final_sync(kit);
1492  Node* result = __ value(rtn);
1493#undef __
1494  C->set_has_loops(true);
1495  return result;
1496}
1497
1498//------------------------------inline_string_indexOf------------------------
1499bool LibraryCallKit::inline_string_indexOf() {
1500  Node* receiver = argument(0);
1501  Node* arg      = argument(1);
1502
1503  Node* result;
1504  if (Matcher::has_match_rule(Op_StrIndexOf) &&
1505      UseSSE42Intrinsics) {
1506    // Generate SSE4.2 version of indexOf
1507    // We currently only have match rules that use SSE4.2
1508
1509    receiver = null_check(receiver);
1510    arg      = null_check(arg);
1511    if (stopped()) {
1512      return true;
1513    }
1514
1515    // Make the merge point
1516    RegionNode* result_rgn = new RegionNode(4);
1517    Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1518    Node* no_ctrl  = NULL;
1519
1520    // Get start addr of source string
1521    Node* source = load_String_value(no_ctrl, receiver);
1522    Node* source_offset = load_String_offset(no_ctrl, receiver);
1523    Node* source_start = array_element_address(source, source_offset, T_CHAR);
1524
1525    // Get length of source string
1526    Node* source_cnt  = load_String_length(no_ctrl, receiver);
1527
1528    // Get start addr of substring
1529    Node* substr = load_String_value(no_ctrl, arg);
1530    Node* substr_offset = load_String_offset(no_ctrl, arg);
1531    Node* substr_start = array_element_address(substr, substr_offset, T_CHAR);
1532
1533    // Get length of source string
1534    Node* substr_cnt  = load_String_length(no_ctrl, arg);
1535
1536    // Check for substr count > string count
1537    Node* cmp = _gvn.transform(new CmpINode(substr_cnt, source_cnt));
1538    Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1539    Node* if_gt = generate_slow_guard(bol, NULL);
1540    if (if_gt != NULL) {
1541      result_phi->init_req(2, intcon(-1));
1542      result_rgn->init_req(2, if_gt);
1543    }
1544
1545    if (!stopped()) {
1546      // Check for substr count == 0
1547      cmp = _gvn.transform(new CmpINode(substr_cnt, intcon(0)));
1548      bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1549      Node* if_zero = generate_slow_guard(bol, NULL);
1550      if (if_zero != NULL) {
1551        result_phi->init_req(3, intcon(0));
1552        result_rgn->init_req(3, if_zero);
1553      }
1554    }
1555
1556    if (!stopped()) {
1557      result = make_string_method_node(Op_StrIndexOf, source_start, source_cnt, substr_start, substr_cnt);
1558      result_phi->init_req(1, result);
1559      result_rgn->init_req(1, control());
1560    }
1561    set_control(_gvn.transform(result_rgn));
1562    record_for_igvn(result_rgn);
1563    result = _gvn.transform(result_phi);
1564
1565  } else { // Use LibraryCallKit::string_indexOf
1566    // don't intrinsify if argument isn't a constant string.
1567    if (!arg->is_Con()) {
1568     return false;
1569    }
1570    const TypeOopPtr* str_type = _gvn.type(arg)->isa_oopptr();
1571    if (str_type == NULL) {
1572      return false;
1573    }
1574    ciInstanceKlass* klass = env()->String_klass();
1575    ciObject* str_const = str_type->const_oop();
1576    if (str_const == NULL || str_const->klass() != klass) {
1577      return false;
1578    }
1579    ciInstance* str = str_const->as_instance();
1580    assert(str != NULL, "must be instance");
1581
1582    ciObject* v = str->field_value_by_offset(java_lang_String::value_offset_in_bytes()).as_object();
1583    ciTypeArray* pat = v->as_type_array(); // pattern (argument) character array
1584
1585    int o;
1586    int c;
1587    if (java_lang_String::has_offset_field()) {
1588      o = str->field_value_by_offset(java_lang_String::offset_offset_in_bytes()).as_int();
1589      c = str->field_value_by_offset(java_lang_String::count_offset_in_bytes()).as_int();
1590    } else {
1591      o = 0;
1592      c = pat->length();
1593    }
1594
1595    // constant strings have no offset and count == length which
1596    // simplifies the resulting code somewhat so lets optimize for that.
1597    if (o != 0 || c != pat->length()) {
1598     return false;
1599    }
1600
1601    receiver = null_check(receiver, T_OBJECT);
1602    // NOTE: No null check on the argument is needed since it's a constant String oop.
1603    if (stopped()) {
1604      return true;
1605    }
1606
1607    // The null string as a pattern always returns 0 (match at beginning of string)
1608    if (c == 0) {
1609      set_result(intcon(0));
1610      return true;
1611    }
1612
1613    // Generate default indexOf
1614    jchar lastChar = pat->char_at(o + (c - 1));
1615    int cache = 0;
1616    int i;
1617    for (i = 0; i < c - 1; i++) {
1618      assert(i < pat->length(), "out of range");
1619      cache |= (1 << (pat->char_at(o + i) & (sizeof(cache) * BitsPerByte - 1)));
1620    }
1621
1622    int md2 = c;
1623    for (i = 0; i < c - 1; i++) {
1624      assert(i < pat->length(), "out of range");
1625      if (pat->char_at(o + i) == lastChar) {
1626        md2 = (c - 1) - i;
1627      }
1628    }
1629
1630    result = string_indexOf(receiver, pat, o, cache, md2);
1631  }
1632  set_result(result);
1633  return true;
1634}
1635
1636//--------------------------round_double_node--------------------------------
1637// Round a double node if necessary.
1638Node* LibraryCallKit::round_double_node(Node* n) {
1639  if (Matcher::strict_fp_requires_explicit_rounding && UseSSE <= 1)
1640    n = _gvn.transform(new RoundDoubleNode(0, n));
1641  return n;
1642}
1643
1644//------------------------------inline_math-----------------------------------
1645// public static double Math.abs(double)
1646// public static double Math.sqrt(double)
1647// public static double Math.log(double)
1648// public static double Math.log10(double)
1649bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1650  Node* arg = round_double_node(argument(0));
1651  Node* n;
1652  switch (id) {
1653  case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1654  case vmIntrinsics::_dsqrt:  n = new SqrtDNode(C, control(),  arg);  break;
1655  case vmIntrinsics::_dlog:   n = new LogDNode(C, control(),   arg);  break;
1656  case vmIntrinsics::_dlog10: n = new Log10DNode(C, control(), arg);  break;
1657  default:  fatal_unexpected_iid(id);  break;
1658  }
1659  set_result(_gvn.transform(n));
1660  return true;
1661}
1662
1663//------------------------------inline_trig----------------------------------
1664// Inline sin/cos/tan instructions, if possible.  If rounding is required, do
1665// argument reduction which will turn into a fast/slow diamond.
1666bool LibraryCallKit::inline_trig(vmIntrinsics::ID id) {
1667  Node* arg = round_double_node(argument(0));
1668  Node* n = NULL;
1669
1670  switch (id) {
1671  case vmIntrinsics::_dsin:  n = new SinDNode(C, control(), arg);  break;
1672  case vmIntrinsics::_dcos:  n = new CosDNode(C, control(), arg);  break;
1673  case vmIntrinsics::_dtan:  n = new TanDNode(C, control(), arg);  break;
1674  default:  fatal_unexpected_iid(id);  break;
1675  }
1676  n = _gvn.transform(n);
1677
1678  // Rounding required?  Check for argument reduction!
1679  if (Matcher::strict_fp_requires_explicit_rounding) {
1680    static const double     pi_4 =  0.7853981633974483;
1681    static const double neg_pi_4 = -0.7853981633974483;
1682    // pi/2 in 80-bit extended precision
1683    // static const unsigned char pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0x3f,0x00,0x00,0x00,0x00,0x00,0x00};
1684    // -pi/2 in 80-bit extended precision
1685    // static const unsigned char neg_pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0xbf,0x00,0x00,0x00,0x00,0x00,0x00};
1686    // Cutoff value for using this argument reduction technique
1687    //static const double    pi_2_minus_epsilon =  1.564660403643354;
1688    //static const double neg_pi_2_plus_epsilon = -1.564660403643354;
1689
1690    // Pseudocode for sin:
1691    // if (x <= Math.PI / 4.0) {
1692    //   if (x >= -Math.PI / 4.0) return  fsin(x);
1693    //   if (x >= -Math.PI / 2.0) return -fcos(x + Math.PI / 2.0);
1694    // } else {
1695    //   if (x <=  Math.PI / 2.0) return  fcos(x - Math.PI / 2.0);
1696    // }
1697    // return StrictMath.sin(x);
1698
1699    // Pseudocode for cos:
1700    // if (x <= Math.PI / 4.0) {
1701    //   if (x >= -Math.PI / 4.0) return  fcos(x);
1702    //   if (x >= -Math.PI / 2.0) return  fsin(x + Math.PI / 2.0);
1703    // } else {
1704    //   if (x <=  Math.PI / 2.0) return -fsin(x - Math.PI / 2.0);
1705    // }
1706    // return StrictMath.cos(x);
1707
1708    // Actually, sticking in an 80-bit Intel value into C2 will be tough; it
1709    // requires a special machine instruction to load it.  Instead we'll try
1710    // the 'easy' case.  If we really need the extra range +/- PI/2 we'll
1711    // probably do the math inside the SIN encoding.
1712
1713    // Make the merge point
1714    RegionNode* r = new RegionNode(3);
1715    Node* phi = new PhiNode(r, Type::DOUBLE);
1716
1717    // Flatten arg so we need only 1 test
1718    Node *abs = _gvn.transform(new AbsDNode(arg));
1719    // Node for PI/4 constant
1720    Node *pi4 = makecon(TypeD::make(pi_4));
1721    // Check PI/4 : abs(arg)
1722    Node *cmp = _gvn.transform(new CmpDNode(pi4,abs));
1723    // Check: If PI/4 < abs(arg) then go slow
1724    Node *bol = _gvn.transform(new BoolNode( cmp, BoolTest::lt ));
1725    // Branch either way
1726    IfNode *iff = create_and_xform_if(control(),bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
1727    set_control(opt_iff(r,iff));
1728
1729    // Set fast path result
1730    phi->init_req(2, n);
1731
1732    // Slow path - non-blocking leaf call
1733    Node* call = NULL;
1734    switch (id) {
1735    case vmIntrinsics::_dsin:
1736      call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1737                               CAST_FROM_FN_PTR(address, SharedRuntime::dsin),
1738                               "Sin", NULL, arg, top());
1739      break;
1740    case vmIntrinsics::_dcos:
1741      call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1742                               CAST_FROM_FN_PTR(address, SharedRuntime::dcos),
1743                               "Cos", NULL, arg, top());
1744      break;
1745    case vmIntrinsics::_dtan:
1746      call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1747                               CAST_FROM_FN_PTR(address, SharedRuntime::dtan),
1748                               "Tan", NULL, arg, top());
1749      break;
1750    }
1751    assert(control()->in(0) == call, "");
1752    Node* slow_result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1753    r->init_req(1, control());
1754    phi->init_req(1, slow_result);
1755
1756    // Post-merge
1757    set_control(_gvn.transform(r));
1758    record_for_igvn(r);
1759    n = _gvn.transform(phi);
1760
1761    C->set_has_split_ifs(true); // Has chance for split-if optimization
1762  }
1763  set_result(n);
1764  return true;
1765}
1766
1767Node* LibraryCallKit::finish_pow_exp(Node* result, Node* x, Node* y, const TypeFunc* call_type, address funcAddr, const char* funcName) {
1768  //-------------------
1769  //result=(result.isNaN())? funcAddr():result;
1770  // Check: If isNaN() by checking result!=result? then either trap
1771  // or go to runtime
1772  Node* cmpisnan = _gvn.transform(new CmpDNode(result, result));
1773  // Build the boolean node
1774  Node* bolisnum = _gvn.transform(new BoolNode(cmpisnan, BoolTest::eq));
1775
1776  if (!too_many_traps(Deoptimization::Reason_intrinsic)) {
1777    { BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);
1778      // The pow or exp intrinsic returned a NaN, which requires a call
1779      // to the runtime.  Recompile with the runtime call.
1780      uncommon_trap(Deoptimization::Reason_intrinsic,
1781                    Deoptimization::Action_make_not_entrant);
1782    }
1783    return result;
1784  } else {
1785    // If this inlining ever returned NaN in the past, we compile a call
1786    // to the runtime to properly handle corner cases
1787
1788    IfNode* iff = create_and_xform_if(control(), bolisnum, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
1789    Node* if_slow = _gvn.transform(new IfFalseNode(iff));
1790    Node* if_fast = _gvn.transform(new IfTrueNode(iff));
1791
1792    if (!if_slow->is_top()) {
1793      RegionNode* result_region = new RegionNode(3);
1794      PhiNode*    result_val = new PhiNode(result_region, Type::DOUBLE);
1795
1796      result_region->init_req(1, if_fast);
1797      result_val->init_req(1, result);
1798
1799      set_control(if_slow);
1800
1801      const TypePtr* no_memory_effects = NULL;
1802      Node* rt = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
1803                                   no_memory_effects,
1804                                   x, top(), y, y ? top() : NULL);
1805      Node* value = _gvn.transform(new ProjNode(rt, TypeFunc::Parms+0));
1806#ifdef ASSERT
1807      Node* value_top = _gvn.transform(new ProjNode(rt, TypeFunc::Parms+1));
1808      assert(value_top == top(), "second value must be top");
1809#endif
1810
1811      result_region->init_req(2, control());
1812      result_val->init_req(2, value);
1813      set_control(_gvn.transform(result_region));
1814      return _gvn.transform(result_val);
1815    } else {
1816      return result;
1817    }
1818  }
1819}
1820
1821//------------------------------inline_exp-------------------------------------
1822// Inline exp instructions, if possible.  The Intel hardware only misses
1823// really odd corner cases (+/- Infinity).  Just uncommon-trap them.
1824bool LibraryCallKit::inline_exp() {
1825  Node* arg = round_double_node(argument(0));
1826  Node* n   = _gvn.transform(new ExpDNode(C, control(), arg));
1827
1828  n = finish_pow_exp(n, arg, NULL, OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");
1829  set_result(n);
1830
1831  C->set_has_split_ifs(true); // Has chance for split-if optimization
1832  return true;
1833}
1834
1835//------------------------------inline_pow-------------------------------------
1836// Inline power instructions, if possible.
1837bool LibraryCallKit::inline_pow() {
1838  // Pseudocode for pow
1839  // if (y == 2) {
1840  //   return x * x;
1841  // } else {
1842  //   if (x <= 0.0) {
1843  //     long longy = (long)y;
1844  //     if ((double)longy == y) { // if y is long
1845  //       if (y + 1 == y) longy = 0; // huge number: even
1846  //       result = ((1&longy) == 0)?-DPow(abs(x), y):DPow(abs(x), y);
1847  //     } else {
1848  //       result = NaN;
1849  //     }
1850  //   } else {
1851  //     result = DPow(x,y);
1852  //   }
1853  //   if (result != result)?  {
1854  //     result = uncommon_trap() or runtime_call();
1855  //   }
1856  //   return result;
1857  // }
1858
1859  Node* x = round_double_node(argument(0));
1860  Node* y = round_double_node(argument(2));
1861
1862  Node* result = NULL;
1863
1864  Node*   const_two_node = makecon(TypeD::make(2.0));
1865  Node*   cmp_node       = _gvn.transform(new CmpDNode(y, const_two_node));
1866  Node*   bool_node      = _gvn.transform(new BoolNode(cmp_node, BoolTest::eq));
1867  IfNode* if_node        = create_and_xform_if(control(), bool_node, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1868  Node*   if_true        = _gvn.transform(new IfTrueNode(if_node));
1869  Node*   if_false       = _gvn.transform(new IfFalseNode(if_node));
1870
1871  RegionNode* region_node = new RegionNode(3);
1872  region_node->init_req(1, if_true);
1873
1874  Node* phi_node = new PhiNode(region_node, Type::DOUBLE);
1875  // special case for x^y where y == 2, we can convert it to x * x
1876  phi_node->init_req(1, _gvn.transform(new MulDNode(x, x)));
1877
1878  // set control to if_false since we will now process the false branch
1879  set_control(if_false);
1880
1881  if (!too_many_traps(Deoptimization::Reason_intrinsic)) {
1882    // Short form: skip the fancy tests and just check for NaN result.
1883    result = _gvn.transform(new PowDNode(C, control(), x, y));
1884  } else {
1885    // If this inlining ever returned NaN in the past, include all
1886    // checks + call to the runtime.
1887
1888    // Set the merge point for If node with condition of (x <= 0.0)
1889    // There are four possible paths to region node and phi node
1890    RegionNode *r = new RegionNode(4);
1891    Node *phi = new PhiNode(r, Type::DOUBLE);
1892
1893    // Build the first if node: if (x <= 0.0)
1894    // Node for 0 constant
1895    Node *zeronode = makecon(TypeD::ZERO);
1896    // Check x:0
1897    Node *cmp = _gvn.transform(new CmpDNode(x, zeronode));
1898    // Check: If (x<=0) then go complex path
1899    Node *bol1 = _gvn.transform(new BoolNode( cmp, BoolTest::le ));
1900    // Branch either way
1901    IfNode *if1 = create_and_xform_if(control(),bol1, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1902    // Fast path taken; set region slot 3
1903    Node *fast_taken = _gvn.transform(new IfFalseNode(if1));
1904    r->init_req(3,fast_taken); // Capture fast-control
1905
1906    // Fast path not-taken, i.e. slow path
1907    Node *complex_path = _gvn.transform(new IfTrueNode(if1));
1908
1909    // Set fast path result
1910    Node *fast_result = _gvn.transform(new PowDNode(C, control(), x, y));
1911    phi->init_req(3, fast_result);
1912
1913    // Complex path
1914    // Build the second if node (if y is long)
1915    // Node for (long)y
1916    Node *longy = _gvn.transform(new ConvD2LNode(y));
1917    // Node for (double)((long) y)
1918    Node *doublelongy= _gvn.transform(new ConvL2DNode(longy));
1919    // Check (double)((long) y) : y
1920    Node *cmplongy= _gvn.transform(new CmpDNode(doublelongy, y));
1921    // Check if (y isn't long) then go to slow path
1922
1923    Node *bol2 = _gvn.transform(new BoolNode( cmplongy, BoolTest::ne ));
1924    // Branch either way
1925    IfNode *if2 = create_and_xform_if(complex_path,bol2, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1926    Node* ylong_path = _gvn.transform(new IfFalseNode(if2));
1927
1928    Node *slow_path = _gvn.transform(new IfTrueNode(if2));
1929
1930    // Calculate DPow(abs(x), y)*(1 & (long)y)
1931    // Node for constant 1
1932    Node *conone = longcon(1);
1933    // 1& (long)y
1934    Node *signnode= _gvn.transform(new AndLNode(conone, longy));
1935
1936    // A huge number is always even. Detect a huge number by checking
1937    // if y + 1 == y and set integer to be tested for parity to 0.
1938    // Required for corner case:
1939    // (long)9.223372036854776E18 = max_jlong
1940    // (double)(long)9.223372036854776E18 = 9.223372036854776E18
1941    // max_jlong is odd but 9.223372036854776E18 is even
1942    Node* yplus1 = _gvn.transform(new AddDNode(y, makecon(TypeD::make(1))));
1943    Node *cmpyplus1= _gvn.transform(new CmpDNode(yplus1, y));
1944    Node *bolyplus1 = _gvn.transform(new BoolNode( cmpyplus1, BoolTest::eq ));
1945    Node* correctedsign = NULL;
1946    if (ConditionalMoveLimit != 0) {
1947      correctedsign = _gvn.transform(CMoveNode::make(NULL, bolyplus1, signnode, longcon(0), TypeLong::LONG));
1948    } else {
1949      IfNode *ifyplus1 = create_and_xform_if(ylong_path,bolyplus1, PROB_FAIR, COUNT_UNKNOWN);
1950      RegionNode *r = new RegionNode(3);
1951      Node *phi = new PhiNode(r, TypeLong::LONG);
1952      r->init_req(1, _gvn.transform(new IfFalseNode(ifyplus1)));
1953      r->init_req(2, _gvn.transform(new IfTrueNode(ifyplus1)));
1954      phi->init_req(1, signnode);
1955      phi->init_req(2, longcon(0));
1956      correctedsign = _gvn.transform(phi);
1957      ylong_path = _gvn.transform(r);
1958      record_for_igvn(r);
1959    }
1960
1961    // zero node
1962    Node *conzero = longcon(0);
1963    // Check (1&(long)y)==0?
1964    Node *cmpeq1 = _gvn.transform(new CmpLNode(correctedsign, conzero));
1965    // Check if (1&(long)y)!=0?, if so the result is negative
1966    Node *bol3 = _gvn.transform(new BoolNode( cmpeq1, BoolTest::ne ));
1967    // abs(x)
1968    Node *absx=_gvn.transform(new AbsDNode(x));
1969    // abs(x)^y
1970    Node *absxpowy = _gvn.transform(new PowDNode(C, control(), absx, y));
1971    // -abs(x)^y
1972    Node *negabsxpowy = _gvn.transform(new NegDNode (absxpowy));
1973    // (1&(long)y)==1?-DPow(abs(x), y):DPow(abs(x), y)
1974    Node *signresult = NULL;
1975    if (ConditionalMoveLimit != 0) {
1976      signresult = _gvn.transform(CMoveNode::make(NULL, bol3, absxpowy, negabsxpowy, Type::DOUBLE));
1977    } else {
1978      IfNode *ifyeven = create_and_xform_if(ylong_path,bol3, PROB_FAIR, COUNT_UNKNOWN);
1979      RegionNode *r = new RegionNode(3);
1980      Node *phi = new PhiNode(r, Type::DOUBLE);
1981      r->init_req(1, _gvn.transform(new IfFalseNode(ifyeven)));
1982      r->init_req(2, _gvn.transform(new IfTrueNode(ifyeven)));
1983      phi->init_req(1, absxpowy);
1984      phi->init_req(2, negabsxpowy);
1985      signresult = _gvn.transform(phi);
1986      ylong_path = _gvn.transform(r);
1987      record_for_igvn(r);
1988    }
1989    // Set complex path fast result
1990    r->init_req(2, ylong_path);
1991    phi->init_req(2, signresult);
1992
1993    static const jlong nan_bits = CONST64(0x7ff8000000000000);
1994    Node *slow_result = makecon(TypeD::make(*(double*)&nan_bits)); // return NaN
1995    r->init_req(1,slow_path);
1996    phi->init_req(1,slow_result);
1997
1998    // Post merge
1999    set_control(_gvn.transform(r));
2000    record_for_igvn(r);
2001    result = _gvn.transform(phi);
2002  }
2003
2004  result = finish_pow_exp(result, x, y, OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow), "POW");
2005
2006  // control from finish_pow_exp is now input to the region node
2007  region_node->set_req(2, control());
2008  // the result from finish_pow_exp is now input to the phi node
2009  phi_node->init_req(2, result);
2010  set_control(_gvn.transform(region_node));
2011  record_for_igvn(region_node);
2012  set_result(_gvn.transform(phi_node));
2013
2014  C->set_has_split_ifs(true); // Has chance for split-if optimization
2015  return true;
2016}
2017
2018//------------------------------runtime_math-----------------------------
2019bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
2020  assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
2021         "must be (DD)D or (D)D type");
2022
2023  // Inputs
2024  Node* a = round_double_node(argument(0));
2025  Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? round_double_node(argument(2)) : NULL;
2026
2027  const TypePtr* no_memory_effects = NULL;
2028  Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
2029                                 no_memory_effects,
2030                                 a, top(), b, b ? top() : NULL);
2031  Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
2032#ifdef ASSERT
2033  Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
2034  assert(value_top == top(), "second value must be top");
2035#endif
2036
2037  set_result(value);
2038  return true;
2039}
2040
2041//------------------------------inline_math_native-----------------------------
2042bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
2043#define FN_PTR(f) CAST_FROM_FN_PTR(address, f)
2044  switch (id) {
2045    // These intrinsics are not properly supported on all hardware
2046  case vmIntrinsics::_dcos:   return Matcher::has_match_rule(Op_CosD)   ? inline_trig(id) :
2047    runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dcos),   "COS");
2048  case vmIntrinsics::_dsin:   return Matcher::has_match_rule(Op_SinD)   ? inline_trig(id) :
2049    runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dsin),   "SIN");
2050  case vmIntrinsics::_dtan:   return Matcher::has_match_rule(Op_TanD)   ? inline_trig(id) :
2051    runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dtan),   "TAN");
2052
2053  case vmIntrinsics::_dlog:   return Matcher::has_match_rule(Op_LogD)   ? inline_math(id) :
2054    runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog),   "LOG");
2055  case vmIntrinsics::_dlog10: return Matcher::has_match_rule(Op_Log10D) ? inline_math(id) :
2056    runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog10), "LOG10");
2057
2058    // These intrinsics are supported on all hardware
2059  case vmIntrinsics::_dsqrt:  return Matcher::match_rule_supported(Op_SqrtD) ? inline_math(id) : false;
2060  case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_math(id) : false;
2061
2062  case vmIntrinsics::_dexp:   return Matcher::has_match_rule(Op_ExpD)   ? inline_exp()    :
2063    runtime_math(OptoRuntime::Math_D_D_Type(),  FN_PTR(SharedRuntime::dexp),  "EXP");
2064  case vmIntrinsics::_dpow:   return Matcher::has_match_rule(Op_PowD)   ? inline_pow()    :
2065    runtime_math(OptoRuntime::Math_DD_D_Type(), FN_PTR(SharedRuntime::dpow),  "POW");
2066#undef FN_PTR
2067
2068   // These intrinsics are not yet correctly implemented
2069  case vmIntrinsics::_datan2:
2070    return false;
2071
2072  default:
2073    fatal_unexpected_iid(id);
2074    return false;
2075  }
2076}
2077
2078static bool is_simple_name(Node* n) {
2079  return (n->req() == 1         // constant
2080          || (n->is_Type() && n->as_Type()->type()->singleton())
2081          || n->is_Proj()       // parameter or return value
2082          || n->is_Phi()        // local of some sort
2083          );
2084}
2085
2086//----------------------------inline_notify-----------------------------------*
2087bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
2088  const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
2089  address func;
2090  if (id == vmIntrinsics::_notify) {
2091    func = OptoRuntime::monitor_notify_Java();
2092  } else {
2093    func = OptoRuntime::monitor_notifyAll_Java();
2094  }
2095  Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, NULL, TypeRawPtr::BOTTOM, argument(0));
2096  make_slow_call_ex(call, env()->Throwable_klass(), false);
2097  return true;
2098}
2099
2100
2101//----------------------------inline_min_max-----------------------------------
2102bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
2103  set_result(generate_min_max(id, argument(0), argument(1)));
2104  return true;
2105}
2106
2107void LibraryCallKit::inline_math_mathExact(Node* math, Node *test) {
2108  Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2109  IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2110  Node* fast_path = _gvn.transform( new IfFalseNode(check));
2111  Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2112
2113  {
2114    PreserveJVMState pjvms(this);
2115    PreserveReexecuteState preexecs(this);
2116    jvms()->set_should_reexecute(true);
2117
2118    set_control(slow_path);
2119    set_i_o(i_o());
2120
2121    uncommon_trap(Deoptimization::Reason_intrinsic,
2122                  Deoptimization::Action_none);
2123  }
2124
2125  set_control(fast_path);
2126  set_result(math);
2127}
2128
2129template <typename OverflowOp>
2130bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2131  typedef typename OverflowOp::MathOp MathOp;
2132
2133  MathOp* mathOp = new MathOp(arg1, arg2);
2134  Node* operation = _gvn.transform( mathOp );
2135  Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2136  inline_math_mathExact(operation, ofcheck);
2137  return true;
2138}
2139
2140bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2141  return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2142}
2143
2144bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2145  return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2146}
2147
2148bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2149  return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2150}
2151
2152bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2153  return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2154}
2155
2156bool LibraryCallKit::inline_math_negateExactI() {
2157  return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2158}
2159
2160bool LibraryCallKit::inline_math_negateExactL() {
2161  return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2162}
2163
2164bool LibraryCallKit::inline_math_multiplyExactI() {
2165  return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2166}
2167
2168bool LibraryCallKit::inline_math_multiplyExactL() {
2169  return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2170}
2171
2172Node*
2173LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) {
2174  // These are the candidate return value:
2175  Node* xvalue = x0;
2176  Node* yvalue = y0;
2177
2178  if (xvalue == yvalue) {
2179    return xvalue;
2180  }
2181
2182  bool want_max = (id == vmIntrinsics::_max);
2183
2184  const TypeInt* txvalue = _gvn.type(xvalue)->isa_int();
2185  const TypeInt* tyvalue = _gvn.type(yvalue)->isa_int();
2186  if (txvalue == NULL || tyvalue == NULL)  return top();
2187  // This is not really necessary, but it is consistent with a
2188  // hypothetical MaxINode::Value method:
2189  int widen = MAX2(txvalue->_widen, tyvalue->_widen);
2190
2191  // %%% This folding logic should (ideally) be in a different place.
2192  // Some should be inside IfNode, and there to be a more reliable
2193  // transformation of ?: style patterns into cmoves.  We also want
2194  // more powerful optimizations around cmove and min/max.
2195
2196  // Try to find a dominating comparison of these guys.
2197  // It can simplify the index computation for Arrays.copyOf
2198  // and similar uses of System.arraycopy.
2199  // First, compute the normalized version of CmpI(x, y).
2200  int   cmp_op = Op_CmpI;
2201  Node* xkey = xvalue;
2202  Node* ykey = yvalue;
2203  Node* ideal_cmpxy = _gvn.transform(new CmpINode(xkey, ykey));
2204  if (ideal_cmpxy->is_Cmp()) {
2205    // E.g., if we have CmpI(length - offset, count),
2206    // it might idealize to CmpI(length, count + offset)
2207    cmp_op = ideal_cmpxy->Opcode();
2208    xkey = ideal_cmpxy->in(1);
2209    ykey = ideal_cmpxy->in(2);
2210  }
2211
2212  // Start by locating any relevant comparisons.
2213  Node* start_from = (xkey->outcnt() < ykey->outcnt()) ? xkey : ykey;
2214  Node* cmpxy = NULL;
2215  Node* cmpyx = NULL;
2216  for (DUIterator_Fast kmax, k = start_from->fast_outs(kmax); k < kmax; k++) {
2217    Node* cmp = start_from->fast_out(k);
2218    if (cmp->outcnt() > 0 &&            // must have prior uses
2219        cmp->in(0) == NULL &&           // must be context-independent
2220        cmp->Opcode() == cmp_op) {      // right kind of compare
2221      if (cmp->in(1) == xkey && cmp->in(2) == ykey)  cmpxy = cmp;
2222      if (cmp->in(1) == ykey && cmp->in(2) == xkey)  cmpyx = cmp;
2223    }
2224  }
2225
2226  const int NCMPS = 2;
2227  Node* cmps[NCMPS] = { cmpxy, cmpyx };
2228  int cmpn;
2229  for (cmpn = 0; cmpn < NCMPS; cmpn++) {
2230    if (cmps[cmpn] != NULL)  break;     // find a result
2231  }
2232  if (cmpn < NCMPS) {
2233    // Look for a dominating test that tells us the min and max.
2234    int depth = 0;                // Limit search depth for speed
2235    Node* dom = control();
2236    for (; dom != NULL; dom = IfNode::up_one_dom(dom, true)) {
2237      if (++depth >= 100)  break;
2238      Node* ifproj = dom;
2239      if (!ifproj->is_Proj())  continue;
2240      Node* iff = ifproj->in(0);
2241      if (!iff->is_If())  continue;
2242      Node* bol = iff->in(1);
2243      if (!bol->is_Bool())  continue;
2244      Node* cmp = bol->in(1);
2245      if (cmp == NULL)  continue;
2246      for (cmpn = 0; cmpn < NCMPS; cmpn++)
2247        if (cmps[cmpn] == cmp)  break;
2248      if (cmpn == NCMPS)  continue;
2249      BoolTest::mask btest = bol->as_Bool()->_test._test;
2250      if (ifproj->is_IfFalse())  btest = BoolTest(btest).negate();
2251      if (cmp->in(1) == ykey)    btest = BoolTest(btest).commute();
2252      // At this point, we know that 'x btest y' is true.
2253      switch (btest) {
2254      case BoolTest::eq:
2255        // They are proven equal, so we can collapse the min/max.
2256        // Either value is the answer.  Choose the simpler.
2257        if (is_simple_name(yvalue) && !is_simple_name(xvalue))
2258          return yvalue;
2259        return xvalue;
2260      case BoolTest::lt:          // x < y
2261      case BoolTest::le:          // x <= y
2262        return (want_max ? yvalue : xvalue);
2263      case BoolTest::gt:          // x > y
2264      case BoolTest::ge:          // x >= y
2265        return (want_max ? xvalue : yvalue);
2266      }
2267    }
2268  }
2269
2270  // We failed to find a dominating test.
2271  // Let's pick a test that might GVN with prior tests.
2272  Node*          best_bol   = NULL;
2273  BoolTest::mask best_btest = BoolTest::illegal;
2274  for (cmpn = 0; cmpn < NCMPS; cmpn++) {
2275    Node* cmp = cmps[cmpn];
2276    if (cmp == NULL)  continue;
2277    for (DUIterator_Fast jmax, j = cmp->fast_outs(jmax); j < jmax; j++) {
2278      Node* bol = cmp->fast_out(j);
2279      if (!bol->is_Bool())  continue;
2280      BoolTest::mask btest = bol->as_Bool()->_test._test;
2281      if (btest == BoolTest::eq || btest == BoolTest::ne)  continue;
2282      if (cmp->in(1) == ykey)   btest = BoolTest(btest).commute();
2283      if (bol->outcnt() > (best_bol == NULL ? 0 : best_bol->outcnt())) {
2284        best_bol   = bol->as_Bool();
2285        best_btest = btest;
2286      }
2287    }
2288  }
2289
2290  Node* answer_if_true  = NULL;
2291  Node* answer_if_false = NULL;
2292  switch (best_btest) {
2293  default:
2294    if (cmpxy == NULL)
2295      cmpxy = ideal_cmpxy;
2296    best_bol = _gvn.transform(new BoolNode(cmpxy, BoolTest::lt));
2297    // and fall through:
2298  case BoolTest::lt:          // x < y
2299  case BoolTest::le:          // x <= y
2300    answer_if_true  = (want_max ? yvalue : xvalue);
2301    answer_if_false = (want_max ? xvalue : yvalue);
2302    break;
2303  case BoolTest::gt:          // x > y
2304  case BoolTest::ge:          // x >= y
2305    answer_if_true  = (want_max ? xvalue : yvalue);
2306    answer_if_false = (want_max ? yvalue : xvalue);
2307    break;
2308  }
2309
2310  jint hi, lo;
2311  if (want_max) {
2312    // We can sharpen the minimum.
2313    hi = MAX2(txvalue->_hi, tyvalue->_hi);
2314    lo = MAX2(txvalue->_lo, tyvalue->_lo);
2315  } else {
2316    // We can sharpen the maximum.
2317    hi = MIN2(txvalue->_hi, tyvalue->_hi);
2318    lo = MIN2(txvalue->_lo, tyvalue->_lo);
2319  }
2320
2321  // Use a flow-free graph structure, to avoid creating excess control edges
2322  // which could hinder other optimizations.
2323  // Since Math.min/max is often used with arraycopy, we want
2324  // tightly_coupled_allocation to be able to see beyond min/max expressions.
2325  Node* cmov = CMoveNode::make(NULL, best_bol,
2326                               answer_if_false, answer_if_true,
2327                               TypeInt::make(lo, hi, widen));
2328
2329  return _gvn.transform(cmov);
2330
2331  /*
2332  // This is not as desirable as it may seem, since Min and Max
2333  // nodes do not have a full set of optimizations.
2334  // And they would interfere, anyway, with 'if' optimizations
2335  // and with CMoveI canonical forms.
2336  switch (id) {
2337  case vmIntrinsics::_min:
2338    result_val = _gvn.transform(new (C, 3) MinINode(x,y)); break;
2339  case vmIntrinsics::_max:
2340    result_val = _gvn.transform(new (C, 3) MaxINode(x,y)); break;
2341  default:
2342    ShouldNotReachHere();
2343  }
2344  */
2345}
2346
2347inline int
2348LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset) {
2349  const TypePtr* base_type = TypePtr::NULL_PTR;
2350  if (base != NULL)  base_type = _gvn.type(base)->isa_ptr();
2351  if (base_type == NULL) {
2352    // Unknown type.
2353    return Type::AnyPtr;
2354  } else if (base_type == TypePtr::NULL_PTR) {
2355    // Since this is a NULL+long form, we have to switch to a rawptr.
2356    base   = _gvn.transform(new CastX2PNode(offset));
2357    offset = MakeConX(0);
2358    return Type::RawPtr;
2359  } else if (base_type->base() == Type::RawPtr) {
2360    return Type::RawPtr;
2361  } else if (base_type->isa_oopptr()) {
2362    // Base is never null => always a heap address.
2363    if (base_type->ptr() == TypePtr::NotNull) {
2364      return Type::OopPtr;
2365    }
2366    // Offset is small => always a heap address.
2367    const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2368    if (offset_type != NULL &&
2369        base_type->offset() == 0 &&     // (should always be?)
2370        offset_type->_lo >= 0 &&
2371        !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2372      return Type::OopPtr;
2373    }
2374    // Otherwise, it might either be oop+off or NULL+addr.
2375    return Type::AnyPtr;
2376  } else {
2377    // No information:
2378    return Type::AnyPtr;
2379  }
2380}
2381
2382inline Node* LibraryCallKit::make_unsafe_address(Node* base, Node* offset) {
2383  int kind = classify_unsafe_addr(base, offset);
2384  if (kind == Type::RawPtr) {
2385    return basic_plus_adr(top(), base, offset);
2386  } else {
2387    return basic_plus_adr(base, offset);
2388  }
2389}
2390
2391//--------------------------inline_number_methods-----------------------------
2392// inline int     Integer.numberOfLeadingZeros(int)
2393// inline int        Long.numberOfLeadingZeros(long)
2394//
2395// inline int     Integer.numberOfTrailingZeros(int)
2396// inline int        Long.numberOfTrailingZeros(long)
2397//
2398// inline int     Integer.bitCount(int)
2399// inline int        Long.bitCount(long)
2400//
2401// inline char  Character.reverseBytes(char)
2402// inline short     Short.reverseBytes(short)
2403// inline int     Integer.reverseBytes(int)
2404// inline long       Long.reverseBytes(long)
2405bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2406  Node* arg = argument(0);
2407  Node* n;
2408  switch (id) {
2409  case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg);  break;
2410  case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg);  break;
2411  case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg);  break;
2412  case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg);  break;
2413  case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg);  break;
2414  case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg);  break;
2415  case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(0,   arg);  break;
2416  case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode( 0,   arg);  break;
2417  case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode( 0,   arg);  break;
2418  case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode( 0,   arg);  break;
2419  default:  fatal_unexpected_iid(id);  break;
2420  }
2421  set_result(_gvn.transform(n));
2422  return true;
2423}
2424
2425//----------------------------inline_unsafe_access----------------------------
2426
2427const static BasicType T_ADDRESS_HOLDER = T_LONG;
2428
2429// Helper that guards and inserts a pre-barrier.
2430void LibraryCallKit::insert_pre_barrier(Node* base_oop, Node* offset,
2431                                        Node* pre_val, bool need_mem_bar) {
2432  // We could be accessing the referent field of a reference object. If so, when G1
2433  // is enabled, we need to log the value in the referent field in an SATB buffer.
2434  // This routine performs some compile time filters and generates suitable
2435  // runtime filters that guard the pre-barrier code.
2436  // Also add memory barrier for non volatile load from the referent field
2437  // to prevent commoning of loads across safepoint.
2438  if (!UseG1GC && !need_mem_bar)
2439    return;
2440
2441  // Some compile time checks.
2442
2443  // If offset is a constant, is it java_lang_ref_Reference::_reference_offset?
2444  const TypeX* otype = offset->find_intptr_t_type();
2445  if (otype != NULL && otype->is_con() &&
2446      otype->get_con() != java_lang_ref_Reference::referent_offset) {
2447    // Constant offset but not the reference_offset so just return
2448    return;
2449  }
2450
2451  // We only need to generate the runtime guards for instances.
2452  const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();
2453  if (btype != NULL) {
2454    if (btype->isa_aryptr()) {
2455      // Array type so nothing to do
2456      return;
2457    }
2458
2459    const TypeInstPtr* itype = btype->isa_instptr();
2460    if (itype != NULL) {
2461      // Can the klass of base_oop be statically determined to be
2462      // _not_ a sub-class of Reference and _not_ Object?
2463      ciKlass* klass = itype->klass();
2464      if ( klass->is_loaded() &&
2465          !klass->is_subtype_of(env()->Reference_klass()) &&
2466          !env()->Object_klass()->is_subtype_of(klass)) {
2467        return;
2468      }
2469    }
2470  }
2471
2472  // The compile time filters did not reject base_oop/offset so
2473  // we need to generate the following runtime filters
2474  //
2475  // if (offset == java_lang_ref_Reference::_reference_offset) {
2476  //   if (instance_of(base, java.lang.ref.Reference)) {
2477  //     pre_barrier(_, pre_val, ...);
2478  //   }
2479  // }
2480
2481  float likely   = PROB_LIKELY(  0.999);
2482  float unlikely = PROB_UNLIKELY(0.999);
2483
2484  IdealKit ideal(this);
2485#define __ ideal.
2486
2487  Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset);
2488
2489  __ if_then(offset, BoolTest::eq, referent_off, unlikely); {
2490      // Update graphKit memory and control from IdealKit.
2491      sync_kit(ideal);
2492
2493      Node* ref_klass_con = makecon(TypeKlassPtr::make(env()->Reference_klass()));
2494      Node* is_instof = gen_instanceof(base_oop, ref_klass_con);
2495
2496      // Update IdealKit memory and control from graphKit.
2497      __ sync_kit(this);
2498
2499      Node* one = __ ConI(1);
2500      // is_instof == 0 if base_oop == NULL
2501      __ if_then(is_instof, BoolTest::eq, one, unlikely); {
2502
2503        // Update graphKit from IdeakKit.
2504        sync_kit(ideal);
2505
2506        // Use the pre-barrier to record the value in the referent field
2507        pre_barrier(false /* do_load */,
2508                    __ ctrl(),
2509                    NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
2510                    pre_val /* pre_val */,
2511                    T_OBJECT);
2512        if (need_mem_bar) {
2513          // Add memory barrier to prevent commoning reads from this field
2514          // across safepoint since GC can change its value.
2515          insert_mem_bar(Op_MemBarCPUOrder);
2516        }
2517        // Update IdealKit from graphKit.
2518        __ sync_kit(this);
2519
2520      } __ end_if(); // _ref_type != ref_none
2521  } __ end_if(); // offset == referent_offset
2522
2523  // Final sync IdealKit and GraphKit.
2524  final_sync(ideal);
2525#undef __
2526}
2527
2528
2529// Interpret Unsafe.fieldOffset cookies correctly:
2530extern jlong Unsafe_field_offset_to_byte_offset(jlong field_offset);
2531
2532const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr) {
2533  // Attempt to infer a sharper value type from the offset and base type.
2534  ciKlass* sharpened_klass = NULL;
2535
2536  // See if it is an instance field, with an object type.
2537  if (alias_type->field() != NULL) {
2538    assert(!is_native_ptr, "native pointer op cannot use a java address");
2539    if (alias_type->field()->type()->is_klass()) {
2540      sharpened_klass = alias_type->field()->type()->as_klass();
2541    }
2542  }
2543
2544  // See if it is a narrow oop array.
2545  if (adr_type->isa_aryptr()) {
2546    if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2547      const TypeOopPtr *elem_type = adr_type->is_aryptr()->elem()->isa_oopptr();
2548      if (elem_type != NULL) {
2549        sharpened_klass = elem_type->klass();
2550      }
2551    }
2552  }
2553
2554  // The sharpened class might be unloaded if there is no class loader
2555  // contraint in place.
2556  if (sharpened_klass != NULL && sharpened_klass->is_loaded()) {
2557    const TypeOopPtr* tjp = TypeOopPtr::make_from_klass(sharpened_klass);
2558
2559#ifndef PRODUCT
2560    if (C->print_intrinsics() || C->print_inlining()) {
2561      tty->print("  from base type: ");  adr_type->dump();
2562      tty->print("  sharpened value: ");  tjp->dump();
2563    }
2564#endif
2565    // Sharpen the value type.
2566    return tjp;
2567  }
2568  return NULL;
2569}
2570
2571bool LibraryCallKit::inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile) {
2572  if (callee()->is_static())  return false;  // caller must have the capability!
2573
2574#ifndef PRODUCT
2575  {
2576    ResourceMark rm;
2577    // Check the signatures.
2578    ciSignature* sig = callee()->signature();
2579#ifdef ASSERT
2580    if (!is_store) {
2581      // Object getObject(Object base, int/long offset), etc.
2582      BasicType rtype = sig->return_type()->basic_type();
2583      if (rtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::getAddress_name())
2584          rtype = T_ADDRESS;  // it is really a C void*
2585      assert(rtype == type, "getter must return the expected value");
2586      if (!is_native_ptr) {
2587        assert(sig->count() == 2, "oop getter has 2 arguments");
2588        assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2589        assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2590      } else {
2591        assert(sig->count() == 1, "native getter has 1 argument");
2592        assert(sig->type_at(0)->basic_type() == T_LONG, "getter base is long");
2593      }
2594    } else {
2595      // void putObject(Object base, int/long offset, Object x), etc.
2596      assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2597      if (!is_native_ptr) {
2598        assert(sig->count() == 3, "oop putter has 3 arguments");
2599        assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2600        assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2601      } else {
2602        assert(sig->count() == 2, "native putter has 2 arguments");
2603        assert(sig->type_at(0)->basic_type() == T_LONG, "putter base is long");
2604      }
2605      BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2606      if (vtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::putAddress_name())
2607        vtype = T_ADDRESS;  // it is really a C void*
2608      assert(vtype == type, "putter must accept the expected value");
2609    }
2610#endif // ASSERT
2611 }
2612#endif //PRODUCT
2613
2614  C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2615
2616  Node* receiver = argument(0);  // type: oop
2617
2618  // Build address expression.
2619  Node* adr;
2620  Node* heap_base_oop = top();
2621  Node* offset = top();
2622  Node* val;
2623
2624  if (!is_native_ptr) {
2625    // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2626    Node* base = argument(1);  // type: oop
2627    // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2628    offset = argument(2);  // type: long
2629    // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2630    // to be plain byte offsets, which are also the same as those accepted
2631    // by oopDesc::field_base.
2632    assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2633           "fieldOffset must be byte-scaled");
2634    // 32-bit machines ignore the high half!
2635    offset = ConvL2X(offset);
2636    adr = make_unsafe_address(base, offset);
2637    heap_base_oop = base;
2638    val = is_store ? argument(4) : NULL;
2639  } else {
2640    Node* ptr = argument(1);  // type: long
2641    ptr = ConvL2X(ptr);  // adjust Java long to machine word
2642    adr = make_unsafe_address(NULL, ptr);
2643    val = is_store ? argument(3) : NULL;
2644  }
2645
2646  const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2647
2648  // First guess at the value type.
2649  const Type *value_type = Type::get_const_basic_type(type);
2650
2651  // Try to categorize the address.  If it comes up as TypeJavaPtr::BOTTOM,
2652  // there was not enough information to nail it down.
2653  Compile::AliasType* alias_type = C->alias_type(adr_type);
2654  assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2655
2656  // We will need memory barriers unless we can determine a unique
2657  // alias category for this reference.  (Note:  If for some reason
2658  // the barriers get omitted and the unsafe reference begins to "pollute"
2659  // the alias analysis of the rest of the graph, either Compile::can_alias
2660  // or Compile::must_alias will throw a diagnostic assert.)
2661  bool need_mem_bar = (alias_type->adr_type() == TypeOopPtr::BOTTOM);
2662
2663  // If we are reading the value of the referent field of a Reference
2664  // object (either by using Unsafe directly or through reflection)
2665  // then, if G1 is enabled, we need to record the referent in an
2666  // SATB log buffer using the pre-barrier mechanism.
2667  // Also we need to add memory barrier to prevent commoning reads
2668  // from this field across safepoint since GC can change its value.
2669  bool need_read_barrier = !is_native_ptr && !is_store &&
2670                           offset != top() && heap_base_oop != top();
2671
2672  if (!is_store && type == T_OBJECT) {
2673    const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type, is_native_ptr);
2674    if (tjp != NULL) {
2675      value_type = tjp;
2676    }
2677  }
2678
2679  receiver = null_check(receiver);
2680  if (stopped()) {
2681    return true;
2682  }
2683  // Heap pointers get a null-check from the interpreter,
2684  // as a courtesy.  However, this is not guaranteed by Unsafe,
2685  // and it is not possible to fully distinguish unintended nulls
2686  // from intended ones in this API.
2687
2688  if (is_volatile) {
2689    // We need to emit leading and trailing CPU membars (see below) in
2690    // addition to memory membars when is_volatile. This is a little
2691    // too strong, but avoids the need to insert per-alias-type
2692    // volatile membars (for stores; compare Parse::do_put_xxx), which
2693    // we cannot do effectively here because we probably only have a
2694    // rough approximation of type.
2695    need_mem_bar = true;
2696    // For Stores, place a memory ordering barrier now.
2697    if (is_store) {
2698      insert_mem_bar(Op_MemBarRelease);
2699    } else {
2700      if (support_IRIW_for_not_multiple_copy_atomic_cpu) {
2701        insert_mem_bar(Op_MemBarVolatile);
2702      }
2703    }
2704  }
2705
2706  // Memory barrier to prevent normal and 'unsafe' accesses from
2707  // bypassing each other.  Happens after null checks, so the
2708  // exception paths do not take memory state from the memory barrier,
2709  // so there's no problems making a strong assert about mixing users
2710  // of safe & unsafe memory.
2711  if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
2712
2713  if (!is_store) {
2714    MemNode::MemOrd mo = is_volatile ? MemNode::acquire : MemNode::unordered;
2715    // To be valid, unsafe loads may depend on other conditions than
2716    // the one that guards them: pin the Load node
2717    Node* p = make_load(control(), adr, value_type, type, adr_type, mo, LoadNode::Pinned, is_volatile);
2718    // load value
2719    switch (type) {
2720    case T_BOOLEAN:
2721    case T_CHAR:
2722    case T_BYTE:
2723    case T_SHORT:
2724    case T_INT:
2725    case T_LONG:
2726    case T_FLOAT:
2727    case T_DOUBLE:
2728      break;
2729    case T_OBJECT:
2730      if (need_read_barrier) {
2731        insert_pre_barrier(heap_base_oop, offset, p, !(is_volatile || need_mem_bar));
2732      }
2733      break;
2734    case T_ADDRESS:
2735      // Cast to an int type.
2736      p = _gvn.transform(new CastP2XNode(NULL, p));
2737      p = ConvX2UL(p);
2738      break;
2739    default:
2740      fatal(err_msg_res("unexpected type %d: %s", type, type2name(type)));
2741      break;
2742    }
2743    // The load node has the control of the preceding MemBarCPUOrder.  All
2744    // following nodes will have the control of the MemBarCPUOrder inserted at
2745    // the end of this method.  So, pushing the load onto the stack at a later
2746    // point is fine.
2747    set_result(p);
2748  } else {
2749    // place effect of store into memory
2750    switch (type) {
2751    case T_DOUBLE:
2752      val = dstore_rounding(val);
2753      break;
2754    case T_ADDRESS:
2755      // Repackage the long as a pointer.
2756      val = ConvL2X(val);
2757      val = _gvn.transform(new CastX2PNode(val));
2758      break;
2759    }
2760
2761    MemNode::MemOrd mo = is_volatile ? MemNode::release : MemNode::unordered;
2762    if (type != T_OBJECT ) {
2763      (void) store_to_memory(control(), adr, val, type, adr_type, mo, is_volatile);
2764    } else {
2765      // Possibly an oop being stored to Java heap or native memory
2766      if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(heap_base_oop))) {
2767        // oop to Java heap.
2768        (void) store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo);
2769      } else {
2770        // We can't tell at compile time if we are storing in the Java heap or outside
2771        // of it. So we need to emit code to conditionally do the proper type of
2772        // store.
2773
2774        IdealKit ideal(this);
2775#define __ ideal.
2776        // QQQ who knows what probability is here??
2777        __ if_then(heap_base_oop, BoolTest::ne, null(), PROB_UNLIKELY(0.999)); {
2778          // Sync IdealKit and graphKit.
2779          sync_kit(ideal);
2780          Node* st = store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo);
2781          // Update IdealKit memory.
2782          __ sync_kit(this);
2783        } __ else_(); {
2784          __ store(__ ctrl(), adr, val, type, alias_type->index(), mo, is_volatile);
2785        } __ end_if();
2786        // Final sync IdealKit and GraphKit.
2787        final_sync(ideal);
2788#undef __
2789      }
2790    }
2791  }
2792
2793  if (is_volatile) {
2794    if (!is_store) {
2795      insert_mem_bar(Op_MemBarAcquire);
2796    } else {
2797      if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {
2798        insert_mem_bar(Op_MemBarVolatile);
2799      }
2800    }
2801  }
2802
2803  if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
2804
2805  return true;
2806}
2807
2808//----------------------------inline_unsafe_load_store----------------------------
2809// This method serves a couple of different customers (depending on LoadStoreKind):
2810//
2811// LS_cmpxchg:
2812//   public final native boolean compareAndSwapObject(Object o, long offset, Object expected, Object x);
2813//   public final native boolean compareAndSwapInt(   Object o, long offset, int    expected, int    x);
2814//   public final native boolean compareAndSwapLong(  Object o, long offset, long   expected, long   x);
2815//
2816// LS_xadd:
2817//   public int  getAndAddInt( Object o, long offset, int  delta)
2818//   public long getAndAddLong(Object o, long offset, long delta)
2819//
2820// LS_xchg:
2821//   int    getAndSet(Object o, long offset, int    newValue)
2822//   long   getAndSet(Object o, long offset, long   newValue)
2823//   Object getAndSet(Object o, long offset, Object newValue)
2824//
2825bool LibraryCallKit::inline_unsafe_load_store(BasicType type, LoadStoreKind kind) {
2826  // This basic scheme here is the same as inline_unsafe_access, but
2827  // differs in enough details that combining them would make the code
2828  // overly confusing.  (This is a true fact! I originally combined
2829  // them, but even I was confused by it!) As much code/comments as
2830  // possible are retained from inline_unsafe_access though to make
2831  // the correspondences clearer. - dl
2832
2833  if (callee()->is_static())  return false;  // caller must have the capability!
2834
2835#ifndef PRODUCT
2836  BasicType rtype;
2837  {
2838    ResourceMark rm;
2839    // Check the signatures.
2840    ciSignature* sig = callee()->signature();
2841    rtype = sig->return_type()->basic_type();
2842    if (kind == LS_xadd || kind == LS_xchg) {
2843      // Check the signatures.
2844#ifdef ASSERT
2845      assert(rtype == type, "get and set must return the expected type");
2846      assert(sig->count() == 3, "get and set has 3 arguments");
2847      assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2848      assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2849      assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2850#endif // ASSERT
2851    } else if (kind == LS_cmpxchg) {
2852      // Check the signatures.
2853#ifdef ASSERT
2854      assert(rtype == T_BOOLEAN, "CAS must return boolean");
2855      assert(sig->count() == 4, "CAS has 4 arguments");
2856      assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2857      assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2858#endif // ASSERT
2859    } else {
2860      ShouldNotReachHere();
2861    }
2862  }
2863#endif //PRODUCT
2864
2865  C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2866
2867  // Get arguments:
2868  Node* receiver = NULL;
2869  Node* base     = NULL;
2870  Node* offset   = NULL;
2871  Node* oldval   = NULL;
2872  Node* newval   = NULL;
2873  if (kind == LS_cmpxchg) {
2874    const bool two_slot_type = type2size[type] == 2;
2875    receiver = argument(0);  // type: oop
2876    base     = argument(1);  // type: oop
2877    offset   = argument(2);  // type: long
2878    oldval   = argument(4);  // type: oop, int, or long
2879    newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
2880  } else if (kind == LS_xadd || kind == LS_xchg){
2881    receiver = argument(0);  // type: oop
2882    base     = argument(1);  // type: oop
2883    offset   = argument(2);  // type: long
2884    oldval   = NULL;
2885    newval   = argument(4);  // type: oop, int, or long
2886  }
2887
2888  // Null check receiver.
2889  receiver = null_check(receiver);
2890  if (stopped()) {
2891    return true;
2892  }
2893
2894  // Build field offset expression.
2895  // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2896  // to be plain byte offsets, which are also the same as those accepted
2897  // by oopDesc::field_base.
2898  assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2899  // 32-bit machines ignore the high half of long offsets
2900  offset = ConvL2X(offset);
2901  Node* adr = make_unsafe_address(base, offset);
2902  const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2903
2904  // For CAS, unlike inline_unsafe_access, there seems no point in
2905  // trying to refine types. Just use the coarse types here.
2906  const Type *value_type = Type::get_const_basic_type(type);
2907  Compile::AliasType* alias_type = C->alias_type(adr_type);
2908  assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2909
2910  if (kind == LS_xchg && type == T_OBJECT) {
2911    const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2912    if (tjp != NULL) {
2913      value_type = tjp;
2914    }
2915  }
2916
2917  int alias_idx = C->get_alias_index(adr_type);
2918
2919  // Memory-model-wise, a LoadStore acts like a little synchronized
2920  // block, so needs barriers on each side.  These don't translate
2921  // into actual barriers on most machines, but we still need rest of
2922  // compiler to respect ordering.
2923
2924  insert_mem_bar(Op_MemBarRelease);
2925  insert_mem_bar(Op_MemBarCPUOrder);
2926
2927  // 4984716: MemBars must be inserted before this
2928  //          memory node in order to avoid a false
2929  //          dependency which will confuse the scheduler.
2930  Node *mem = memory(alias_idx);
2931
2932  // For now, we handle only those cases that actually exist: ints,
2933  // longs, and Object. Adding others should be straightforward.
2934  Node* load_store;
2935  switch(type) {
2936  case T_INT:
2937    if (kind == LS_xadd) {
2938      load_store = _gvn.transform(new GetAndAddINode(control(), mem, adr, newval, adr_type));
2939    } else if (kind == LS_xchg) {
2940      load_store = _gvn.transform(new GetAndSetINode(control(), mem, adr, newval, adr_type));
2941    } else if (kind == LS_cmpxchg) {
2942      load_store = _gvn.transform(new CompareAndSwapINode(control(), mem, adr, newval, oldval));
2943    } else {
2944      ShouldNotReachHere();
2945    }
2946    break;
2947  case T_LONG:
2948    if (kind == LS_xadd) {
2949      load_store = _gvn.transform(new GetAndAddLNode(control(), mem, adr, newval, adr_type));
2950    } else if (kind == LS_xchg) {
2951      load_store = _gvn.transform(new GetAndSetLNode(control(), mem, adr, newval, adr_type));
2952    } else if (kind == LS_cmpxchg) {
2953      load_store = _gvn.transform(new CompareAndSwapLNode(control(), mem, adr, newval, oldval));
2954    } else {
2955      ShouldNotReachHere();
2956    }
2957    break;
2958  case T_OBJECT:
2959    // Transformation of a value which could be NULL pointer (CastPP #NULL)
2960    // could be delayed during Parse (for example, in adjust_map_after_if()).
2961    // Execute transformation here to avoid barrier generation in such case.
2962    if (_gvn.type(newval) == TypePtr::NULL_PTR)
2963      newval = _gvn.makecon(TypePtr::NULL_PTR);
2964
2965    // Reference stores need a store barrier.
2966    if (kind == LS_xchg) {
2967      // If pre-barrier must execute before the oop store, old value will require do_load here.
2968      if (!can_move_pre_barrier()) {
2969        pre_barrier(true /* do_load*/,
2970                    control(), base, adr, alias_idx, newval, value_type->make_oopptr(),
2971                    NULL /* pre_val*/,
2972                    T_OBJECT);
2973      } // Else move pre_barrier to use load_store value, see below.
2974    } else if (kind == LS_cmpxchg) {
2975      // Same as for newval above:
2976      if (_gvn.type(oldval) == TypePtr::NULL_PTR) {
2977        oldval = _gvn.makecon(TypePtr::NULL_PTR);
2978      }
2979      // The only known value which might get overwritten is oldval.
2980      pre_barrier(false /* do_load */,
2981                  control(), NULL, NULL, max_juint, NULL, NULL,
2982                  oldval /* pre_val */,
2983                  T_OBJECT);
2984    } else {
2985      ShouldNotReachHere();
2986    }
2987
2988#ifdef _LP64
2989    if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2990      Node *newval_enc = _gvn.transform(new EncodePNode(newval, newval->bottom_type()->make_narrowoop()));
2991      if (kind == LS_xchg) {
2992        load_store = _gvn.transform(new GetAndSetNNode(control(), mem, adr,
2993                                                       newval_enc, adr_type, value_type->make_narrowoop()));
2994      } else {
2995        assert(kind == LS_cmpxchg, "wrong LoadStore operation");
2996        Node *oldval_enc = _gvn.transform(new EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
2997        load_store = _gvn.transform(new CompareAndSwapNNode(control(), mem, adr,
2998                                                                newval_enc, oldval_enc));
2999      }
3000    } else
3001#endif
3002    {
3003      if (kind == LS_xchg) {
3004        load_store = _gvn.transform(new GetAndSetPNode(control(), mem, adr, newval, adr_type, value_type->is_oopptr()));
3005      } else {
3006        assert(kind == LS_cmpxchg, "wrong LoadStore operation");
3007        load_store = _gvn.transform(new CompareAndSwapPNode(control(), mem, adr, newval, oldval));
3008      }
3009    }
3010    post_barrier(control(), load_store, base, adr, alias_idx, newval, T_OBJECT, true);
3011    break;
3012  default:
3013    fatal(err_msg_res("unexpected type %d: %s", type, type2name(type)));
3014    break;
3015  }
3016
3017  // SCMemProjNodes represent the memory state of a LoadStore. Their
3018  // main role is to prevent LoadStore nodes from being optimized away
3019  // when their results aren't used.
3020  Node* proj = _gvn.transform(new SCMemProjNode(load_store));
3021  set_memory(proj, alias_idx);
3022
3023  if (type == T_OBJECT && kind == LS_xchg) {
3024#ifdef _LP64
3025    if (adr->bottom_type()->is_ptr_to_narrowoop()) {
3026      load_store = _gvn.transform(new DecodeNNode(load_store, load_store->get_ptr_type()));
3027    }
3028#endif
3029    if (can_move_pre_barrier()) {
3030      // Don't need to load pre_val. The old value is returned by load_store.
3031      // The pre_barrier can execute after the xchg as long as no safepoint
3032      // gets inserted between them.
3033      pre_barrier(false /* do_load */,
3034                  control(), NULL, NULL, max_juint, NULL, NULL,
3035                  load_store /* pre_val */,
3036                  T_OBJECT);
3037    }
3038  }
3039
3040  // Add the trailing membar surrounding the access
3041  insert_mem_bar(Op_MemBarCPUOrder);
3042  insert_mem_bar(Op_MemBarAcquire);
3043
3044  assert(type2size[load_store->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3045  set_result(load_store);
3046  return true;
3047}
3048
3049//----------------------------inline_unsafe_ordered_store----------------------
3050// public native void sun.misc.Unsafe.putOrderedObject(Object o, long offset, Object x);
3051// public native void sun.misc.Unsafe.putOrderedInt(Object o, long offset, int x);
3052// public native void sun.misc.Unsafe.putOrderedLong(Object o, long offset, long x);
3053bool LibraryCallKit::inline_unsafe_ordered_store(BasicType type) {
3054  // This is another variant of inline_unsafe_access, differing in
3055  // that it always issues store-store ("release") barrier and ensures
3056  // store-atomicity (which only matters for "long").
3057
3058  if (callee()->is_static())  return false;  // caller must have the capability!
3059
3060#ifndef PRODUCT
3061  {
3062    ResourceMark rm;
3063    // Check the signatures.
3064    ciSignature* sig = callee()->signature();
3065#ifdef ASSERT
3066    BasicType rtype = sig->return_type()->basic_type();
3067    assert(rtype == T_VOID, "must return void");
3068    assert(sig->count() == 3, "has 3 arguments");
3069    assert(sig->type_at(0)->basic_type() == T_OBJECT, "base is object");
3070    assert(sig->type_at(1)->basic_type() == T_LONG, "offset is long");
3071#endif // ASSERT
3072  }
3073#endif //PRODUCT
3074
3075  C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
3076
3077  // Get arguments:
3078  Node* receiver = argument(0);  // type: oop
3079  Node* base     = argument(1);  // type: oop
3080  Node* offset   = argument(2);  // type: long
3081  Node* val      = argument(4);  // type: oop, int, or long
3082
3083  // Null check receiver.
3084  receiver = null_check(receiver);
3085  if (stopped()) {
3086    return true;
3087  }
3088
3089  // Build field offset expression.
3090  assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
3091  // 32-bit machines ignore the high half of long offsets
3092  offset = ConvL2X(offset);
3093  Node* adr = make_unsafe_address(base, offset);
3094  const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
3095  const Type *value_type = Type::get_const_basic_type(type);
3096  Compile::AliasType* alias_type = C->alias_type(adr_type);
3097
3098  insert_mem_bar(Op_MemBarRelease);
3099  insert_mem_bar(Op_MemBarCPUOrder);
3100  // Ensure that the store is atomic for longs:
3101  const bool require_atomic_access = true;
3102  Node* store;
3103  if (type == T_OBJECT) // reference stores need a store barrier.
3104    store = store_oop_to_unknown(control(), base, adr, adr_type, val, type, MemNode::release);
3105  else {
3106    store = store_to_memory(control(), adr, val, type, adr_type, MemNode::release, require_atomic_access);
3107  }
3108  insert_mem_bar(Op_MemBarCPUOrder);
3109  return true;
3110}
3111
3112bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3113  // Regardless of form, don't allow previous ld/st to move down,
3114  // then issue acquire, release, or volatile mem_bar.
3115  insert_mem_bar(Op_MemBarCPUOrder);
3116  switch(id) {
3117    case vmIntrinsics::_loadFence:
3118      insert_mem_bar(Op_LoadFence);
3119      return true;
3120    case vmIntrinsics::_storeFence:
3121      insert_mem_bar(Op_StoreFence);
3122      return true;
3123    case vmIntrinsics::_fullFence:
3124      insert_mem_bar(Op_MemBarVolatile);
3125      return true;
3126    default:
3127      fatal_unexpected_iid(id);
3128      return false;
3129  }
3130}
3131
3132bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3133  if (!kls->is_Con()) {
3134    return true;
3135  }
3136  const TypeKlassPtr* klsptr = kls->bottom_type()->isa_klassptr();
3137  if (klsptr == NULL) {
3138    return true;
3139  }
3140  ciInstanceKlass* ik = klsptr->klass()->as_instance_klass();
3141  // don't need a guard for a klass that is already initialized
3142  return !ik->is_initialized();
3143}
3144
3145//----------------------------inline_unsafe_allocate---------------------------
3146// public native Object sun.misc.Unsafe.allocateInstance(Class<?> cls);
3147bool LibraryCallKit::inline_unsafe_allocate() {
3148  if (callee()->is_static())  return false;  // caller must have the capability!
3149
3150  null_check_receiver();  // null-check, then ignore
3151  Node* cls = null_check(argument(1));
3152  if (stopped())  return true;
3153
3154  Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
3155  kls = null_check(kls);
3156  if (stopped())  return true;  // argument was like int.class
3157
3158  Node* test = NULL;
3159  if (LibraryCallKit::klass_needs_init_guard(kls)) {
3160    // Note:  The argument might still be an illegal value like
3161    // Serializable.class or Object[].class.   The runtime will handle it.
3162    // But we must make an explicit check for initialization.
3163    Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3164    // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3165    // can generate code to load it as unsigned byte.
3166    Node* inst = make_load(NULL, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::unordered);
3167    Node* bits = intcon(InstanceKlass::fully_initialized);
3168    test = _gvn.transform(new SubINode(inst, bits));
3169    // The 'test' is non-zero if we need to take a slow path.
3170  }
3171
3172  Node* obj = new_instance(kls, test);
3173  set_result(obj);
3174  return true;
3175}
3176
3177#ifdef TRACE_HAVE_INTRINSICS
3178/*
3179 * oop -> myklass
3180 * myklass->trace_id |= USED
3181 * return myklass->trace_id & ~0x3
3182 */
3183bool LibraryCallKit::inline_native_classID() {
3184  null_check_receiver();  // null-check, then ignore
3185  Node* cls = null_check(argument(1), T_OBJECT);
3186  Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
3187  kls = null_check(kls, T_OBJECT);
3188  ByteSize offset = TRACE_ID_OFFSET;
3189  Node* insp = basic_plus_adr(kls, in_bytes(offset));
3190  Node* tvalue = make_load(NULL, insp, TypeLong::LONG, T_LONG, MemNode::unordered);
3191  Node* bits = longcon(~0x03l); // ignore bit 0 & 1
3192  Node* andl = _gvn.transform(new AndLNode(tvalue, bits));
3193  Node* clsused = longcon(0x01l); // set the class bit
3194  Node* orl = _gvn.transform(new OrLNode(tvalue, clsused));
3195
3196  const TypePtr *adr_type = _gvn.type(insp)->isa_ptr();
3197  store_to_memory(control(), insp, orl, T_LONG, adr_type, MemNode::unordered);
3198  set_result(andl);
3199  return true;
3200}
3201
3202bool LibraryCallKit::inline_native_threadID() {
3203  Node* tls_ptr = NULL;
3204  Node* cur_thr = generate_current_thread(tls_ptr);
3205  Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
3206  Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3207  p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::thread_id_offset()));
3208
3209  Node* threadid = NULL;
3210  size_t thread_id_size = OSThread::thread_id_size();
3211  if (thread_id_size == (size_t) BytesPerLong) {
3212    threadid = ConvL2I(make_load(control(), p, TypeLong::LONG, T_LONG, MemNode::unordered));
3213  } else if (thread_id_size == (size_t) BytesPerInt) {
3214    threadid = make_load(control(), p, TypeInt::INT, T_INT, MemNode::unordered);
3215  } else {
3216    ShouldNotReachHere();
3217  }
3218  set_result(threadid);
3219  return true;
3220}
3221#endif
3222
3223//------------------------inline_native_time_funcs--------------
3224// inline code for System.currentTimeMillis() and System.nanoTime()
3225// these have the same type and signature
3226bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3227  const TypeFunc* tf = OptoRuntime::void_long_Type();
3228  const TypePtr* no_memory_effects = NULL;
3229  Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3230  Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3231#ifdef ASSERT
3232  Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3233  assert(value_top == top(), "second value must be top");
3234#endif
3235  set_result(value);
3236  return true;
3237}
3238
3239//------------------------inline_native_currentThread------------------
3240bool LibraryCallKit::inline_native_currentThread() {
3241  Node* junk = NULL;
3242  set_result(generate_current_thread(junk));
3243  return true;
3244}
3245
3246//------------------------inline_native_isInterrupted------------------
3247// private native boolean java.lang.Thread.isInterrupted(boolean ClearInterrupted);
3248bool LibraryCallKit::inline_native_isInterrupted() {
3249  // Add a fast path to t.isInterrupted(clear_int):
3250  //   (t == Thread.current() &&
3251  //    (!TLS._osthread._interrupted || WINDOWS_ONLY(false) NOT_WINDOWS(!clear_int)))
3252  //   ? TLS._osthread._interrupted : /*slow path:*/ t.isInterrupted(clear_int)
3253  // So, in the common case that the interrupt bit is false,
3254  // we avoid making a call into the VM.  Even if the interrupt bit
3255  // is true, if the clear_int argument is false, we avoid the VM call.
3256  // However, if the receiver is not currentThread, we must call the VM,
3257  // because there must be some locking done around the operation.
3258
3259  // We only go to the fast case code if we pass two guards.
3260  // Paths which do not pass are accumulated in the slow_region.
3261
3262  enum {
3263    no_int_result_path   = 1, // t == Thread.current() && !TLS._osthread._interrupted
3264    no_clear_result_path = 2, // t == Thread.current() &&  TLS._osthread._interrupted && !clear_int
3265    slow_result_path     = 3, // slow path: t.isInterrupted(clear_int)
3266    PATH_LIMIT
3267  };
3268
3269  // Ensure that it's not possible to move the load of TLS._osthread._interrupted flag
3270  // out of the function.
3271  insert_mem_bar(Op_MemBarCPUOrder);
3272
3273  RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3274  PhiNode*    result_val = new PhiNode(result_rgn, TypeInt::BOOL);
3275
3276  RegionNode* slow_region = new RegionNode(1);
3277  record_for_igvn(slow_region);
3278
3279  // (a) Receiving thread must be the current thread.
3280  Node* rec_thr = argument(0);
3281  Node* tls_ptr = NULL;
3282  Node* cur_thr = generate_current_thread(tls_ptr);
3283  Node* cmp_thr = _gvn.transform(new CmpPNode(cur_thr, rec_thr));
3284  Node* bol_thr = _gvn.transform(new BoolNode(cmp_thr, BoolTest::ne));
3285
3286  generate_slow_guard(bol_thr, slow_region);
3287
3288  // (b) Interrupt bit on TLS must be false.
3289  Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
3290  Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3291  p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::interrupted_offset()));
3292
3293  // Set the control input on the field _interrupted read to prevent it floating up.
3294  Node* int_bit = make_load(control(), p, TypeInt::BOOL, T_INT, MemNode::unordered);
3295  Node* cmp_bit = _gvn.transform(new CmpINode(int_bit, intcon(0)));
3296  Node* bol_bit = _gvn.transform(new BoolNode(cmp_bit, BoolTest::ne));
3297
3298  IfNode* iff_bit = create_and_map_if(control(), bol_bit, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
3299
3300  // First fast path:  if (!TLS._interrupted) return false;
3301  Node* false_bit = _gvn.transform(new IfFalseNode(iff_bit));
3302  result_rgn->init_req(no_int_result_path, false_bit);
3303  result_val->init_req(no_int_result_path, intcon(0));
3304
3305  // drop through to next case
3306  set_control( _gvn.transform(new IfTrueNode(iff_bit)));
3307
3308#ifndef TARGET_OS_FAMILY_windows
3309  // (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path.
3310  Node* clr_arg = argument(1);
3311  Node* cmp_arg = _gvn.transform(new CmpINode(clr_arg, intcon(0)));
3312  Node* bol_arg = _gvn.transform(new BoolNode(cmp_arg, BoolTest::ne));
3313  IfNode* iff_arg = create_and_map_if(control(), bol_arg, PROB_FAIR, COUNT_UNKNOWN);
3314
3315  // Second fast path:  ... else if (!clear_int) return true;
3316  Node* false_arg = _gvn.transform(new IfFalseNode(iff_arg));
3317  result_rgn->init_req(no_clear_result_path, false_arg);
3318  result_val->init_req(no_clear_result_path, intcon(1));
3319
3320  // drop through to next case
3321  set_control( _gvn.transform(new IfTrueNode(iff_arg)));
3322#else
3323  // To return true on Windows you must read the _interrupted field
3324  // and check the the event state i.e. take the slow path.
3325#endif // TARGET_OS_FAMILY_windows
3326
3327  // (d) Otherwise, go to the slow path.
3328  slow_region->add_req(control());
3329  set_control( _gvn.transform(slow_region));
3330
3331  if (stopped()) {
3332    // There is no slow path.
3333    result_rgn->init_req(slow_result_path, top());
3334    result_val->init_req(slow_result_path, top());
3335  } else {
3336    // non-virtual because it is a private non-static
3337    CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_isInterrupted);
3338
3339    Node* slow_val = set_results_for_java_call(slow_call);
3340    // this->control() comes from set_results_for_java_call
3341
3342    Node* fast_io  = slow_call->in(TypeFunc::I_O);
3343    Node* fast_mem = slow_call->in(TypeFunc::Memory);
3344
3345    // These two phis are pre-filled with copies of of the fast IO and Memory
3346    PhiNode* result_mem  = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
3347    PhiNode* result_io   = PhiNode::make(result_rgn, fast_io,  Type::ABIO);
3348
3349    result_rgn->init_req(slow_result_path, control());
3350    result_io ->init_req(slow_result_path, i_o());
3351    result_mem->init_req(slow_result_path, reset_memory());
3352    result_val->init_req(slow_result_path, slow_val);
3353
3354    set_all_memory(_gvn.transform(result_mem));
3355    set_i_o(       _gvn.transform(result_io));
3356  }
3357
3358  C->set_has_split_ifs(true); // Has chance for split-if optimization
3359  set_result(result_rgn, result_val);
3360  return true;
3361}
3362
3363//---------------------------load_mirror_from_klass----------------------------
3364// Given a klass oop, load its java mirror (a java.lang.Class oop).
3365Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
3366  Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
3367  return make_load(NULL, p, TypeInstPtr::MIRROR, T_OBJECT, MemNode::unordered);
3368}
3369
3370//-----------------------load_klass_from_mirror_common-------------------------
3371// Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
3372// Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
3373// and branch to the given path on the region.
3374// If never_see_null, take an uncommon trap on null, so we can optimistically
3375// compile for the non-null case.
3376// If the region is NULL, force never_see_null = true.
3377Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
3378                                                    bool never_see_null,
3379                                                    RegionNode* region,
3380                                                    int null_path,
3381                                                    int offset) {
3382  if (region == NULL)  never_see_null = true;
3383  Node* p = basic_plus_adr(mirror, offset);
3384  const TypeKlassPtr*  kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3385  Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
3386  Node* null_ctl = top();
3387  kls = null_check_oop(kls, &null_ctl, never_see_null);
3388  if (region != NULL) {
3389    // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
3390    region->init_req(null_path, null_ctl);
3391  } else {
3392    assert(null_ctl == top(), "no loose ends");
3393  }
3394  return kls;
3395}
3396
3397//--------------------(inline_native_Class_query helpers)---------------------
3398// Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE, JVM_ACC_HAS_FINALIZER.
3399// Fall through if (mods & mask) == bits, take the guard otherwise.
3400Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
3401  // Branch around if the given klass has the given modifier bit set.
3402  // Like generate_guard, adds a new path onto the region.
3403  Node* modp = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3404  Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT, MemNode::unordered);
3405  Node* mask = intcon(modifier_mask);
3406  Node* bits = intcon(modifier_bits);
3407  Node* mbit = _gvn.transform(new AndINode(mods, mask));
3408  Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
3409  Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3410  return generate_fair_guard(bol, region);
3411}
3412Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
3413  return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);
3414}
3415
3416//-------------------------inline_native_Class_query-------------------
3417bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
3418  const Type* return_type = TypeInt::BOOL;
3419  Node* prim_return_value = top();  // what happens if it's a primitive class?
3420  bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3421  bool expect_prim = false;     // most of these guys expect to work on refs
3422
3423  enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
3424
3425  Node* mirror = argument(0);
3426  Node* obj    = top();
3427
3428  switch (id) {
3429  case vmIntrinsics::_isInstance:
3430    // nothing is an instance of a primitive type
3431    prim_return_value = intcon(0);
3432    obj = argument(1);
3433    break;
3434  case vmIntrinsics::_getModifiers:
3435    prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3436    assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");
3437    return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);
3438    break;
3439  case vmIntrinsics::_isInterface:
3440    prim_return_value = intcon(0);
3441    break;
3442  case vmIntrinsics::_isArray:
3443    prim_return_value = intcon(0);
3444    expect_prim = true;  // cf. ObjectStreamClass.getClassSignature
3445    break;
3446  case vmIntrinsics::_isPrimitive:
3447    prim_return_value = intcon(1);
3448    expect_prim = true;  // obviously
3449    break;
3450  case vmIntrinsics::_getSuperclass:
3451    prim_return_value = null();
3452    return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
3453    break;
3454  case vmIntrinsics::_getClassAccessFlags:
3455    prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3456    return_type = TypeInt::INT;  // not bool!  6297094
3457    break;
3458  default:
3459    fatal_unexpected_iid(id);
3460    break;
3461  }
3462
3463  const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3464  if (mirror_con == NULL)  return false;  // cannot happen?
3465
3466#ifndef PRODUCT
3467  if (C->print_intrinsics() || C->print_inlining()) {
3468    ciType* k = mirror_con->java_mirror_type();
3469    if (k) {
3470      tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
3471      k->print_name();
3472      tty->cr();
3473    }
3474  }
3475#endif
3476
3477  // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
3478  RegionNode* region = new RegionNode(PATH_LIMIT);
3479  record_for_igvn(region);
3480  PhiNode* phi = new PhiNode(region, return_type);
3481
3482  // The mirror will never be null of Reflection.getClassAccessFlags, however
3483  // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
3484  // if it is. See bug 4774291.
3485
3486  // For Reflection.getClassAccessFlags(), the null check occurs in
3487  // the wrong place; see inline_unsafe_access(), above, for a similar
3488  // situation.
3489  mirror = null_check(mirror);
3490  // If mirror or obj is dead, only null-path is taken.
3491  if (stopped())  return true;
3492
3493  if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
3494
3495  // Now load the mirror's klass metaobject, and null-check it.
3496  // Side-effects region with the control path if the klass is null.
3497  Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
3498  // If kls is null, we have a primitive mirror.
3499  phi->init_req(_prim_path, prim_return_value);
3500  if (stopped()) { set_result(region, phi); return true; }
3501  bool safe_for_replace = (region->in(_prim_path) == top());
3502
3503  Node* p;  // handy temp
3504  Node* null_ctl;
3505
3506  // Now that we have the non-null klass, we can perform the real query.
3507  // For constant classes, the query will constant-fold in LoadNode::Value.
3508  Node* query_value = top();
3509  switch (id) {
3510  case vmIntrinsics::_isInstance:
3511    // nothing is an instance of a primitive type
3512    query_value = gen_instanceof(obj, kls, safe_for_replace);
3513    break;
3514
3515  case vmIntrinsics::_getModifiers:
3516    p = basic_plus_adr(kls, in_bytes(Klass::modifier_flags_offset()));
3517    query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
3518    break;
3519
3520  case vmIntrinsics::_isInterface:
3521    // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3522    if (generate_interface_guard(kls, region) != NULL)
3523      // A guard was added.  If the guard is taken, it was an interface.
3524      phi->add_req(intcon(1));
3525    // If we fall through, it's a plain class.
3526    query_value = intcon(0);
3527    break;
3528
3529  case vmIntrinsics::_isArray:
3530    // (To verify this code sequence, check the asserts in JVM_IsArrayClass.)
3531    if (generate_array_guard(kls, region) != NULL)
3532      // A guard was added.  If the guard is taken, it was an array.
3533      phi->add_req(intcon(1));
3534    // If we fall through, it's a plain class.
3535    query_value = intcon(0);
3536    break;
3537
3538  case vmIntrinsics::_isPrimitive:
3539    query_value = intcon(0); // "normal" path produces false
3540    break;
3541
3542  case vmIntrinsics::_getSuperclass:
3543    // The rules here are somewhat unfortunate, but we can still do better
3544    // with random logic than with a JNI call.
3545    // Interfaces store null or Object as _super, but must report null.
3546    // Arrays store an intermediate super as _super, but must report Object.
3547    // Other types can report the actual _super.
3548    // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3549    if (generate_interface_guard(kls, region) != NULL)
3550      // A guard was added.  If the guard is taken, it was an interface.
3551      phi->add_req(null());
3552    if (generate_array_guard(kls, region) != NULL)
3553      // A guard was added.  If the guard is taken, it was an array.
3554      phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
3555    // If we fall through, it's a plain class.  Get its _super.
3556    p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
3557    kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL));
3558    null_ctl = top();
3559    kls = null_check_oop(kls, &null_ctl);
3560    if (null_ctl != top()) {
3561      // If the guard is taken, Object.superClass is null (both klass and mirror).
3562      region->add_req(null_ctl);
3563      phi   ->add_req(null());
3564    }
3565    if (!stopped()) {
3566      query_value = load_mirror_from_klass(kls);
3567    }
3568    break;
3569
3570  case vmIntrinsics::_getClassAccessFlags:
3571    p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3572    query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
3573    break;
3574
3575  default:
3576    fatal_unexpected_iid(id);
3577    break;
3578  }
3579
3580  // Fall-through is the normal case of a query to a real class.
3581  phi->init_req(1, query_value);
3582  region->init_req(1, control());
3583
3584  C->set_has_split_ifs(true); // Has chance for split-if optimization
3585  set_result(region, phi);
3586  return true;
3587}
3588
3589//-------------------------inline_Class_cast-------------------
3590bool LibraryCallKit::inline_Class_cast() {
3591  Node* mirror = argument(0); // Class
3592  Node* obj    = argument(1);
3593  const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3594  if (mirror_con == NULL) {
3595    return false;  // dead path (mirror->is_top()).
3596  }
3597  if (obj == NULL || obj->is_top()) {
3598    return false;  // dead path
3599  }
3600  const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
3601
3602  // First, see if Class.cast() can be folded statically.
3603  // java_mirror_type() returns non-null for compile-time Class constants.
3604  ciType* tm = mirror_con->java_mirror_type();
3605  if (tm != NULL && tm->is_klass() &&
3606      tp != NULL && tp->klass() != NULL) {
3607    if (!tp->klass()->is_loaded()) {
3608      // Don't use intrinsic when class is not loaded.
3609      return false;
3610    } else {
3611      int static_res = C->static_subtype_check(tm->as_klass(), tp->klass());
3612      if (static_res == Compile::SSC_always_true) {
3613        // isInstance() is true - fold the code.
3614        set_result(obj);
3615        return true;
3616      } else if (static_res == Compile::SSC_always_false) {
3617        // Don't use intrinsic, have to throw ClassCastException.
3618        // If the reference is null, the non-intrinsic bytecode will
3619        // be optimized appropriately.
3620        return false;
3621      }
3622    }
3623  }
3624
3625  // Bailout intrinsic and do normal inlining if exception path is frequent.
3626  if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3627    return false;
3628  }
3629
3630  // Generate dynamic checks.
3631  // Class.cast() is java implementation of _checkcast bytecode.
3632  // Do checkcast (Parse::do_checkcast()) optimizations here.
3633
3634  mirror = null_check(mirror);
3635  // If mirror is dead, only null-path is taken.
3636  if (stopped()) {
3637    return true;
3638  }
3639
3640  // Not-subtype or the mirror's klass ptr is NULL (in case it is a primitive).
3641  enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
3642  RegionNode* region = new RegionNode(PATH_LIMIT);
3643  record_for_igvn(region);
3644
3645  // Now load the mirror's klass metaobject, and null-check it.
3646  // If kls is null, we have a primitive mirror and
3647  // nothing is an instance of a primitive type.
3648  Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
3649
3650  Node* res = top();
3651  if (!stopped()) {
3652    Node* bad_type_ctrl = top();
3653    // Do checkcast optimizations.
3654    res = gen_checkcast(obj, kls, &bad_type_ctrl);
3655    region->init_req(_bad_type_path, bad_type_ctrl);
3656  }
3657  if (region->in(_prim_path) != top() ||
3658      region->in(_bad_type_path) != top()) {
3659    // Let Interpreter throw ClassCastException.
3660    PreserveJVMState pjvms(this);
3661    set_control(_gvn.transform(region));
3662    uncommon_trap(Deoptimization::Reason_intrinsic,
3663                  Deoptimization::Action_maybe_recompile);
3664  }
3665  if (!stopped()) {
3666    set_result(res);
3667  }
3668  return true;
3669}
3670
3671
3672//--------------------------inline_native_subtype_check------------------------
3673// This intrinsic takes the JNI calls out of the heart of
3674// UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
3675bool LibraryCallKit::inline_native_subtype_check() {
3676  // Pull both arguments off the stack.
3677  Node* args[2];                // two java.lang.Class mirrors: superc, subc
3678  args[0] = argument(0);
3679  args[1] = argument(1);
3680  Node* klasses[2];             // corresponding Klasses: superk, subk
3681  klasses[0] = klasses[1] = top();
3682
3683  enum {
3684    // A full decision tree on {superc is prim, subc is prim}:
3685    _prim_0_path = 1,           // {P,N} => false
3686                                // {P,P} & superc!=subc => false
3687    _prim_same_path,            // {P,P} & superc==subc => true
3688    _prim_1_path,               // {N,P} => false
3689    _ref_subtype_path,          // {N,N} & subtype check wins => true
3690    _both_ref_path,             // {N,N} & subtype check loses => false
3691    PATH_LIMIT
3692  };
3693
3694  RegionNode* region = new RegionNode(PATH_LIMIT);
3695  Node*       phi    = new PhiNode(region, TypeInt::BOOL);
3696  record_for_igvn(region);
3697
3698  const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
3699  const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3700  int class_klass_offset = java_lang_Class::klass_offset_in_bytes();
3701
3702  // First null-check both mirrors and load each mirror's klass metaobject.
3703  int which_arg;
3704  for (which_arg = 0; which_arg <= 1; which_arg++) {
3705    Node* arg = args[which_arg];
3706    arg = null_check(arg);
3707    if (stopped())  break;
3708    args[which_arg] = arg;
3709
3710    Node* p = basic_plus_adr(arg, class_klass_offset);
3711    Node* kls = LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, adr_type, kls_type);
3712    klasses[which_arg] = _gvn.transform(kls);
3713  }
3714
3715  // Having loaded both klasses, test each for null.
3716  bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3717  for (which_arg = 0; which_arg <= 1; which_arg++) {
3718    Node* kls = klasses[which_arg];
3719    Node* null_ctl = top();
3720    kls = null_check_oop(kls, &null_ctl, never_see_null);
3721    int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
3722    region->init_req(prim_path, null_ctl);
3723    if (stopped())  break;
3724    klasses[which_arg] = kls;
3725  }
3726
3727  if (!stopped()) {
3728    // now we have two reference types, in klasses[0..1]
3729    Node* subk   = klasses[1];  // the argument to isAssignableFrom
3730    Node* superk = klasses[0];  // the receiver
3731    region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
3732    // now we have a successful reference subtype check
3733    region->set_req(_ref_subtype_path, control());
3734  }
3735
3736  // If both operands are primitive (both klasses null), then
3737  // we must return true when they are identical primitives.
3738  // It is convenient to test this after the first null klass check.
3739  set_control(region->in(_prim_0_path)); // go back to first null check
3740  if (!stopped()) {
3741    // Since superc is primitive, make a guard for the superc==subc case.
3742    Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
3743    Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
3744    generate_guard(bol_eq, region, PROB_FAIR);
3745    if (region->req() == PATH_LIMIT+1) {
3746      // A guard was added.  If the added guard is taken, superc==subc.
3747      region->swap_edges(PATH_LIMIT, _prim_same_path);
3748      region->del_req(PATH_LIMIT);
3749    }
3750    region->set_req(_prim_0_path, control()); // Not equal after all.
3751  }
3752
3753  // these are the only paths that produce 'true':
3754  phi->set_req(_prim_same_path,   intcon(1));
3755  phi->set_req(_ref_subtype_path, intcon(1));
3756
3757  // pull together the cases:
3758  assert(region->req() == PATH_LIMIT, "sane region");
3759  for (uint i = 1; i < region->req(); i++) {
3760    Node* ctl = region->in(i);
3761    if (ctl == NULL || ctl == top()) {
3762      region->set_req(i, top());
3763      phi   ->set_req(i, top());
3764    } else if (phi->in(i) == NULL) {
3765      phi->set_req(i, intcon(0)); // all other paths produce 'false'
3766    }
3767  }
3768
3769  set_control(_gvn.transform(region));
3770  set_result(_gvn.transform(phi));
3771  return true;
3772}
3773
3774//---------------------generate_array_guard_common------------------------
3775Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
3776                                                  bool obj_array, bool not_array) {
3777
3778  if (stopped()) {
3779    return NULL;
3780  }
3781
3782  // If obj_array/non_array==false/false:
3783  // Branch around if the given klass is in fact an array (either obj or prim).
3784  // If obj_array/non_array==false/true:
3785  // Branch around if the given klass is not an array klass of any kind.
3786  // If obj_array/non_array==true/true:
3787  // Branch around if the kls is not an oop array (kls is int[], String, etc.)
3788  // If obj_array/non_array==true/false:
3789  // Branch around if the kls is an oop array (Object[] or subtype)
3790  //
3791  // Like generate_guard, adds a new path onto the region.
3792  jint  layout_con = 0;
3793  Node* layout_val = get_layout_helper(kls, layout_con);
3794  if (layout_val == NULL) {
3795    bool query = (obj_array
3796                  ? Klass::layout_helper_is_objArray(layout_con)
3797                  : Klass::layout_helper_is_array(layout_con));
3798    if (query == not_array) {
3799      return NULL;                       // never a branch
3800    } else {                             // always a branch
3801      Node* always_branch = control();
3802      if (region != NULL)
3803        region->add_req(always_branch);
3804      set_control(top());
3805      return always_branch;
3806    }
3807  }
3808  // Now test the correct condition.
3809  jint  nval = (obj_array
3810                ? ((jint)Klass::_lh_array_tag_type_value
3811                   <<    Klass::_lh_array_tag_shift)
3812                : Klass::_lh_neutral_value);
3813  Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
3814  BoolTest::mask btest = BoolTest::lt;  // correct for testing is_[obj]array
3815  // invert the test if we are looking for a non-array
3816  if (not_array)  btest = BoolTest(btest).negate();
3817  Node* bol = _gvn.transform(new BoolNode(cmp, btest));
3818  return generate_fair_guard(bol, region);
3819}
3820
3821
3822//-----------------------inline_native_newArray--------------------------
3823// private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
3824bool LibraryCallKit::inline_native_newArray() {
3825  Node* mirror    = argument(0);
3826  Node* count_val = argument(1);
3827
3828  mirror = null_check(mirror);
3829  // If mirror or obj is dead, only null-path is taken.
3830  if (stopped())  return true;
3831
3832  enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
3833  RegionNode* result_reg = new RegionNode(PATH_LIMIT);
3834  PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
3835  PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
3836  PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
3837
3838  bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3839  Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
3840                                                  result_reg, _slow_path);
3841  Node* normal_ctl   = control();
3842  Node* no_array_ctl = result_reg->in(_slow_path);
3843
3844  // Generate code for the slow case.  We make a call to newArray().
3845  set_control(no_array_ctl);
3846  if (!stopped()) {
3847    // Either the input type is void.class, or else the
3848    // array klass has not yet been cached.  Either the
3849    // ensuing call will throw an exception, or else it
3850    // will cache the array klass for next time.
3851    PreserveJVMState pjvms(this);
3852    CallJavaNode* slow_call = generate_method_call_static(vmIntrinsics::_newArray);
3853    Node* slow_result = set_results_for_java_call(slow_call);
3854    // this->control() comes from set_results_for_java_call
3855    result_reg->set_req(_slow_path, control());
3856    result_val->set_req(_slow_path, slow_result);
3857    result_io ->set_req(_slow_path, i_o());
3858    result_mem->set_req(_slow_path, reset_memory());
3859  }
3860
3861  set_control(normal_ctl);
3862  if (!stopped()) {
3863    // Normal case:  The array type has been cached in the java.lang.Class.
3864    // The following call works fine even if the array type is polymorphic.
3865    // It could be a dynamic mix of int[], boolean[], Object[], etc.
3866    Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
3867    result_reg->init_req(_normal_path, control());
3868    result_val->init_req(_normal_path, obj);
3869    result_io ->init_req(_normal_path, i_o());
3870    result_mem->init_req(_normal_path, reset_memory());
3871  }
3872
3873  // Return the combined state.
3874  set_i_o(        _gvn.transform(result_io)  );
3875  set_all_memory( _gvn.transform(result_mem));
3876
3877  C->set_has_split_ifs(true); // Has chance for split-if optimization
3878  set_result(result_reg, result_val);
3879  return true;
3880}
3881
3882//----------------------inline_native_getLength--------------------------
3883// public static native int java.lang.reflect.Array.getLength(Object array);
3884bool LibraryCallKit::inline_native_getLength() {
3885  if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3886
3887  Node* array = null_check(argument(0));
3888  // If array is dead, only null-path is taken.
3889  if (stopped())  return true;
3890
3891  // Deoptimize if it is a non-array.
3892  Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);
3893
3894  if (non_array != NULL) {
3895    PreserveJVMState pjvms(this);
3896    set_control(non_array);
3897    uncommon_trap(Deoptimization::Reason_intrinsic,
3898                  Deoptimization::Action_maybe_recompile);
3899  }
3900
3901  // If control is dead, only non-array-path is taken.
3902  if (stopped())  return true;
3903
3904  // The works fine even if the array type is polymorphic.
3905  // It could be a dynamic mix of int[], boolean[], Object[], etc.
3906  Node* result = load_array_length(array);
3907
3908  C->set_has_split_ifs(true);  // Has chance for split-if optimization
3909  set_result(result);
3910  return true;
3911}
3912
3913//------------------------inline_array_copyOf----------------------------
3914// public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
3915// public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
3916bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
3917  if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3918
3919  // Get the arguments.
3920  Node* original          = argument(0);
3921  Node* start             = is_copyOfRange? argument(1): intcon(0);
3922  Node* end               = is_copyOfRange? argument(2): argument(1);
3923  Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
3924
3925  Node* newcopy;
3926
3927  // Set the original stack and the reexecute bit for the interpreter to reexecute
3928  // the bytecode that invokes Arrays.copyOf if deoptimization happens.
3929  { PreserveReexecuteState preexecs(this);
3930    jvms()->set_should_reexecute(true);
3931
3932    array_type_mirror = null_check(array_type_mirror);
3933    original          = null_check(original);
3934
3935    // Check if a null path was taken unconditionally.
3936    if (stopped())  return true;
3937
3938    Node* orig_length = load_array_length(original);
3939
3940    Node* klass_node = load_klass_from_mirror(array_type_mirror, false, NULL, 0);
3941    klass_node = null_check(klass_node);
3942
3943    RegionNode* bailout = new RegionNode(1);
3944    record_for_igvn(bailout);
3945
3946    // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
3947    // Bail out if that is so.
3948    Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
3949    if (not_objArray != NULL) {
3950      // Improve the klass node's type from the new optimistic assumption:
3951      ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
3952      const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
3953      Node* cast = new CastPPNode(klass_node, akls);
3954      cast->init_req(0, control());
3955      klass_node = _gvn.transform(cast);
3956    }
3957
3958    // Bail out if either start or end is negative.
3959    generate_negative_guard(start, bailout, &start);
3960    generate_negative_guard(end,   bailout, &end);
3961
3962    Node* length = end;
3963    if (_gvn.type(start) != TypeInt::ZERO) {
3964      length = _gvn.transform(new SubINode(end, start));
3965    }
3966
3967    // Bail out if length is negative.
3968    // Without this the new_array would throw
3969    // NegativeArraySizeException but IllegalArgumentException is what
3970    // should be thrown
3971    generate_negative_guard(length, bailout, &length);
3972
3973    if (bailout->req() > 1) {
3974      PreserveJVMState pjvms(this);
3975      set_control(_gvn.transform(bailout));
3976      uncommon_trap(Deoptimization::Reason_intrinsic,
3977                    Deoptimization::Action_maybe_recompile);
3978    }
3979
3980    if (!stopped()) {
3981      // How many elements will we copy from the original?
3982      // The answer is MinI(orig_length - start, length).
3983      Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
3984      Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);
3985
3986      // Generate a direct call to the right arraycopy function(s).
3987      // We know the copy is disjoint but we might not know if the
3988      // oop stores need checking.
3989      // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
3990      // This will fail a store-check if x contains any non-nulls.
3991
3992      // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
3993      // loads/stores but it is legal only if we're sure the
3994      // Arrays.copyOf would succeed. So we need all input arguments
3995      // to the copyOf to be validated, including that the copy to the
3996      // new array won't trigger an ArrayStoreException. That subtype
3997      // check can be optimized if we know something on the type of
3998      // the input array from type speculation.
3999      if (_gvn.type(klass_node)->singleton()) {
4000        ciKlass* subk   = _gvn.type(load_object_klass(original))->is_klassptr()->klass();
4001        ciKlass* superk = _gvn.type(klass_node)->is_klassptr()->klass();
4002
4003        int test = C->static_subtype_check(superk, subk);
4004        if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4005          const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4006          if (t_original->speculative_type() != NULL) {
4007            original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4008          }
4009        }
4010      }
4011
4012      bool validated = false;
4013      // Reason_class_check rather than Reason_intrinsic because we
4014      // want to intrinsify even if this traps.
4015      if (!too_many_traps(Deoptimization::Reason_class_check)) {
4016        Node* not_subtype_ctrl = gen_subtype_check(load_object_klass(original),
4017                                                   klass_node);
4018
4019        if (not_subtype_ctrl != top()) {
4020          PreserveJVMState pjvms(this);
4021          set_control(not_subtype_ctrl);
4022          uncommon_trap(Deoptimization::Reason_class_check,
4023                        Deoptimization::Action_make_not_entrant);
4024          assert(stopped(), "Should be stopped");
4025        }
4026        validated = true;
4027      }
4028
4029      if (!stopped()) {
4030        newcopy = new_array(klass_node, length, 0);  // no arguments to push
4031
4032        ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true,
4033                                                load_object_klass(original), klass_node);
4034        if (!is_copyOfRange) {
4035          ac->set_copyof(validated);
4036        } else {
4037          ac->set_copyofrange(validated);
4038        }
4039        Node* n = _gvn.transform(ac);
4040        if (n == ac) {
4041          ac->connect_outputs(this);
4042        } else {
4043          assert(validated, "shouldn't transform if all arguments not validated");
4044          set_all_memory(n);
4045        }
4046      }
4047    }
4048  } // original reexecute is set back here
4049
4050  C->set_has_split_ifs(true); // Has chance for split-if optimization
4051  if (!stopped()) {
4052    set_result(newcopy);
4053  }
4054  return true;
4055}
4056
4057
4058//----------------------generate_virtual_guard---------------------------
4059// Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
4060Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
4061                                             RegionNode* slow_region) {
4062  ciMethod* method = callee();
4063  int vtable_index = method->vtable_index();
4064  assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4065         err_msg_res("bad index %d", vtable_index));
4066  // Get the Method* out of the appropriate vtable entry.
4067  int entry_offset  = (InstanceKlass::vtable_start_offset() +
4068                     vtable_index*vtableEntry::size()) * wordSize +
4069                     vtableEntry::method_offset_in_bytes();
4070  Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
4071  Node* target_call = make_load(NULL, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4072
4073  // Compare the target method with the expected method (e.g., Object.hashCode).
4074  const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
4075
4076  Node* native_call = makecon(native_call_addr);
4077  Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
4078  Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
4079
4080  return generate_slow_guard(test_native, slow_region);
4081}
4082
4083//-----------------------generate_method_call----------------------------
4084// Use generate_method_call to make a slow-call to the real
4085// method if the fast path fails.  An alternative would be to
4086// use a stub like OptoRuntime::slow_arraycopy_Java.
4087// This only works for expanding the current library call,
4088// not another intrinsic.  (E.g., don't use this for making an
4089// arraycopy call inside of the copyOf intrinsic.)
4090CallJavaNode*
4091LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {
4092  // When compiling the intrinsic method itself, do not use this technique.
4093  guarantee(callee() != C->method(), "cannot make slow-call to self");
4094
4095  ciMethod* method = callee();
4096  // ensure the JVMS we have will be correct for this call
4097  guarantee(method_id == method->intrinsic_id(), "must match");
4098
4099  const TypeFunc* tf = TypeFunc::make(method);
4100  CallJavaNode* slow_call;
4101  if (is_static) {
4102    assert(!is_virtual, "");
4103    slow_call = new CallStaticJavaNode(C, tf,
4104                           SharedRuntime::get_resolve_static_call_stub(),
4105                           method, bci());
4106  } else if (is_virtual) {
4107    null_check_receiver();
4108    int vtable_index = Method::invalid_vtable_index;
4109    if (UseInlineCaches) {
4110      // Suppress the vtable call
4111    } else {
4112      // hashCode and clone are not a miranda methods,
4113      // so the vtable index is fixed.
4114      // No need to use the linkResolver to get it.
4115       vtable_index = method->vtable_index();
4116       assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4117              err_msg_res("bad index %d", vtable_index));
4118    }
4119    slow_call = new CallDynamicJavaNode(tf,
4120                          SharedRuntime::get_resolve_virtual_call_stub(),
4121                          method, vtable_index, bci());
4122  } else {  // neither virtual nor static:  opt_virtual
4123    null_check_receiver();
4124    slow_call = new CallStaticJavaNode(C, tf,
4125                                SharedRuntime::get_resolve_opt_virtual_call_stub(),
4126                                method, bci());
4127    slow_call->set_optimized_virtual(true);
4128  }
4129  set_arguments_for_java_call(slow_call);
4130  set_edges_for_java_call(slow_call);
4131  return slow_call;
4132}
4133
4134
4135/**
4136 * Build special case code for calls to hashCode on an object. This call may
4137 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4138 * slightly different code.
4139 */
4140bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4141  assert(is_static == callee()->is_static(), "correct intrinsic selection");
4142  assert(!(is_virtual && is_static), "either virtual, special, or static");
4143
4144  enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4145
4146  RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4147  PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
4148  PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4149  PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4150  Node* obj = NULL;
4151  if (!is_static) {
4152    // Check for hashing null object
4153    obj = null_check_receiver();
4154    if (stopped())  return true;        // unconditionally null
4155    result_reg->init_req(_null_path, top());
4156    result_val->init_req(_null_path, top());
4157  } else {
4158    // Do a null check, and return zero if null.
4159    // System.identityHashCode(null) == 0
4160    obj = argument(0);
4161    Node* null_ctl = top();
4162    obj = null_check_oop(obj, &null_ctl);
4163    result_reg->init_req(_null_path, null_ctl);
4164    result_val->init_req(_null_path, _gvn.intcon(0));
4165  }
4166
4167  // Unconditionally null?  Then return right away.
4168  if (stopped()) {
4169    set_control( result_reg->in(_null_path));
4170    if (!stopped())
4171      set_result(result_val->in(_null_path));
4172    return true;
4173  }
4174
4175  // We only go to the fast case code if we pass a number of guards.  The
4176  // paths which do not pass are accumulated in the slow_region.
4177  RegionNode* slow_region = new RegionNode(1);
4178  record_for_igvn(slow_region);
4179
4180  // If this is a virtual call, we generate a funny guard.  We pull out
4181  // the vtable entry corresponding to hashCode() from the target object.
4182  // If the target method which we are calling happens to be the native
4183  // Object hashCode() method, we pass the guard.  We do not need this
4184  // guard for non-virtual calls -- the caller is known to be the native
4185  // Object hashCode().
4186  if (is_virtual) {
4187    // After null check, get the object's klass.
4188    Node* obj_klass = load_object_klass(obj);
4189    generate_virtual_guard(obj_klass, slow_region);
4190  }
4191
4192  // Get the header out of the object, use LoadMarkNode when available
4193  Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4194  // The control of the load must be NULL. Otherwise, the load can move before
4195  // the null check after castPP removal.
4196  Node* no_ctrl = NULL;
4197  Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4198
4199  // Test the header to see if it is unlocked.
4200  Node *lock_mask      = _gvn.MakeConX(markOopDesc::biased_lock_mask_in_place);
4201  Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4202  Node *unlocked_val   = _gvn.MakeConX(markOopDesc::unlocked_value);
4203  Node *chk_unlocked   = _gvn.transform(new CmpXNode( lmasked_header, unlocked_val));
4204  Node *test_unlocked  = _gvn.transform(new BoolNode( chk_unlocked, BoolTest::ne));
4205
4206  generate_slow_guard(test_unlocked, slow_region);
4207
4208  // Get the hash value and check to see that it has been properly assigned.
4209  // We depend on hash_mask being at most 32 bits and avoid the use of
4210  // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4211  // vm: see markOop.hpp.
4212  Node *hash_mask      = _gvn.intcon(markOopDesc::hash_mask);
4213  Node *hash_shift     = _gvn.intcon(markOopDesc::hash_shift);
4214  Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4215  // This hack lets the hash bits live anywhere in the mark object now, as long
4216  // as the shift drops the relevant bits into the low 32 bits.  Note that
4217  // Java spec says that HashCode is an int so there's no point in capturing
4218  // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4219  hshifted_header      = ConvX2I(hshifted_header);
4220  Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
4221
4222  Node *no_hash_val    = _gvn.intcon(markOopDesc::no_hash);
4223  Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
4224  Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
4225
4226  generate_slow_guard(test_assigned, slow_region);
4227
4228  Node* init_mem = reset_memory();
4229  // fill in the rest of the null path:
4230  result_io ->init_req(_null_path, i_o());
4231  result_mem->init_req(_null_path, init_mem);
4232
4233  result_val->init_req(_fast_path, hash_val);
4234  result_reg->init_req(_fast_path, control());
4235  result_io ->init_req(_fast_path, i_o());
4236  result_mem->init_req(_fast_path, init_mem);
4237
4238  // Generate code for the slow case.  We make a call to hashCode().
4239  set_control(_gvn.transform(slow_region));
4240  if (!stopped()) {
4241    // No need for PreserveJVMState, because we're using up the present state.
4242    set_all_memory(init_mem);
4243    vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
4244    CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);
4245    Node* slow_result = set_results_for_java_call(slow_call);
4246    // this->control() comes from set_results_for_java_call
4247    result_reg->init_req(_slow_path, control());
4248    result_val->init_req(_slow_path, slow_result);
4249    result_io  ->set_req(_slow_path, i_o());
4250    result_mem ->set_req(_slow_path, reset_memory());
4251  }
4252
4253  // Return the combined state.
4254  set_i_o(        _gvn.transform(result_io)  );
4255  set_all_memory( _gvn.transform(result_mem));
4256
4257  set_result(result_reg, result_val);
4258  return true;
4259}
4260
4261//---------------------------inline_native_getClass----------------------------
4262// public final native Class<?> java.lang.Object.getClass();
4263//
4264// Build special case code for calls to getClass on an object.
4265bool LibraryCallKit::inline_native_getClass() {
4266  Node* obj = null_check_receiver();
4267  if (stopped())  return true;
4268  set_result(load_mirror_from_klass(load_object_klass(obj)));
4269  return true;
4270}
4271
4272//-----------------inline_native_Reflection_getCallerClass---------------------
4273// public static native Class<?> sun.reflect.Reflection.getCallerClass();
4274//
4275// In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4276//
4277// NOTE: This code must perform the same logic as JVM_GetCallerClass
4278// in that it must skip particular security frames and checks for
4279// caller sensitive methods.
4280bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4281#ifndef PRODUCT
4282  if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4283    tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4284  }
4285#endif
4286
4287  if (!jvms()->has_method()) {
4288#ifndef PRODUCT
4289    if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4290      tty->print_cr("  Bailing out because intrinsic was inlined at top level");
4291    }
4292#endif
4293    return false;
4294  }
4295
4296  // Walk back up the JVM state to find the caller at the required
4297  // depth.
4298  JVMState* caller_jvms = jvms();
4299
4300  // Cf. JVM_GetCallerClass
4301  // NOTE: Start the loop at depth 1 because the current JVM state does
4302  // not include the Reflection.getCallerClass() frame.
4303  for (int n = 1; caller_jvms != NULL; caller_jvms = caller_jvms->caller(), n++) {
4304    ciMethod* m = caller_jvms->method();
4305    switch (n) {
4306    case 0:
4307      fatal("current JVM state does not include the Reflection.getCallerClass frame");
4308      break;
4309    case 1:
4310      // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
4311      if (!m->caller_sensitive()) {
4312#ifndef PRODUCT
4313        if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4314          tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
4315        }
4316#endif
4317        return false;  // bail-out; let JVM_GetCallerClass do the work
4318      }
4319      break;
4320    default:
4321      if (!m->is_ignored_by_security_stack_walk()) {
4322        // We have reached the desired frame; return the holder class.
4323        // Acquire method holder as java.lang.Class and push as constant.
4324        ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
4325        ciInstance* caller_mirror = caller_klass->java_mirror();
4326        set_result(makecon(TypeInstPtr::make(caller_mirror)));
4327
4328#ifndef PRODUCT
4329        if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4330          tty->print_cr("  Succeeded: caller = %d) %s.%s, JVMS depth = %d", n, caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), jvms()->depth());
4331          tty->print_cr("  JVM state at this point:");
4332          for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4333            ciMethod* m = jvms()->of_depth(i)->method();
4334            tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4335          }
4336        }
4337#endif
4338        return true;
4339      }
4340      break;
4341    }
4342  }
4343
4344#ifndef PRODUCT
4345  if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4346    tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
4347    tty->print_cr("  JVM state at this point:");
4348    for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4349      ciMethod* m = jvms()->of_depth(i)->method();
4350      tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4351    }
4352  }
4353#endif
4354
4355  return false;  // bail-out; let JVM_GetCallerClass do the work
4356}
4357
4358bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
4359  Node* arg = argument(0);
4360  Node* result;
4361
4362  switch (id) {
4363  case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
4364  case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
4365  case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
4366  case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
4367
4368  case vmIntrinsics::_doubleToLongBits: {
4369    // two paths (plus control) merge in a wood
4370    RegionNode *r = new RegionNode(3);
4371    Node *phi = new PhiNode(r, TypeLong::LONG);
4372
4373    Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
4374    // Build the boolean node
4375    Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
4376
4377    // Branch either way.
4378    // NaN case is less traveled, which makes all the difference.
4379    IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4380    Node *opt_isnan = _gvn.transform(ifisnan);
4381    assert( opt_isnan->is_If(), "Expect an IfNode");
4382    IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4383    Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
4384
4385    set_control(iftrue);
4386
4387    static const jlong nan_bits = CONST64(0x7ff8000000000000);
4388    Node *slow_result = longcon(nan_bits); // return NaN
4389    phi->init_req(1, _gvn.transform( slow_result ));
4390    r->init_req(1, iftrue);
4391
4392    // Else fall through
4393    Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
4394    set_control(iffalse);
4395
4396    phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
4397    r->init_req(2, iffalse);
4398
4399    // Post merge
4400    set_control(_gvn.transform(r));
4401    record_for_igvn(r);
4402
4403    C->set_has_split_ifs(true); // Has chance for split-if optimization
4404    result = phi;
4405    assert(result->bottom_type()->isa_long(), "must be");
4406    break;
4407  }
4408
4409  case vmIntrinsics::_floatToIntBits: {
4410    // two paths (plus control) merge in a wood
4411    RegionNode *r = new RegionNode(3);
4412    Node *phi = new PhiNode(r, TypeInt::INT);
4413
4414    Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
4415    // Build the boolean node
4416    Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
4417
4418    // Branch either way.
4419    // NaN case is less traveled, which makes all the difference.
4420    IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4421    Node *opt_isnan = _gvn.transform(ifisnan);
4422    assert( opt_isnan->is_If(), "Expect an IfNode");
4423    IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4424    Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
4425
4426    set_control(iftrue);
4427
4428    static const jint nan_bits = 0x7fc00000;
4429    Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
4430    phi->init_req(1, _gvn.transform( slow_result ));
4431    r->init_req(1, iftrue);
4432
4433    // Else fall through
4434    Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
4435    set_control(iffalse);
4436
4437    phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
4438    r->init_req(2, iffalse);
4439
4440    // Post merge
4441    set_control(_gvn.transform(r));
4442    record_for_igvn(r);
4443
4444    C->set_has_split_ifs(true); // Has chance for split-if optimization
4445    result = phi;
4446    assert(result->bottom_type()->isa_int(), "must be");
4447    break;
4448  }
4449
4450  default:
4451    fatal_unexpected_iid(id);
4452    break;
4453  }
4454  set_result(_gvn.transform(result));
4455  return true;
4456}
4457
4458#ifdef _LP64
4459#define XTOP ,top() /*additional argument*/
4460#else  //_LP64
4461#define XTOP        /*no additional argument*/
4462#endif //_LP64
4463
4464//----------------------inline_unsafe_copyMemory-------------------------
4465// public native void sun.misc.Unsafe.copyMemory(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
4466bool LibraryCallKit::inline_unsafe_copyMemory() {
4467  if (callee()->is_static())  return false;  // caller must have the capability!
4468  null_check_receiver();  // null-check receiver
4469  if (stopped())  return true;
4470
4471  C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
4472
4473  Node* src_ptr =         argument(1);   // type: oop
4474  Node* src_off = ConvL2X(argument(2));  // type: long
4475  Node* dst_ptr =         argument(4);   // type: oop
4476  Node* dst_off = ConvL2X(argument(5));  // type: long
4477  Node* size    = ConvL2X(argument(7));  // type: long
4478
4479  assert(Unsafe_field_offset_to_byte_offset(11) == 11,
4480         "fieldOffset must be byte-scaled");
4481
4482  Node* src = make_unsafe_address(src_ptr, src_off);
4483  Node* dst = make_unsafe_address(dst_ptr, dst_off);
4484
4485  // Conservatively insert a memory barrier on all memory slices.
4486  // Do not let writes of the copy source or destination float below the copy.
4487  insert_mem_bar(Op_MemBarCPUOrder);
4488
4489  // Call it.  Note that the length argument is not scaled.
4490  make_runtime_call(RC_LEAF|RC_NO_FP,
4491                    OptoRuntime::fast_arraycopy_Type(),
4492                    StubRoutines::unsafe_arraycopy(),
4493                    "unsafe_arraycopy",
4494                    TypeRawPtr::BOTTOM,
4495                    src, dst, size XTOP);
4496
4497  // Do not let reads of the copy destination float above the copy.
4498  insert_mem_bar(Op_MemBarCPUOrder);
4499
4500  return true;
4501}
4502
4503//------------------------clone_coping-----------------------------------
4504// Helper function for inline_native_clone.
4505void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark) {
4506  assert(obj_size != NULL, "");
4507  Node* raw_obj = alloc_obj->in(1);
4508  assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
4509
4510  AllocateNode* alloc = NULL;
4511  if (ReduceBulkZeroing) {
4512    // We will be completely responsible for initializing this object -
4513    // mark Initialize node as complete.
4514    alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
4515    // The object was just allocated - there should be no any stores!
4516    guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");
4517    // Mark as complete_with_arraycopy so that on AllocateNode
4518    // expansion, we know this AllocateNode is initialized by an array
4519    // copy and a StoreStore barrier exists after the array copy.
4520    alloc->initialization()->set_complete_with_arraycopy();
4521  }
4522
4523  // Copy the fastest available way.
4524  // TODO: generate fields copies for small objects instead.
4525  Node* src  = obj;
4526  Node* dest = alloc_obj;
4527  Node* size = _gvn.transform(obj_size);
4528
4529  // Exclude the header but include array length to copy by 8 bytes words.
4530  // Can't use base_offset_in_bytes(bt) since basic type is unknown.
4531  int base_off = is_array ? arrayOopDesc::length_offset_in_bytes() :
4532                            instanceOopDesc::base_offset_in_bytes();
4533  // base_off:
4534  // 8  - 32-bit VM
4535  // 12 - 64-bit VM, compressed klass
4536  // 16 - 64-bit VM, normal klass
4537  if (base_off % BytesPerLong != 0) {
4538    assert(UseCompressedClassPointers, "");
4539    if (is_array) {
4540      // Exclude length to copy by 8 bytes words.
4541      base_off += sizeof(int);
4542    } else {
4543      // Include klass to copy by 8 bytes words.
4544      base_off = instanceOopDesc::klass_offset_in_bytes();
4545    }
4546    assert(base_off % BytesPerLong == 0, "expect 8 bytes alignment");
4547  }
4548  src  = basic_plus_adr(src,  base_off);
4549  dest = basic_plus_adr(dest, base_off);
4550
4551  // Compute the length also, if needed:
4552  Node* countx = size;
4553  countx = _gvn.transform(new SubXNode(countx, MakeConX(base_off)));
4554  countx = _gvn.transform(new URShiftXNode(countx, intcon(LogBytesPerLong) ));
4555
4556  const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4557
4558  ArrayCopyNode* ac = ArrayCopyNode::make(this, false, src, NULL, dest, NULL, countx, false);
4559  ac->set_clonebasic();
4560  Node* n = _gvn.transform(ac);
4561  if (n == ac) {
4562    set_predefined_output_for_runtime_call(ac, ac->in(TypeFunc::Memory), raw_adr_type);
4563  } else {
4564    set_all_memory(n);
4565  }
4566
4567  // If necessary, emit some card marks afterwards.  (Non-arrays only.)
4568  if (card_mark) {
4569    assert(!is_array, "");
4570    // Put in store barrier for any and all oops we are sticking
4571    // into this object.  (We could avoid this if we could prove
4572    // that the object type contains no oop fields at all.)
4573    Node* no_particular_value = NULL;
4574    Node* no_particular_field = NULL;
4575    int raw_adr_idx = Compile::AliasIdxRaw;
4576    post_barrier(control(),
4577                 memory(raw_adr_type),
4578                 alloc_obj,
4579                 no_particular_field,
4580                 raw_adr_idx,
4581                 no_particular_value,
4582                 T_OBJECT,
4583                 false);
4584  }
4585
4586  // Do not let reads from the cloned object float above the arraycopy.
4587  if (alloc != NULL) {
4588    // Do not let stores that initialize this object be reordered with
4589    // a subsequent store that would make this object accessible by
4590    // other threads.
4591    // Record what AllocateNode this StoreStore protects so that
4592    // escape analysis can go from the MemBarStoreStoreNode to the
4593    // AllocateNode and eliminate the MemBarStoreStoreNode if possible
4594    // based on the escape status of the AllocateNode.
4595    insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
4596  } else {
4597    insert_mem_bar(Op_MemBarCPUOrder);
4598  }
4599}
4600
4601//------------------------inline_native_clone----------------------------
4602// protected native Object java.lang.Object.clone();
4603//
4604// Here are the simple edge cases:
4605//  null receiver => normal trap
4606//  virtual and clone was overridden => slow path to out-of-line clone
4607//  not cloneable or finalizer => slow path to out-of-line Object.clone
4608//
4609// The general case has two steps, allocation and copying.
4610// Allocation has two cases, and uses GraphKit::new_instance or new_array.
4611//
4612// Copying also has two cases, oop arrays and everything else.
4613// Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
4614// Everything else uses the tight inline loop supplied by CopyArrayNode.
4615//
4616// These steps fold up nicely if and when the cloned object's klass
4617// can be sharply typed as an object array, a type array, or an instance.
4618//
4619bool LibraryCallKit::inline_native_clone(bool is_virtual) {
4620  PhiNode* result_val;
4621
4622  // Set the reexecute bit for the interpreter to reexecute
4623  // the bytecode that invokes Object.clone if deoptimization happens.
4624  { PreserveReexecuteState preexecs(this);
4625    jvms()->set_should_reexecute(true);
4626
4627    Node* obj = null_check_receiver();
4628    if (stopped())  return true;
4629
4630    const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
4631
4632    // If we are going to clone an instance, we need its exact type to
4633    // know the number and types of fields to convert the clone to
4634    // loads/stores. Maybe a speculative type can help us.
4635    if (!obj_type->klass_is_exact() &&
4636        obj_type->speculative_type() != NULL &&
4637        obj_type->speculative_type()->is_instance_klass()) {
4638      ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
4639      if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
4640          !spec_ik->has_injected_fields()) {
4641        ciKlass* k = obj_type->klass();
4642        if (!k->is_instance_klass() ||
4643            k->as_instance_klass()->is_interface() ||
4644            k->as_instance_klass()->has_subklass()) {
4645          obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
4646        }
4647      }
4648    }
4649
4650    Node* obj_klass = load_object_klass(obj);
4651    const TypeKlassPtr* tklass = _gvn.type(obj_klass)->isa_klassptr();
4652    const TypeOopPtr*   toop   = ((tklass != NULL)
4653                                ? tklass->as_instance_type()
4654                                : TypeInstPtr::NOTNULL);
4655
4656    // Conservatively insert a memory barrier on all memory slices.
4657    // Do not let writes into the original float below the clone.
4658    insert_mem_bar(Op_MemBarCPUOrder);
4659
4660    // paths into result_reg:
4661    enum {
4662      _slow_path = 1,     // out-of-line call to clone method (virtual or not)
4663      _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
4664      _array_path,        // plain array allocation, plus arrayof_long_arraycopy
4665      _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
4666      PATH_LIMIT
4667    };
4668    RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4669    result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4670    PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
4671    PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4672    record_for_igvn(result_reg);
4673
4674    const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4675    int raw_adr_idx = Compile::AliasIdxRaw;
4676
4677    Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);
4678    if (array_ctl != NULL) {
4679      // It's an array.
4680      PreserveJVMState pjvms(this);
4681      set_control(array_ctl);
4682      Node* obj_length = load_array_length(obj);
4683      Node* obj_size  = NULL;
4684      Node* alloc_obj = new_array(obj_klass, obj_length, 0, &obj_size);  // no arguments to push
4685
4686      if (!use_ReduceInitialCardMarks()) {
4687        // If it is an oop array, it requires very special treatment,
4688        // because card marking is required on each card of the array.
4689        Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);
4690        if (is_obja != NULL) {
4691          PreserveJVMState pjvms2(this);
4692          set_control(is_obja);
4693          // Generate a direct call to the right arraycopy function(s).
4694          Node* alloc = tightly_coupled_allocation(alloc_obj, NULL);
4695          ArrayCopyNode* ac = ArrayCopyNode::make(this, true, obj, intcon(0), alloc_obj, intcon(0), obj_length, alloc != NULL);
4696          ac->set_cloneoop();
4697          Node* n = _gvn.transform(ac);
4698          assert(n == ac, "cannot disappear");
4699          ac->connect_outputs(this);
4700
4701          result_reg->init_req(_objArray_path, control());
4702          result_val->init_req(_objArray_path, alloc_obj);
4703          result_i_o ->set_req(_objArray_path, i_o());
4704          result_mem ->set_req(_objArray_path, reset_memory());
4705        }
4706      }
4707      // Otherwise, there are no card marks to worry about.
4708      // (We can dispense with card marks if we know the allocation
4709      //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
4710      //  causes the non-eden paths to take compensating steps to
4711      //  simulate a fresh allocation, so that no further
4712      //  card marks are required in compiled code to initialize
4713      //  the object.)
4714
4715      if (!stopped()) {
4716        copy_to_clone(obj, alloc_obj, obj_size, true, false);
4717
4718        // Present the results of the copy.
4719        result_reg->init_req(_array_path, control());
4720        result_val->init_req(_array_path, alloc_obj);
4721        result_i_o ->set_req(_array_path, i_o());
4722        result_mem ->set_req(_array_path, reset_memory());
4723      }
4724    }
4725
4726    // We only go to the instance fast case code if we pass a number of guards.
4727    // The paths which do not pass are accumulated in the slow_region.
4728    RegionNode* slow_region = new RegionNode(1);
4729    record_for_igvn(slow_region);
4730    if (!stopped()) {
4731      // It's an instance (we did array above).  Make the slow-path tests.
4732      // If this is a virtual call, we generate a funny guard.  We grab
4733      // the vtable entry corresponding to clone() from the target object.
4734      // If the target method which we are calling happens to be the
4735      // Object clone() method, we pass the guard.  We do not need this
4736      // guard for non-virtual calls; the caller is known to be the native
4737      // Object clone().
4738      if (is_virtual) {
4739        generate_virtual_guard(obj_klass, slow_region);
4740      }
4741
4742      // The object must be cloneable and must not have a finalizer.
4743      // Both of these conditions may be checked in a single test.
4744      // We could optimize the cloneable test further, but we don't care.
4745      generate_access_flags_guard(obj_klass,
4746                                  // Test both conditions:
4747                                  JVM_ACC_IS_CLONEABLE | JVM_ACC_HAS_FINALIZER,
4748                                  // Must be cloneable but not finalizer:
4749                                  JVM_ACC_IS_CLONEABLE,
4750                                  slow_region);
4751    }
4752
4753    if (!stopped()) {
4754      // It's an instance, and it passed the slow-path tests.
4755      PreserveJVMState pjvms(this);
4756      Node* obj_size  = NULL;
4757      // Need to deoptimize on exception from allocation since Object.clone intrinsic
4758      // is reexecuted if deoptimization occurs and there could be problems when merging
4759      // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
4760      Node* alloc_obj = new_instance(obj_klass, NULL, &obj_size, /*deoptimize_on_exception=*/true);
4761
4762      copy_to_clone(obj, alloc_obj, obj_size, false, !use_ReduceInitialCardMarks());
4763
4764      // Present the results of the slow call.
4765      result_reg->init_req(_instance_path, control());
4766      result_val->init_req(_instance_path, alloc_obj);
4767      result_i_o ->set_req(_instance_path, i_o());
4768      result_mem ->set_req(_instance_path, reset_memory());
4769    }
4770
4771    // Generate code for the slow case.  We make a call to clone().
4772    set_control(_gvn.transform(slow_region));
4773    if (!stopped()) {
4774      PreserveJVMState pjvms(this);
4775      CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);
4776      Node* slow_result = set_results_for_java_call(slow_call);
4777      // this->control() comes from set_results_for_java_call
4778      result_reg->init_req(_slow_path, control());
4779      result_val->init_req(_slow_path, slow_result);
4780      result_i_o ->set_req(_slow_path, i_o());
4781      result_mem ->set_req(_slow_path, reset_memory());
4782    }
4783
4784    // Return the combined state.
4785    set_control(    _gvn.transform(result_reg));
4786    set_i_o(        _gvn.transform(result_i_o));
4787    set_all_memory( _gvn.transform(result_mem));
4788  } // original reexecute is set back here
4789
4790  set_result(_gvn.transform(result_val));
4791  return true;
4792}
4793
4794// If we have a tighly coupled allocation, the arraycopy may take care
4795// of the array initialization. If one of the guards we insert between
4796// the allocation and the arraycopy causes a deoptimization, an
4797// unitialized array will escape the compiled method. To prevent that
4798// we set the JVM state for uncommon traps between the allocation and
4799// the arraycopy to the state before the allocation so, in case of
4800// deoptimization, we'll reexecute the allocation and the
4801// initialization.
4802JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
4803  if (alloc != NULL) {
4804    ciMethod* trap_method = alloc->jvms()->method();
4805    int trap_bci = alloc->jvms()->bci();
4806
4807    if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &
4808          !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
4809      // Make sure there's no store between the allocation and the
4810      // arraycopy otherwise visible side effects could be rexecuted
4811      // in case of deoptimization and cause incorrect execution.
4812      bool no_interfering_store = true;
4813      Node* mem = alloc->in(TypeFunc::Memory);
4814      if (mem->is_MergeMem()) {
4815        for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
4816          Node* n = mms.memory();
4817          if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
4818            assert(n->is_Store(), "what else?");
4819            no_interfering_store = false;
4820            break;
4821          }
4822        }
4823      } else {
4824        for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
4825          Node* n = mms.memory();
4826          if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
4827            assert(n->is_Store(), "what else?");
4828            no_interfering_store = false;
4829            break;
4830          }
4831        }
4832      }
4833
4834      if (no_interfering_store) {
4835        JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
4836        uint size = alloc->req();
4837        SafePointNode* sfpt = new SafePointNode(size, old_jvms);
4838        old_jvms->set_map(sfpt);
4839        for (uint i = 0; i < size; i++) {
4840          sfpt->init_req(i, alloc->in(i));
4841        }
4842        // re-push array length for deoptimization
4843        sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
4844        old_jvms->set_sp(old_jvms->sp()+1);
4845        old_jvms->set_monoff(old_jvms->monoff()+1);
4846        old_jvms->set_scloff(old_jvms->scloff()+1);
4847        old_jvms->set_endoff(old_jvms->endoff()+1);
4848        old_jvms->set_should_reexecute(true);
4849
4850        sfpt->set_i_o(map()->i_o());
4851        sfpt->set_memory(map()->memory());
4852        sfpt->set_control(map()->control());
4853
4854        JVMState* saved_jvms = jvms();
4855        saved_reexecute_sp = _reexecute_sp;
4856
4857        set_jvms(sfpt->jvms());
4858        _reexecute_sp = jvms()->sp();
4859
4860        return saved_jvms;
4861      }
4862    }
4863  }
4864  return NULL;
4865}
4866
4867// In case of a deoptimization, we restart execution at the
4868// allocation, allocating a new array. We would leave an uninitialized
4869// array in the heap that GCs wouldn't expect. Move the allocation
4870// after the traps so we don't allocate the array if we
4871// deoptimize. This is possible because tightly_coupled_allocation()
4872// guarantees there's no observer of the allocated array at this point
4873// and the control flow is simple enough.
4874void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms, int saved_reexecute_sp) {
4875  if (saved_jvms != NULL && !stopped()) {
4876    assert(alloc != NULL, "only with a tightly coupled allocation");
4877    // restore JVM state to the state at the arraycopy
4878    saved_jvms->map()->set_control(map()->control());
4879    assert(saved_jvms->map()->memory() == map()->memory(), "memory state changed?");
4880    assert(saved_jvms->map()->i_o() == map()->i_o(), "IO state changed?");
4881    // If we've improved the types of some nodes (null check) while
4882    // emitting the guards, propagate them to the current state
4883    map()->replaced_nodes().apply(saved_jvms->map());
4884    set_jvms(saved_jvms);
4885    _reexecute_sp = saved_reexecute_sp;
4886
4887    // Remove the allocation from above the guards
4888    CallProjections callprojs;
4889    alloc->extract_projections(&callprojs, true);
4890    InitializeNode* init = alloc->initialization();
4891    Node* alloc_mem = alloc->in(TypeFunc::Memory);
4892    C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
4893    C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
4894    C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
4895
4896    // move the allocation here (after the guards)
4897    _gvn.hash_delete(alloc);
4898    alloc->set_req(TypeFunc::Control, control());
4899    alloc->set_req(TypeFunc::I_O, i_o());
4900    Node *mem = reset_memory();
4901    set_all_memory(mem);
4902    alloc->set_req(TypeFunc::Memory, mem);
4903    set_control(init->proj_out(TypeFunc::Control));
4904    set_i_o(callprojs.fallthrough_ioproj);
4905
4906    // Update memory as done in GraphKit::set_output_for_allocation()
4907    const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
4908    const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
4909    if (ary_type->isa_aryptr() && length_type != NULL) {
4910      ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
4911    }
4912    const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
4913    int            elemidx  = C->get_alias_index(telemref);
4914    set_memory(init->proj_out(TypeFunc::Memory), Compile::AliasIdxRaw);
4915    set_memory(init->proj_out(TypeFunc::Memory), elemidx);
4916
4917    Node* allocx = _gvn.transform(alloc);
4918    assert(allocx == alloc, "where has the allocation gone?");
4919    assert(dest->is_CheckCastPP(), "not an allocation result?");
4920
4921    _gvn.hash_delete(dest);
4922    dest->set_req(0, control());
4923    Node* destx = _gvn.transform(dest);
4924    assert(destx == dest, "where has the allocation result gone?");
4925  }
4926}
4927
4928
4929//------------------------------inline_arraycopy-----------------------
4930// public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
4931//                                                      Object dest, int destPos,
4932//                                                      int length);
4933bool LibraryCallKit::inline_arraycopy() {
4934  // Get the arguments.
4935  Node* src         = argument(0);  // type: oop
4936  Node* src_offset  = argument(1);  // type: int
4937  Node* dest        = argument(2);  // type: oop
4938  Node* dest_offset = argument(3);  // type: int
4939  Node* length      = argument(4);  // type: int
4940
4941
4942  // Check for allocation before we add nodes that would confuse
4943  // tightly_coupled_allocation()
4944  AllocateArrayNode* alloc = tightly_coupled_allocation(dest, NULL);
4945
4946  int saved_reexecute_sp = -1;
4947  JVMState* saved_jvms = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
4948  // See arraycopy_restore_alloc_state() comment
4949  // if alloc == NULL we don't have to worry about a tightly coupled allocation so we can emit all needed guards
4950  // if saved_jvms != NULL (then alloc != NULL) then we can handle guards and a tightly coupled allocation
4951  // if saved_jvms == NULL and alloc != NULL, we can���t emit any guards
4952  bool can_emit_guards = (alloc == NULL || saved_jvms != NULL);
4953
4954  // The following tests must be performed
4955  // (1) src and dest are arrays.
4956  // (2) src and dest arrays must have elements of the same BasicType
4957  // (3) src and dest must not be null.
4958  // (4) src_offset must not be negative.
4959  // (5) dest_offset must not be negative.
4960  // (6) length must not be negative.
4961  // (7) src_offset + length must not exceed length of src.
4962  // (8) dest_offset + length must not exceed length of dest.
4963  // (9) each element of an oop array must be assignable
4964
4965  // (3) src and dest must not be null.
4966  // always do this here because we need the JVM state for uncommon traps
4967  Node* null_ctl = top();
4968  src  = saved_jvms != NULL ? null_check_oop(src, &null_ctl, true, true) : null_check(src,  T_ARRAY);
4969  assert(null_ctl->is_top(), "no null control here");
4970  dest = null_check(dest, T_ARRAY);
4971
4972  if (!can_emit_guards) {
4973    // if saved_jvms == NULL and alloc != NULL, we don't emit any
4974    // guards but the arraycopy node could still take advantage of a
4975    // tightly allocated allocation. tightly_coupled_allocation() is
4976    // called again to make sure it takes the null check above into
4977    // account: the null check is mandatory and if it caused an
4978    // uncommon trap to be emitted then the allocation can't be
4979    // considered tightly coupled in this context.
4980    alloc = tightly_coupled_allocation(dest, NULL);
4981  }
4982
4983  bool validated = false;
4984
4985  const Type* src_type  = _gvn.type(src);
4986  const Type* dest_type = _gvn.type(dest);
4987  const TypeAryPtr* top_src  = src_type->isa_aryptr();
4988  const TypeAryPtr* top_dest = dest_type->isa_aryptr();
4989
4990  // Do we have the type of src?
4991  bool has_src = (top_src != NULL && top_src->klass() != NULL);
4992  // Do we have the type of dest?
4993  bool has_dest = (top_dest != NULL && top_dest->klass() != NULL);
4994  // Is the type for src from speculation?
4995  bool src_spec = false;
4996  // Is the type for dest from speculation?
4997  bool dest_spec = false;
4998
4999  if ((!has_src || !has_dest) && can_emit_guards) {
5000    // We don't have sufficient type information, let's see if
5001    // speculative types can help. We need to have types for both src
5002    // and dest so that it pays off.
5003
5004    // Do we already have or could we have type information for src
5005    bool could_have_src = has_src;
5006    // Do we already have or could we have type information for dest
5007    bool could_have_dest = has_dest;
5008
5009    ciKlass* src_k = NULL;
5010    if (!has_src) {
5011      src_k = src_type->speculative_type_not_null();
5012      if (src_k != NULL && src_k->is_array_klass()) {
5013        could_have_src = true;
5014      }
5015    }
5016
5017    ciKlass* dest_k = NULL;
5018    if (!has_dest) {
5019      dest_k = dest_type->speculative_type_not_null();
5020      if (dest_k != NULL && dest_k->is_array_klass()) {
5021        could_have_dest = true;
5022      }
5023    }
5024
5025    if (could_have_src && could_have_dest) {
5026      // This is going to pay off so emit the required guards
5027      if (!has_src) {
5028        src = maybe_cast_profiled_obj(src, src_k, true);
5029        src_type  = _gvn.type(src);
5030        top_src  = src_type->isa_aryptr();
5031        has_src = (top_src != NULL && top_src->klass() != NULL);
5032        src_spec = true;
5033      }
5034      if (!has_dest) {
5035        dest = maybe_cast_profiled_obj(dest, dest_k, true);
5036        dest_type  = _gvn.type(dest);
5037        top_dest  = dest_type->isa_aryptr();
5038        has_dest = (top_dest != NULL && top_dest->klass() != NULL);
5039        dest_spec = true;
5040      }
5041    }
5042  }
5043
5044  if (has_src && has_dest && can_emit_guards) {
5045    BasicType src_elem  = top_src->klass()->as_array_klass()->element_type()->basic_type();
5046    BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
5047    if (src_elem  == T_ARRAY)  src_elem  = T_OBJECT;
5048    if (dest_elem == T_ARRAY)  dest_elem = T_OBJECT;
5049
5050    if (src_elem == dest_elem && src_elem == T_OBJECT) {
5051      // If both arrays are object arrays then having the exact types
5052      // for both will remove the need for a subtype check at runtime
5053      // before the call and may make it possible to pick a faster copy
5054      // routine (without a subtype check on every element)
5055      // Do we have the exact type of src?
5056      bool could_have_src = src_spec;
5057      // Do we have the exact type of dest?
5058      bool could_have_dest = dest_spec;
5059      ciKlass* src_k = top_src->klass();
5060      ciKlass* dest_k = top_dest->klass();
5061      if (!src_spec) {
5062        src_k = src_type->speculative_type_not_null();
5063        if (src_k != NULL && src_k->is_array_klass()) {
5064          could_have_src = true;
5065        }
5066      }
5067      if (!dest_spec) {
5068        dest_k = dest_type->speculative_type_not_null();
5069        if (dest_k != NULL && dest_k->is_array_klass()) {
5070          could_have_dest = true;
5071        }
5072      }
5073      if (could_have_src && could_have_dest) {
5074        // If we can have both exact types, emit the missing guards
5075        if (could_have_src && !src_spec) {
5076          src = maybe_cast_profiled_obj(src, src_k, true);
5077        }
5078        if (could_have_dest && !dest_spec) {
5079          dest = maybe_cast_profiled_obj(dest, dest_k, true);
5080        }
5081      }
5082    }
5083  }
5084
5085  ciMethod* trap_method = method();
5086  int trap_bci = bci();
5087  if (saved_jvms != NULL) {
5088    trap_method = alloc->jvms()->method();
5089    trap_bci = alloc->jvms()->bci();
5090  }
5091
5092  if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5093      can_emit_guards &&
5094      !src->is_top() && !dest->is_top()) {
5095    // validate arguments: enables transformation the ArrayCopyNode
5096    validated = true;
5097
5098    RegionNode* slow_region = new RegionNode(1);
5099    record_for_igvn(slow_region);
5100
5101    // (1) src and dest are arrays.
5102    generate_non_array_guard(load_object_klass(src), slow_region);
5103    generate_non_array_guard(load_object_klass(dest), slow_region);
5104
5105    // (2) src and dest arrays must have elements of the same BasicType
5106    // done at macro expansion or at Ideal transformation time
5107
5108    // (4) src_offset must not be negative.
5109    generate_negative_guard(src_offset, slow_region);
5110
5111    // (5) dest_offset must not be negative.
5112    generate_negative_guard(dest_offset, slow_region);
5113
5114    // (7) src_offset + length must not exceed length of src.
5115    generate_limit_guard(src_offset, length,
5116                         load_array_length(src),
5117                         slow_region);
5118
5119    // (8) dest_offset + length must not exceed length of dest.
5120    generate_limit_guard(dest_offset, length,
5121                         load_array_length(dest),
5122                         slow_region);
5123
5124    // (9) each element of an oop array must be assignable
5125    Node* src_klass  = load_object_klass(src);
5126    Node* dest_klass = load_object_klass(dest);
5127    Node* not_subtype_ctrl = gen_subtype_check(src_klass, dest_klass);
5128
5129    if (not_subtype_ctrl != top()) {
5130      PreserveJVMState pjvms(this);
5131      set_control(not_subtype_ctrl);
5132      uncommon_trap(Deoptimization::Reason_intrinsic,
5133                    Deoptimization::Action_make_not_entrant);
5134      assert(stopped(), "Should be stopped");
5135    }
5136    {
5137      PreserveJVMState pjvms(this);
5138      set_control(_gvn.transform(slow_region));
5139      uncommon_trap(Deoptimization::Reason_intrinsic,
5140                    Deoptimization::Action_make_not_entrant);
5141      assert(stopped(), "Should be stopped");
5142    }
5143  }
5144
5145  arraycopy_move_allocation_here(alloc, dest, saved_jvms, saved_reexecute_sp);
5146
5147  if (stopped()) {
5148    return true;
5149  }
5150
5151  ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != NULL,
5152                                          // Create LoadRange and LoadKlass nodes for use during macro expansion here
5153                                          // so the compiler has a chance to eliminate them: during macro expansion,
5154                                          // we have to set their control (CastPP nodes are eliminated).
5155                                          load_object_klass(src), load_object_klass(dest),
5156                                          load_array_length(src), load_array_length(dest));
5157
5158  ac->set_arraycopy(validated);
5159
5160  Node* n = _gvn.transform(ac);
5161  if (n == ac) {
5162    ac->connect_outputs(this);
5163  } else {
5164    assert(validated, "shouldn't transform if all arguments not validated");
5165    set_all_memory(n);
5166  }
5167
5168  return true;
5169}
5170
5171
5172// Helper function which determines if an arraycopy immediately follows
5173// an allocation, with no intervening tests or other escapes for the object.
5174AllocateArrayNode*
5175LibraryCallKit::tightly_coupled_allocation(Node* ptr,
5176                                           RegionNode* slow_region) {
5177  if (stopped())             return NULL;  // no fast path
5178  if (C->AliasLevel() == 0)  return NULL;  // no MergeMems around
5179
5180  AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);
5181  if (alloc == NULL)  return NULL;
5182
5183  Node* rawmem = memory(Compile::AliasIdxRaw);
5184  // Is the allocation's memory state untouched?
5185  if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
5186    // Bail out if there have been raw-memory effects since the allocation.
5187    // (Example:  There might have been a call or safepoint.)
5188    return NULL;
5189  }
5190  rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
5191  if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
5192    return NULL;
5193  }
5194
5195  // There must be no unexpected observers of this allocation.
5196  for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
5197    Node* obs = ptr->fast_out(i);
5198    if (obs != this->map()) {
5199      return NULL;
5200    }
5201  }
5202
5203  // This arraycopy must unconditionally follow the allocation of the ptr.
5204  Node* alloc_ctl = ptr->in(0);
5205  assert(just_allocated_object(alloc_ctl) == ptr, "most recent allo");
5206
5207  Node* ctl = control();
5208  while (ctl != alloc_ctl) {
5209    // There may be guards which feed into the slow_region.
5210    // Any other control flow means that we might not get a chance
5211    // to finish initializing the allocated object.
5212    if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {
5213      IfNode* iff = ctl->in(0)->as_If();
5214      Node* not_ctl = iff->proj_out(1 - ctl->as_Proj()->_con);
5215      assert(not_ctl != NULL && not_ctl != ctl, "found alternate");
5216      if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {
5217        ctl = iff->in(0);       // This test feeds the known slow_region.
5218        continue;
5219      }
5220      // One more try:  Various low-level checks bottom out in
5221      // uncommon traps.  If the debug-info of the trap omits
5222      // any reference to the allocation, as we've already
5223      // observed, then there can be no objection to the trap.
5224      bool found_trap = false;
5225      for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {
5226        Node* obs = not_ctl->fast_out(j);
5227        if (obs->in(0) == not_ctl && obs->is_Call() &&
5228            (obs->as_Call()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {
5229          found_trap = true; break;
5230        }
5231      }
5232      if (found_trap) {
5233        ctl = iff->in(0);       // This test feeds a harmless uncommon trap.
5234        continue;
5235      }
5236    }
5237    return NULL;
5238  }
5239
5240  // If we get this far, we have an allocation which immediately
5241  // precedes the arraycopy, and we can take over zeroing the new object.
5242  // The arraycopy will finish the initialization, and provide
5243  // a new control state to which we will anchor the destination pointer.
5244
5245  return alloc;
5246}
5247
5248//-------------inline_encodeISOArray-----------------------------------
5249// encode char[] to byte[] in ISO_8859_1
5250bool LibraryCallKit::inline_encodeISOArray() {
5251  assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
5252  // no receiver since it is static method
5253  Node *src         = argument(0);
5254  Node *src_offset  = argument(1);
5255  Node *dst         = argument(2);
5256  Node *dst_offset  = argument(3);
5257  Node *length      = argument(4);
5258
5259  const Type* src_type = src->Value(&_gvn);
5260  const Type* dst_type = dst->Value(&_gvn);
5261  const TypeAryPtr* top_src = src_type->isa_aryptr();
5262  const TypeAryPtr* top_dest = dst_type->isa_aryptr();
5263  if (top_src  == NULL || top_src->klass()  == NULL ||
5264      top_dest == NULL || top_dest->klass() == NULL) {
5265    // failed array check
5266    return false;
5267  }
5268
5269  // Figure out the size and type of the elements we will be copying.
5270  BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5271  BasicType dst_elem = dst_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5272  if (src_elem != T_CHAR || dst_elem != T_BYTE) {
5273    return false;
5274  }
5275  Node* src_start = array_element_address(src, src_offset, src_elem);
5276  Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
5277  // 'src_start' points to src array + scaled offset
5278  // 'dst_start' points to dst array + scaled offset
5279
5280  const TypeAryPtr* mtype = TypeAryPtr::BYTES;
5281  Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length);
5282  enc = _gvn.transform(enc);
5283  Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
5284  set_memory(res_mem, mtype);
5285  set_result(enc);
5286  return true;
5287}
5288
5289//-------------inline_multiplyToLen-----------------------------------
5290bool LibraryCallKit::inline_multiplyToLen() {
5291  assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
5292
5293  address stubAddr = StubRoutines::multiplyToLen();
5294  if (stubAddr == NULL) {
5295    return false; // Intrinsic's stub is not implemented on this platform
5296  }
5297  const char* stubName = "multiplyToLen";
5298
5299  assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
5300
5301  // no receiver because it is a static method
5302  Node* x    = argument(0);
5303  Node* xlen = argument(1);
5304  Node* y    = argument(2);
5305  Node* ylen = argument(3);
5306  Node* z    = argument(4);
5307
5308  const Type* x_type = x->Value(&_gvn);
5309  const Type* y_type = y->Value(&_gvn);
5310  const TypeAryPtr* top_x = x_type->isa_aryptr();
5311  const TypeAryPtr* top_y = y_type->isa_aryptr();
5312  if (top_x  == NULL || top_x->klass()  == NULL ||
5313      top_y == NULL || top_y->klass() == NULL) {
5314    // failed array check
5315    return false;
5316  }
5317
5318  BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5319  BasicType y_elem = y_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5320  if (x_elem != T_INT || y_elem != T_INT) {
5321    return false;
5322  }
5323
5324  // Set the original stack and the reexecute bit for the interpreter to reexecute
5325  // the bytecode that invokes BigInteger.multiplyToLen() if deoptimization happens
5326  // on the return from z array allocation in runtime.
5327  { PreserveReexecuteState preexecs(this);
5328    jvms()->set_should_reexecute(true);
5329
5330    Node* x_start = array_element_address(x, intcon(0), x_elem);
5331    Node* y_start = array_element_address(y, intcon(0), y_elem);
5332    // 'x_start' points to x array + scaled xlen
5333    // 'y_start' points to y array + scaled ylen
5334
5335    // Allocate the result array
5336    Node* zlen = _gvn.transform(new AddINode(xlen, ylen));
5337    ciKlass* klass = ciTypeArrayKlass::make(T_INT);
5338    Node* klass_node = makecon(TypeKlassPtr::make(klass));
5339
5340    IdealKit ideal(this);
5341
5342#define __ ideal.
5343     Node* one = __ ConI(1);
5344     Node* zero = __ ConI(0);
5345     IdealVariable need_alloc(ideal), z_alloc(ideal);  __ declarations_done();
5346     __ set(need_alloc, zero);
5347     __ set(z_alloc, z);
5348     __ if_then(z, BoolTest::eq, null()); {
5349       __ increment (need_alloc, one);
5350     } __ else_(); {
5351       // Update graphKit memory and control from IdealKit.
5352       sync_kit(ideal);
5353       Node* zlen_arg = load_array_length(z);
5354       // Update IdealKit memory and control from graphKit.
5355       __ sync_kit(this);
5356       __ if_then(zlen_arg, BoolTest::lt, zlen); {
5357         __ increment (need_alloc, one);
5358       } __ end_if();
5359     } __ end_if();
5360
5361     __ if_then(__ value(need_alloc), BoolTest::ne, zero); {
5362       // Update graphKit memory and control from IdealKit.
5363       sync_kit(ideal);
5364       Node * narr = new_array(klass_node, zlen, 1);
5365       // Update IdealKit memory and control from graphKit.
5366       __ sync_kit(this);
5367       __ set(z_alloc, narr);
5368     } __ end_if();
5369
5370     sync_kit(ideal);
5371     z = __ value(z_alloc);
5372     // Can't use TypeAryPtr::INTS which uses Bottom offset.
5373     _gvn.set_type(z, TypeOopPtr::make_from_klass(klass));
5374     // Final sync IdealKit and GraphKit.
5375     final_sync(ideal);
5376#undef __
5377
5378    Node* z_start = array_element_address(z, intcon(0), T_INT);
5379
5380    Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
5381                                   OptoRuntime::multiplyToLen_Type(),
5382                                   stubAddr, stubName, TypePtr::BOTTOM,
5383                                   x_start, xlen, y_start, ylen, z_start, zlen);
5384  } // original reexecute is set back here
5385
5386  C->set_has_split_ifs(true); // Has chance for split-if optimization
5387  set_result(z);
5388  return true;
5389}
5390
5391//-------------inline_squareToLen------------------------------------
5392bool LibraryCallKit::inline_squareToLen() {
5393  assert(UseSquareToLenIntrinsic, "not implementated on this platform");
5394
5395  address stubAddr = StubRoutines::squareToLen();
5396  if (stubAddr == NULL) {
5397    return false; // Intrinsic's stub is not implemented on this platform
5398  }
5399  const char* stubName = "squareToLen";
5400
5401  assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
5402
5403  Node* x    = argument(0);
5404  Node* len  = argument(1);
5405  Node* z    = argument(2);
5406  Node* zlen = argument(3);
5407
5408  const Type* x_type = x->Value(&_gvn);
5409  const Type* z_type = z->Value(&_gvn);
5410  const TypeAryPtr* top_x = x_type->isa_aryptr();
5411  const TypeAryPtr* top_z = z_type->isa_aryptr();
5412  if (top_x  == NULL || top_x->klass()  == NULL ||
5413      top_z  == NULL || top_z->klass()  == NULL) {
5414    // failed array check
5415    return false;
5416  }
5417
5418  BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5419  BasicType z_elem = z_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5420  if (x_elem != T_INT || z_elem != T_INT) {
5421    return false;
5422  }
5423
5424
5425  Node* x_start = array_element_address(x, intcon(0), x_elem);
5426  Node* z_start = array_element_address(z, intcon(0), z_elem);
5427
5428  Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
5429                                  OptoRuntime::squareToLen_Type(),
5430                                  stubAddr, stubName, TypePtr::BOTTOM,
5431                                  x_start, len, z_start, zlen);
5432
5433  set_result(z);
5434  return true;
5435}
5436
5437//-------------inline_mulAdd------------------------------------------
5438bool LibraryCallKit::inline_mulAdd() {
5439  assert(UseMulAddIntrinsic, "not implementated on this platform");
5440
5441  address stubAddr = StubRoutines::mulAdd();
5442  if (stubAddr == NULL) {
5443    return false; // Intrinsic's stub is not implemented on this platform
5444  }
5445  const char* stubName = "mulAdd";
5446
5447  assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
5448
5449  Node* out      = argument(0);
5450  Node* in       = argument(1);
5451  Node* offset   = argument(2);
5452  Node* len      = argument(3);
5453  Node* k        = argument(4);
5454
5455  const Type* out_type = out->Value(&_gvn);
5456  const Type* in_type = in->Value(&_gvn);
5457  const TypeAryPtr* top_out = out_type->isa_aryptr();
5458  const TypeAryPtr* top_in = in_type->isa_aryptr();
5459  if (top_out  == NULL || top_out->klass()  == NULL ||
5460      top_in == NULL || top_in->klass() == NULL) {
5461    // failed array check
5462    return false;
5463  }
5464
5465  BasicType out_elem = out_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5466  BasicType in_elem = in_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5467  if (out_elem != T_INT || in_elem != T_INT) {
5468    return false;
5469  }
5470
5471  Node* outlen = load_array_length(out);
5472  Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
5473  Node* out_start = array_element_address(out, intcon(0), out_elem);
5474  Node* in_start = array_element_address(in, intcon(0), in_elem);
5475
5476  Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
5477                                  OptoRuntime::mulAdd_Type(),
5478                                  stubAddr, stubName, TypePtr::BOTTOM,
5479                                  out_start,in_start, new_offset, len, k);
5480  Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5481  set_result(result);
5482  return true;
5483}
5484
5485//-------------inline_montgomeryMultiply-----------------------------------
5486bool LibraryCallKit::inline_montgomeryMultiply() {
5487  address stubAddr = StubRoutines::montgomeryMultiply();
5488  if (stubAddr == NULL) {
5489    return false; // Intrinsic's stub is not implemented on this platform
5490  }
5491
5492  assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
5493  const char* stubName = "montgomery_square";
5494
5495  assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
5496
5497  Node* a    = argument(0);
5498  Node* b    = argument(1);
5499  Node* n    = argument(2);
5500  Node* len  = argument(3);
5501  Node* inv  = argument(4);
5502  Node* m    = argument(6);
5503
5504  const Type* a_type = a->Value(&_gvn);
5505  const TypeAryPtr* top_a = a_type->isa_aryptr();
5506  const Type* b_type = b->Value(&_gvn);
5507  const TypeAryPtr* top_b = b_type->isa_aryptr();
5508  const Type* n_type = a->Value(&_gvn);
5509  const TypeAryPtr* top_n = n_type->isa_aryptr();
5510  const Type* m_type = a->Value(&_gvn);
5511  const TypeAryPtr* top_m = m_type->isa_aryptr();
5512  if (top_a  == NULL || top_a->klass()  == NULL ||
5513      top_b == NULL || top_b->klass()  == NULL ||
5514      top_n == NULL || top_n->klass()  == NULL ||
5515      top_m == NULL || top_m->klass()  == NULL) {
5516    // failed array check
5517    return false;
5518  }
5519
5520  BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5521  BasicType b_elem = b_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5522  BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5523  BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5524  if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
5525    return false;
5526  }
5527
5528  // Make the call
5529  {
5530    Node* a_start = array_element_address(a, intcon(0), a_elem);
5531    Node* b_start = array_element_address(b, intcon(0), b_elem);
5532    Node* n_start = array_element_address(n, intcon(0), n_elem);
5533    Node* m_start = array_element_address(m, intcon(0), m_elem);
5534
5535    Node* call = make_runtime_call(RC_LEAF,
5536                                   OptoRuntime::montgomeryMultiply_Type(),
5537                                   stubAddr, stubName, TypePtr::BOTTOM,
5538                                   a_start, b_start, n_start, len, inv, top(),
5539                                   m_start);
5540    set_result(m);
5541  }
5542
5543  return true;
5544}
5545
5546bool LibraryCallKit::inline_montgomerySquare() {
5547  address stubAddr = StubRoutines::montgomerySquare();
5548  if (stubAddr == NULL) {
5549    return false; // Intrinsic's stub is not implemented on this platform
5550  }
5551
5552  assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
5553  const char* stubName = "montgomery_square";
5554
5555  assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
5556
5557  Node* a    = argument(0);
5558  Node* n    = argument(1);
5559  Node* len  = argument(2);
5560  Node* inv  = argument(3);
5561  Node* m    = argument(5);
5562
5563  const Type* a_type = a->Value(&_gvn);
5564  const TypeAryPtr* top_a = a_type->isa_aryptr();
5565  const Type* n_type = a->Value(&_gvn);
5566  const TypeAryPtr* top_n = n_type->isa_aryptr();
5567  const Type* m_type = a->Value(&_gvn);
5568  const TypeAryPtr* top_m = m_type->isa_aryptr();
5569  if (top_a  == NULL || top_a->klass()  == NULL ||
5570      top_n == NULL || top_n->klass()  == NULL ||
5571      top_m == NULL || top_m->klass()  == NULL) {
5572    // failed array check
5573    return false;
5574  }
5575
5576  BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5577  BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5578  BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5579  if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
5580    return false;
5581  }
5582
5583  // Make the call
5584  {
5585    Node* a_start = array_element_address(a, intcon(0), a_elem);
5586    Node* n_start = array_element_address(n, intcon(0), n_elem);
5587    Node* m_start = array_element_address(m, intcon(0), m_elem);
5588
5589    Node* call = make_runtime_call(RC_LEAF,
5590                                   OptoRuntime::montgomerySquare_Type(),
5591                                   stubAddr, stubName, TypePtr::BOTTOM,
5592                                   a_start, n_start, len, inv, top(),
5593                                   m_start);
5594    set_result(m);
5595  }
5596
5597  return true;
5598}
5599
5600
5601/**
5602 * Calculate CRC32 for byte.
5603 * int java.util.zip.CRC32.update(int crc, int b)
5604 */
5605bool LibraryCallKit::inline_updateCRC32() {
5606  assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5607  assert(callee()->signature()->size() == 2, "update has 2 parameters");
5608  // no receiver since it is static method
5609  Node* crc  = argument(0); // type: int
5610  Node* b    = argument(1); // type: int
5611
5612  /*
5613   *    int c = ~ crc;
5614   *    b = timesXtoThe32[(b ^ c) & 0xFF];
5615   *    b = b ^ (c >>> 8);
5616   *    crc = ~b;
5617   */
5618
5619  Node* M1 = intcon(-1);
5620  crc = _gvn.transform(new XorINode(crc, M1));
5621  Node* result = _gvn.transform(new XorINode(crc, b));
5622  result = _gvn.transform(new AndINode(result, intcon(0xFF)));
5623
5624  Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
5625  Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
5626  Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
5627  result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
5628
5629  crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
5630  result = _gvn.transform(new XorINode(crc, result));
5631  result = _gvn.transform(new XorINode(result, M1));
5632  set_result(result);
5633  return true;
5634}
5635
5636/**
5637 * Calculate CRC32 for byte[] array.
5638 * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
5639 */
5640bool LibraryCallKit::inline_updateBytesCRC32() {
5641  assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5642  assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5643  // no receiver since it is static method
5644  Node* crc     = argument(0); // type: int
5645  Node* src     = argument(1); // type: oop
5646  Node* offset  = argument(2); // type: int
5647  Node* length  = argument(3); // type: int
5648
5649  const Type* src_type = src->Value(&_gvn);
5650  const TypeAryPtr* top_src = src_type->isa_aryptr();
5651  if (top_src  == NULL || top_src->klass()  == NULL) {
5652    // failed array check
5653    return false;
5654  }
5655
5656  // Figure out the size and type of the elements we will be copying.
5657  BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5658  if (src_elem != T_BYTE) {
5659    return false;
5660  }
5661
5662  // 'src_start' points to src array + scaled offset
5663  Node* src_start = array_element_address(src, offset, src_elem);
5664
5665  // We assume that range check is done by caller.
5666  // TODO: generate range check (offset+length < src.length) in debug VM.
5667
5668  // Call the stub.
5669  address stubAddr = StubRoutines::updateBytesCRC32();
5670  const char *stubName = "updateBytesCRC32";
5671
5672  Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5673                                 stubAddr, stubName, TypePtr::BOTTOM,
5674                                 crc, src_start, length);
5675  Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5676  set_result(result);
5677  return true;
5678}
5679
5680/**
5681 * Calculate CRC32 for ByteBuffer.
5682 * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
5683 */
5684bool LibraryCallKit::inline_updateByteBufferCRC32() {
5685  assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5686  assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
5687  // no receiver since it is static method
5688  Node* crc     = argument(0); // type: int
5689  Node* src     = argument(1); // type: long
5690  Node* offset  = argument(3); // type: int
5691  Node* length  = argument(4); // type: int
5692
5693  src = ConvL2X(src);  // adjust Java long to machine word
5694  Node* base = _gvn.transform(new CastX2PNode(src));
5695  offset = ConvI2X(offset);
5696
5697  // 'src_start' points to src array + scaled offset
5698  Node* src_start = basic_plus_adr(top(), base, offset);
5699
5700  // Call the stub.
5701  address stubAddr = StubRoutines::updateBytesCRC32();
5702  const char *stubName = "updateBytesCRC32";
5703
5704  Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5705                                 stubAddr, stubName, TypePtr::BOTTOM,
5706                                 crc, src_start, length);
5707  Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5708  set_result(result);
5709  return true;
5710}
5711
5712//------------------------------get_table_from_crc32c_class-----------------------
5713Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
5714  Node* table = load_field_from_object(NULL, "byteTable", "[I", /*is_exact*/ false, /*is_static*/ true, crc32c_class);
5715  assert (table != NULL, "wrong version of java.util.zip.CRC32C");
5716
5717  return table;
5718}
5719
5720//------------------------------inline_updateBytesCRC32C-----------------------
5721//
5722// Calculate CRC32C for byte[] array.
5723// int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
5724//
5725bool LibraryCallKit::inline_updateBytesCRC32C() {
5726  assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
5727  assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5728  assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
5729  // no receiver since it is a static method
5730  Node* crc     = argument(0); // type: int
5731  Node* src     = argument(1); // type: oop
5732  Node* offset  = argument(2); // type: int
5733  Node* end     = argument(3); // type: int
5734
5735  Node* length = _gvn.transform(new SubINode(end, offset));
5736
5737  const Type* src_type = src->Value(&_gvn);
5738  const TypeAryPtr* top_src = src_type->isa_aryptr();
5739  if (top_src  == NULL || top_src->klass()  == NULL) {
5740    // failed array check
5741    return false;
5742  }
5743
5744  // Figure out the size and type of the elements we will be copying.
5745  BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5746  if (src_elem != T_BYTE) {
5747    return false;
5748  }
5749
5750  // 'src_start' points to src array + scaled offset
5751  Node* src_start = array_element_address(src, offset, src_elem);
5752
5753  // static final int[] byteTable in class CRC32C
5754  Node* table = get_table_from_crc32c_class(callee()->holder());
5755  Node* table_start = array_element_address(table, intcon(0), T_INT);
5756
5757  // We assume that range check is done by caller.
5758  // TODO: generate range check (offset+length < src.length) in debug VM.
5759
5760  // Call the stub.
5761  address stubAddr = StubRoutines::updateBytesCRC32C();
5762  const char *stubName = "updateBytesCRC32C";
5763
5764  Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
5765                                 stubAddr, stubName, TypePtr::BOTTOM,
5766                                 crc, src_start, length, table_start);
5767  Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5768  set_result(result);
5769  return true;
5770}
5771
5772//------------------------------inline_updateDirectByteBufferCRC32C-----------------------
5773//
5774// Calculate CRC32C for DirectByteBuffer.
5775// int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
5776//
5777bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
5778  assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
5779  assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
5780  assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
5781  // no receiver since it is a static method
5782  Node* crc     = argument(0); // type: int
5783  Node* src     = argument(1); // type: long
5784  Node* offset  = argument(3); // type: int
5785  Node* end     = argument(4); // type: int
5786
5787  Node* length = _gvn.transform(new SubINode(end, offset));
5788
5789  src = ConvL2X(src);  // adjust Java long to machine word
5790  Node* base = _gvn.transform(new CastX2PNode(src));
5791  offset = ConvI2X(offset);
5792
5793  // 'src_start' points to src array + scaled offset
5794  Node* src_start = basic_plus_adr(top(), base, offset);
5795
5796  // static final int[] byteTable in class CRC32C
5797  Node* table = get_table_from_crc32c_class(callee()->holder());
5798  Node* table_start = array_element_address(table, intcon(0), T_INT);
5799
5800  // Call the stub.
5801  address stubAddr = StubRoutines::updateBytesCRC32C();
5802  const char *stubName = "updateBytesCRC32C";
5803
5804  Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
5805                                 stubAddr, stubName, TypePtr::BOTTOM,
5806                                 crc, src_start, length, table_start);
5807  Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5808  set_result(result);
5809  return true;
5810}
5811
5812//----------------------------inline_reference_get----------------------------
5813// public T java.lang.ref.Reference.get();
5814bool LibraryCallKit::inline_reference_get() {
5815  const int referent_offset = java_lang_ref_Reference::referent_offset;
5816  guarantee(referent_offset > 0, "should have already been set");
5817
5818  // Get the argument:
5819  Node* reference_obj = null_check_receiver();
5820  if (stopped()) return true;
5821
5822  Node* adr = basic_plus_adr(reference_obj, reference_obj, referent_offset);
5823
5824  ciInstanceKlass* klass = env()->Object_klass();
5825  const TypeOopPtr* object_type = TypeOopPtr::make_from_klass(klass);
5826
5827  Node* no_ctrl = NULL;
5828  Node* result = make_load(no_ctrl, adr, object_type, T_OBJECT, MemNode::unordered);
5829
5830  // Use the pre-barrier to record the value in the referent field
5831  pre_barrier(false /* do_load */,
5832              control(),
5833              NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
5834              result /* pre_val */,
5835              T_OBJECT);
5836
5837  // Add memory barrier to prevent commoning reads from this field
5838  // across safepoint since GC can change its value.
5839  insert_mem_bar(Op_MemBarCPUOrder);
5840
5841  set_result(result);
5842  return true;
5843}
5844
5845
5846Node * LibraryCallKit::load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
5847                                              bool is_exact=true, bool is_static=false,
5848                                              ciInstanceKlass * fromKls=NULL) {
5849  if (fromKls == NULL) {
5850    const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
5851    assert(tinst != NULL, "obj is null");
5852    assert(tinst->klass()->is_loaded(), "obj is not loaded");
5853    assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
5854    fromKls = tinst->klass()->as_instance_klass();
5855  } else {
5856    assert(is_static, "only for static field access");
5857  }
5858  ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
5859                                              ciSymbol::make(fieldTypeString),
5860                                              is_static);
5861
5862  assert (field != NULL, "undefined field");
5863  if (field == NULL) return (Node *) NULL;
5864
5865  if (is_static) {
5866    const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
5867    fromObj = makecon(tip);
5868  }
5869
5870  // Next code  copied from Parse::do_get_xxx():
5871
5872  // Compute address and memory type.
5873  int offset  = field->offset_in_bytes();
5874  bool is_vol = field->is_volatile();
5875  ciType* field_klass = field->type();
5876  assert(field_klass->is_loaded(), "should be loaded");
5877  const TypePtr* adr_type = C->alias_type(field)->adr_type();
5878  Node *adr = basic_plus_adr(fromObj, fromObj, offset);
5879  BasicType bt = field->layout_type();
5880
5881  // Build the resultant type of the load
5882  const Type *type;
5883  if (bt == T_OBJECT) {
5884    type = TypeOopPtr::make_from_klass(field_klass->as_klass());
5885  } else {
5886    type = Type::get_const_basic_type(bt);
5887  }
5888
5889  if (support_IRIW_for_not_multiple_copy_atomic_cpu && is_vol) {
5890    insert_mem_bar(Op_MemBarVolatile);   // StoreLoad barrier
5891  }
5892  // Build the load.
5893  MemNode::MemOrd mo = is_vol ? MemNode::acquire : MemNode::unordered;
5894  Node* loadedField = make_load(NULL, adr, type, bt, adr_type, mo, LoadNode::DependsOnlyOnTest, is_vol);
5895  // If reference is volatile, prevent following memory ops from
5896  // floating up past the volatile read.  Also prevents commoning
5897  // another volatile read.
5898  if (is_vol) {
5899    // Memory barrier includes bogus read of value to force load BEFORE membar
5900    insert_mem_bar(Op_MemBarAcquire, loadedField);
5901  }
5902  return loadedField;
5903}
5904
5905
5906//------------------------------inline_aescrypt_Block-----------------------
5907bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
5908  address stubAddr;
5909  const char *stubName;
5910  assert(UseAES, "need AES instruction support");
5911
5912  switch(id) {
5913  case vmIntrinsics::_aescrypt_encryptBlock:
5914    stubAddr = StubRoutines::aescrypt_encryptBlock();
5915    stubName = "aescrypt_encryptBlock";
5916    break;
5917  case vmIntrinsics::_aescrypt_decryptBlock:
5918    stubAddr = StubRoutines::aescrypt_decryptBlock();
5919    stubName = "aescrypt_decryptBlock";
5920    break;
5921  }
5922  if (stubAddr == NULL) return false;
5923
5924  Node* aescrypt_object = argument(0);
5925  Node* src             = argument(1);
5926  Node* src_offset      = argument(2);
5927  Node* dest            = argument(3);
5928  Node* dest_offset     = argument(4);
5929
5930  // (1) src and dest are arrays.
5931  const Type* src_type = src->Value(&_gvn);
5932  const Type* dest_type = dest->Value(&_gvn);
5933  const TypeAryPtr* top_src = src_type->isa_aryptr();
5934  const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5935  assert (top_src  != NULL && top_src->klass()  != NULL &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
5936
5937  // for the quick and dirty code we will skip all the checks.
5938  // we are just trying to get the call to be generated.
5939  Node* src_start  = src;
5940  Node* dest_start = dest;
5941  if (src_offset != NULL || dest_offset != NULL) {
5942    assert(src_offset != NULL && dest_offset != NULL, "");
5943    src_start  = array_element_address(src,  src_offset,  T_BYTE);
5944    dest_start = array_element_address(dest, dest_offset, T_BYTE);
5945  }
5946
5947  // now need to get the start of its expanded key array
5948  // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
5949  Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
5950  if (k_start == NULL) return false;
5951
5952  if (Matcher::pass_original_key_for_aes()) {
5953    // on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to
5954    // compatibility issues between Java key expansion and SPARC crypto instructions
5955    Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);
5956    if (original_k_start == NULL) return false;
5957
5958    // Call the stub.
5959    make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
5960                      stubAddr, stubName, TypePtr::BOTTOM,
5961                      src_start, dest_start, k_start, original_k_start);
5962  } else {
5963    // Call the stub.
5964    make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
5965                      stubAddr, stubName, TypePtr::BOTTOM,
5966                      src_start, dest_start, k_start);
5967  }
5968
5969  return true;
5970}
5971
5972//------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
5973bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
5974  address stubAddr;
5975  const char *stubName;
5976
5977  assert(UseAES, "need AES instruction support");
5978
5979  switch(id) {
5980  case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
5981    stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
5982    stubName = "cipherBlockChaining_encryptAESCrypt";
5983    break;
5984  case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
5985    stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
5986    stubName = "cipherBlockChaining_decryptAESCrypt";
5987    break;
5988  }
5989  if (stubAddr == NULL) return false;
5990
5991  Node* cipherBlockChaining_object = argument(0);
5992  Node* src                        = argument(1);
5993  Node* src_offset                 = argument(2);
5994  Node* len                        = argument(3);
5995  Node* dest                       = argument(4);
5996  Node* dest_offset                = argument(5);
5997
5998  // (1) src and dest are arrays.
5999  const Type* src_type = src->Value(&_gvn);
6000  const Type* dest_type = dest->Value(&_gvn);
6001  const TypeAryPtr* top_src = src_type->isa_aryptr();
6002  const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6003  assert (top_src  != NULL && top_src->klass()  != NULL
6004          &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
6005
6006  // checks are the responsibility of the caller
6007  Node* src_start  = src;
6008  Node* dest_start = dest;
6009  if (src_offset != NULL || dest_offset != NULL) {
6010    assert(src_offset != NULL && dest_offset != NULL, "");
6011    src_start  = array_element_address(src,  src_offset,  T_BYTE);
6012    dest_start = array_element_address(dest, dest_offset, T_BYTE);
6013  }
6014
6015  // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
6016  // (because of the predicated logic executed earlier).
6017  // so we cast it here safely.
6018  // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6019
6020  Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
6021  if (embeddedCipherObj == NULL) return false;
6022
6023  // cast it to what we know it will be at runtime
6024  const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
6025  assert(tinst != NULL, "CBC obj is null");
6026  assert(tinst->klass()->is_loaded(), "CBC obj is not loaded");
6027  ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6028  assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
6029
6030  ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6031  const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
6032  const TypeOopPtr* xtype = aklass->as_instance_type();
6033  Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
6034  aescrypt_object = _gvn.transform(aescrypt_object);
6035
6036  // we need to get the start of the aescrypt_object's expanded key array
6037  Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6038  if (k_start == NULL) return false;
6039
6040  // similarly, get the start address of the r vector
6041  Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B", /*is_exact*/ false);
6042  if (objRvec == NULL) return false;
6043  Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
6044
6045  Node* cbcCrypt;
6046  if (Matcher::pass_original_key_for_aes()) {
6047    // on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to
6048    // compatibility issues between Java key expansion and SPARC crypto instructions
6049    Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);
6050    if (original_k_start == NULL) return false;
6051
6052    // Call the stub, passing src_start, dest_start, k_start, r_start, src_len and original_k_start
6053    cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
6054                                 OptoRuntime::cipherBlockChaining_aescrypt_Type(),
6055                                 stubAddr, stubName, TypePtr::BOTTOM,
6056                                 src_start, dest_start, k_start, r_start, len, original_k_start);
6057  } else {
6058    // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
6059    cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
6060                                 OptoRuntime::cipherBlockChaining_aescrypt_Type(),
6061                                 stubAddr, stubName, TypePtr::BOTTOM,
6062                                 src_start, dest_start, k_start, r_start, len);
6063  }
6064
6065  // return cipher length (int)
6066  Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
6067  set_result(retvalue);
6068  return true;
6069}
6070
6071//------------------------------get_key_start_from_aescrypt_object-----------------------
6072Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
6073  Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I", /*is_exact*/ false);
6074  assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
6075  if (objAESCryptKey == NULL) return (Node *) NULL;
6076
6077  // now have the array, need to get the start address of the K array
6078  Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
6079  return k_start;
6080}
6081
6082//------------------------------get_original_key_start_from_aescrypt_object-----------------------
6083Node * LibraryCallKit::get_original_key_start_from_aescrypt_object(Node *aescrypt_object) {
6084  Node* objAESCryptKey = load_field_from_object(aescrypt_object, "lastKey", "[B", /*is_exact*/ false);
6085  assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
6086  if (objAESCryptKey == NULL) return (Node *) NULL;
6087
6088  // now have the array, need to get the start address of the lastKey array
6089  Node* original_k_start = array_element_address(objAESCryptKey, intcon(0), T_BYTE);
6090  return original_k_start;
6091}
6092
6093//----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
6094// Return node representing slow path of predicate check.
6095// the pseudo code we want to emulate with this predicate is:
6096// for encryption:
6097//    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
6098// for decryption:
6099//    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
6100//    note cipher==plain is more conservative than the original java code but that's OK
6101//
6102Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
6103  // The receiver was checked for NULL already.
6104  Node* objCBC = argument(0);
6105
6106  // Load embeddedCipher field of CipherBlockChaining object.
6107  Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
6108
6109  // get AESCrypt klass for instanceOf check
6110  // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
6111  // will have same classloader as CipherBlockChaining object
6112  const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
6113  assert(tinst != NULL, "CBCobj is null");
6114  assert(tinst->klass()->is_loaded(), "CBCobj is not loaded");
6115
6116  // we want to do an instanceof comparison against the AESCrypt class
6117  ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6118  if (!klass_AESCrypt->is_loaded()) {
6119    // if AESCrypt is not even loaded, we never take the intrinsic fast path
6120    Node* ctrl = control();
6121    set_control(top()); // no regular fast path
6122    return ctrl;
6123  }
6124  ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6125
6126  Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
6127  Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
6128  Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6129
6130  Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6131
6132  // for encryption, we are done
6133  if (!decrypting)
6134    return instof_false;  // even if it is NULL
6135
6136  // for decryption, we need to add a further check to avoid
6137  // taking the intrinsic path when cipher and plain are the same
6138  // see the original java code for why.
6139  RegionNode* region = new RegionNode(3);
6140  region->init_req(1, instof_false);
6141  Node* src = argument(1);
6142  Node* dest = argument(4);
6143  Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
6144  Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
6145  Node* src_dest_conjoint = generate_guard(bool_src_dest, NULL, PROB_MIN);
6146  region->init_req(2, src_dest_conjoint);
6147
6148  record_for_igvn(region);
6149  return _gvn.transform(region);
6150}
6151
6152//------------------------------inline_ghash_processBlocks
6153bool LibraryCallKit::inline_ghash_processBlocks() {
6154  address stubAddr;
6155  const char *stubName;
6156  assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
6157
6158  stubAddr = StubRoutines::ghash_processBlocks();
6159  stubName = "ghash_processBlocks";
6160
6161  Node* data           = argument(0);
6162  Node* offset         = argument(1);
6163  Node* len            = argument(2);
6164  Node* state          = argument(3);
6165  Node* subkeyH        = argument(4);
6166
6167  Node* state_start  = array_element_address(state, intcon(0), T_LONG);
6168  assert(state_start, "state is NULL");
6169  Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
6170  assert(subkeyH_start, "subkeyH is NULL");
6171  Node* data_start  = array_element_address(data, offset, T_BYTE);
6172  assert(data_start, "data is NULL");
6173
6174  Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
6175                                  OptoRuntime::ghash_processBlocks_Type(),
6176                                  stubAddr, stubName, TypePtr::BOTTOM,
6177                                  state_start, subkeyH_start, data_start, len);
6178  return true;
6179}
6180
6181//------------------------------inline_sha_implCompress-----------------------
6182//
6183// Calculate SHA (i.e., SHA-1) for single-block byte[] array.
6184// void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
6185//
6186// Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
6187// void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
6188//
6189// Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
6190// void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
6191//
6192bool LibraryCallKit::inline_sha_implCompress(vmIntrinsics::ID id) {
6193  assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
6194
6195  Node* sha_obj = argument(0);
6196  Node* src     = argument(1); // type oop
6197  Node* ofs     = argument(2); // type int
6198
6199  const Type* src_type = src->Value(&_gvn);
6200  const TypeAryPtr* top_src = src_type->isa_aryptr();
6201  if (top_src  == NULL || top_src->klass()  == NULL) {
6202    // failed array check
6203    return false;
6204  }
6205  // Figure out the size and type of the elements we will be copying.
6206  BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
6207  if (src_elem != T_BYTE) {
6208    return false;
6209  }
6210  // 'src_start' points to src array + offset
6211  Node* src_start = array_element_address(src, ofs, src_elem);
6212  Node* state = NULL;
6213  address stubAddr;
6214  const char *stubName;
6215
6216  switch(id) {
6217  case vmIntrinsics::_sha_implCompress:
6218    assert(UseSHA1Intrinsics, "need SHA1 instruction support");
6219    state = get_state_from_sha_object(sha_obj);
6220    stubAddr = StubRoutines::sha1_implCompress();
6221    stubName = "sha1_implCompress";
6222    break;
6223  case vmIntrinsics::_sha2_implCompress:
6224    assert(UseSHA256Intrinsics, "need SHA256 instruction support");
6225    state = get_state_from_sha_object(sha_obj);
6226    stubAddr = StubRoutines::sha256_implCompress();
6227    stubName = "sha256_implCompress";
6228    break;
6229  case vmIntrinsics::_sha5_implCompress:
6230    assert(UseSHA512Intrinsics, "need SHA512 instruction support");
6231    state = get_state_from_sha5_object(sha_obj);
6232    stubAddr = StubRoutines::sha512_implCompress();
6233    stubName = "sha512_implCompress";
6234    break;
6235  default:
6236    fatal_unexpected_iid(id);
6237    return false;
6238  }
6239  if (state == NULL) return false;
6240
6241  // Call the stub.
6242  Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::sha_implCompress_Type(),
6243                                 stubAddr, stubName, TypePtr::BOTTOM,
6244                                 src_start, state);
6245
6246  return true;
6247}
6248
6249//------------------------------inline_digestBase_implCompressMB-----------------------
6250//
6251// Calculate SHA/SHA2/SHA5 for multi-block byte[] array.
6252// int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
6253//
6254bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
6255  assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,
6256         "need SHA1/SHA256/SHA512 instruction support");
6257  assert((uint)predicate < 3, "sanity");
6258  assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
6259
6260  Node* digestBase_obj = argument(0); // The receiver was checked for NULL already.
6261  Node* src            = argument(1); // byte[] array
6262  Node* ofs            = argument(2); // type int
6263  Node* limit          = argument(3); // type int
6264
6265  const Type* src_type = src->Value(&_gvn);
6266  const TypeAryPtr* top_src = src_type->isa_aryptr();
6267  if (top_src  == NULL || top_src->klass()  == NULL) {
6268    // failed array check
6269    return false;
6270  }
6271  // Figure out the size and type of the elements we will be copying.
6272  BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
6273  if (src_elem != T_BYTE) {
6274    return false;
6275  }
6276  // 'src_start' points to src array + offset
6277  Node* src_start = array_element_address(src, ofs, src_elem);
6278
6279  const char* klass_SHA_name = NULL;
6280  const char* stub_name = NULL;
6281  address     stub_addr = NULL;
6282  bool        long_state = false;
6283
6284  switch (predicate) {
6285  case 0:
6286    if (UseSHA1Intrinsics) {
6287      klass_SHA_name = "sun/security/provider/SHA";
6288      stub_name = "sha1_implCompressMB";
6289      stub_addr = StubRoutines::sha1_implCompressMB();
6290    }
6291    break;
6292  case 1:
6293    if (UseSHA256Intrinsics) {
6294      klass_SHA_name = "sun/security/provider/SHA2";
6295      stub_name = "sha256_implCompressMB";
6296      stub_addr = StubRoutines::sha256_implCompressMB();
6297    }
6298    break;
6299  case 2:
6300    if (UseSHA512Intrinsics) {
6301      klass_SHA_name = "sun/security/provider/SHA5";
6302      stub_name = "sha512_implCompressMB";
6303      stub_addr = StubRoutines::sha512_implCompressMB();
6304      long_state = true;
6305    }
6306    break;
6307  default:
6308    fatal(err_msg_res("unknown SHA intrinsic predicate: %d", predicate));
6309  }
6310  if (klass_SHA_name != NULL) {
6311    // get DigestBase klass to lookup for SHA klass
6312    const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
6313    assert(tinst != NULL, "digestBase_obj is not instance???");
6314    assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
6315
6316    ciKlass* klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));
6317    assert(klass_SHA->is_loaded(), "predicate checks that this class is loaded");
6318    ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();
6319    return inline_sha_implCompressMB(digestBase_obj, instklass_SHA, long_state, stub_addr, stub_name, src_start, ofs, limit);
6320  }
6321  return false;
6322}
6323//------------------------------inline_sha_implCompressMB-----------------------
6324bool LibraryCallKit::inline_sha_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_SHA,
6325                                               bool long_state, address stubAddr, const char *stubName,
6326                                               Node* src_start, Node* ofs, Node* limit) {
6327  const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_SHA);
6328  const TypeOopPtr* xtype = aklass->as_instance_type();
6329  Node* sha_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
6330  sha_obj = _gvn.transform(sha_obj);
6331
6332  Node* state;
6333  if (long_state) {
6334    state = get_state_from_sha5_object(sha_obj);
6335  } else {
6336    state = get_state_from_sha_object(sha_obj);
6337  }
6338  if (state == NULL) return false;
6339
6340  // Call the stub.
6341  Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6342                                 OptoRuntime::digestBase_implCompressMB_Type(),
6343                                 stubAddr, stubName, TypePtr::BOTTOM,
6344                                 src_start, state, ofs, limit);
6345  // return ofs (int)
6346  Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6347  set_result(result);
6348
6349  return true;
6350}
6351
6352//------------------------------get_state_from_sha_object-----------------------
6353Node * LibraryCallKit::get_state_from_sha_object(Node *sha_object) {
6354  Node* sha_state = load_field_from_object(sha_object, "state", "[I", /*is_exact*/ false);
6355  assert (sha_state != NULL, "wrong version of sun.security.provider.SHA/SHA2");
6356  if (sha_state == NULL) return (Node *) NULL;
6357
6358  // now have the array, need to get the start address of the state array
6359  Node* state = array_element_address(sha_state, intcon(0), T_INT);
6360  return state;
6361}
6362
6363//------------------------------get_state_from_sha5_object-----------------------
6364Node * LibraryCallKit::get_state_from_sha5_object(Node *sha_object) {
6365  Node* sha_state = load_field_from_object(sha_object, "state", "[J", /*is_exact*/ false);
6366  assert (sha_state != NULL, "wrong version of sun.security.provider.SHA5");
6367  if (sha_state == NULL) return (Node *) NULL;
6368
6369  // now have the array, need to get the start address of the state array
6370  Node* state = array_element_address(sha_state, intcon(0), T_LONG);
6371  return state;
6372}
6373
6374//----------------------------inline_digestBase_implCompressMB_predicate----------------------------
6375// Return node representing slow path of predicate check.
6376// the pseudo code we want to emulate with this predicate is:
6377//    if (digestBaseObj instanceof SHA/SHA2/SHA5) do_intrinsic, else do_javapath
6378//
6379Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
6380  assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,
6381         "need SHA1/SHA256/SHA512 instruction support");
6382  assert((uint)predicate < 3, "sanity");
6383
6384  // The receiver was checked for NULL already.
6385  Node* digestBaseObj = argument(0);
6386
6387  // get DigestBase klass for instanceOf check
6388  const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
6389  assert(tinst != NULL, "digestBaseObj is null");
6390  assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
6391
6392  const char* klass_SHA_name = NULL;
6393  switch (predicate) {
6394  case 0:
6395    if (UseSHA1Intrinsics) {
6396      // we want to do an instanceof comparison against the SHA class
6397      klass_SHA_name = "sun/security/provider/SHA";
6398    }
6399    break;
6400  case 1:
6401    if (UseSHA256Intrinsics) {
6402      // we want to do an instanceof comparison against the SHA2 class
6403      klass_SHA_name = "sun/security/provider/SHA2";
6404    }
6405    break;
6406  case 2:
6407    if (UseSHA512Intrinsics) {
6408      // we want to do an instanceof comparison against the SHA5 class
6409      klass_SHA_name = "sun/security/provider/SHA5";
6410    }
6411    break;
6412  default:
6413    fatal(err_msg_res("unknown SHA intrinsic predicate: %d", predicate));
6414  }
6415
6416  ciKlass* klass_SHA = NULL;
6417  if (klass_SHA_name != NULL) {
6418    klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));
6419  }
6420  if ((klass_SHA == NULL) || !klass_SHA->is_loaded()) {
6421    // if none of SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
6422    Node* ctrl = control();
6423    set_control(top()); // no intrinsic path
6424    return ctrl;
6425  }
6426  ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();
6427
6428  Node* instofSHA = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass_SHA)));
6429  Node* cmp_instof = _gvn.transform(new CmpINode(instofSHA, intcon(1)));
6430  Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6431  Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6432
6433  return instof_false;  // even if it is NULL
6434}
6435
6436bool LibraryCallKit::inline_profileBoolean() {
6437  Node* counts = argument(1);
6438  const TypeAryPtr* ary = NULL;
6439  ciArray* aobj = NULL;
6440  if (counts->is_Con()
6441      && (ary = counts->bottom_type()->isa_aryptr()) != NULL
6442      && (aobj = ary->const_oop()->as_array()) != NULL
6443      && (aobj->length() == 2)) {
6444    // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
6445    jint false_cnt = aobj->element_value(0).as_int();
6446    jint  true_cnt = aobj->element_value(1).as_int();
6447
6448    if (C->log() != NULL) {
6449      C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
6450                     false_cnt, true_cnt);
6451    }
6452
6453    if (false_cnt + true_cnt == 0) {
6454      // According to profile, never executed.
6455      uncommon_trap_exact(Deoptimization::Reason_intrinsic,
6456                          Deoptimization::Action_reinterpret);
6457      return true;
6458    }
6459
6460    // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
6461    // is a number of each value occurrences.
6462    Node* result = argument(0);
6463    if (false_cnt == 0 || true_cnt == 0) {
6464      // According to profile, one value has been never seen.
6465      int expected_val = (false_cnt == 0) ? 1 : 0;
6466
6467      Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
6468      Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
6469
6470      IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
6471      Node* fast_path = _gvn.transform(new IfTrueNode(check));
6472      Node* slow_path = _gvn.transform(new IfFalseNode(check));
6473
6474      { // Slow path: uncommon trap for never seen value and then reexecute
6475        // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
6476        // the value has been seen at least once.
6477        PreserveJVMState pjvms(this);
6478        PreserveReexecuteState preexecs(this);
6479        jvms()->set_should_reexecute(true);
6480
6481        set_control(slow_path);
6482        set_i_o(i_o());
6483
6484        uncommon_trap_exact(Deoptimization::Reason_intrinsic,
6485                            Deoptimization::Action_reinterpret);
6486      }
6487      // The guard for never seen value enables sharpening of the result and
6488      // returning a constant. It allows to eliminate branches on the same value
6489      // later on.
6490      set_control(fast_path);
6491      result = intcon(expected_val);
6492    }
6493    // Stop profiling.
6494    // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
6495    // By replacing method body with profile data (represented as ProfileBooleanNode
6496    // on IR level) we effectively disable profiling.
6497    // It enables full speed execution once optimized code is generated.
6498    Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
6499    C->record_for_igvn(profile);
6500    set_result(profile);
6501    return true;
6502  } else {
6503    // Continue profiling.
6504    // Profile data isn't available at the moment. So, execute method's bytecode version.
6505    // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
6506    // is compiled and counters aren't available since corresponding MethodHandle
6507    // isn't a compile-time constant.
6508    return false;
6509  }
6510}
6511
6512bool LibraryCallKit::inline_isCompileConstant() {
6513  Node* n = argument(0);
6514  set_result(n->is_Con() ? intcon(1) : intcon(0));
6515  return true;
6516}
6517