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