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