1 /* 2 * Copyright (c) 1999, 2023, 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 "ci/ciConstant.hpp" 27 #include "ci/ciEnv.hpp" 28 #include "ci/ciField.hpp" 29 #include "ci/ciInlineKlass.hpp" 30 #include "ci/ciInstance.hpp" 31 #include "ci/ciInstanceKlass.hpp" 32 #include "ci/ciMethod.hpp" 33 #include "ci/ciNullObject.hpp" 34 #include "ci/ciReplay.hpp" 35 #include "ci/ciSymbols.hpp" 36 #include "ci/ciUtilities.inline.hpp" 37 #include "classfile/javaClasses.hpp" 38 #include "classfile/javaClasses.inline.hpp" 39 #include "classfile/systemDictionary.hpp" 40 #include "classfile/vmClasses.hpp" 41 #include "classfile/vmSymbols.hpp" 42 #include "code/codeCache.hpp" 43 #include "code/scopeDesc.hpp" 44 #include "compiler/compilationLog.hpp" 45 #include "compiler/compilationPolicy.hpp" 46 #include "compiler/compileBroker.hpp" 47 #include "compiler/compilerEvent.hpp" 48 #include "compiler/compileLog.hpp" 49 #include "compiler/compileTask.hpp" 50 #include "compiler/disassembler.hpp" 51 #include "gc/shared/collectedHeap.inline.hpp" 52 #include "interpreter/bytecodeStream.hpp" 53 #include "interpreter/linkResolver.hpp" 54 #include "jfr/jfrEvents.hpp" 55 #include "jvm.h" 56 #include "logging/log.hpp" 57 #include "memory/allocation.inline.hpp" 58 #include "memory/oopFactory.hpp" 59 #include "memory/resourceArea.hpp" 60 #include "memory/universe.hpp" 61 #include "oops/constantPool.inline.hpp" 62 #include "oops/cpCache.inline.hpp" 63 #include "oops/method.inline.hpp" 64 #include "oops/methodData.hpp" 65 #include "oops/objArrayKlass.hpp" 66 #include "oops/objArrayOop.inline.hpp" 67 #include "oops/oop.inline.hpp" 68 #include "oops/resolvedIndyEntry.hpp" 69 #include "oops/symbolHandle.hpp" 70 #include "prims/jvmtiExport.hpp" 71 #include "prims/methodHandles.hpp" 72 #include "runtime/fieldDescriptor.inline.hpp" 73 #include "runtime/handles.inline.hpp" 74 #include "runtime/init.hpp" 75 #include "runtime/javaThread.hpp" 76 #include "runtime/jniHandles.inline.hpp" 77 #include "runtime/reflection.hpp" 78 #include "runtime/safepointVerifiers.hpp" 79 #include "runtime/sharedRuntime.hpp" 80 #include "utilities/dtrace.hpp" 81 #include "utilities/macros.hpp" 82 #ifdef COMPILER1 83 #include "c1/c1_Runtime1.hpp" 84 #endif 85 #ifdef COMPILER2 86 #include "opto/runtime.hpp" 87 #endif 88 89 // ciEnv 90 // 91 // This class is the top level broker for requests from the compiler 92 // to the VM. 93 94 ciObject* ciEnv::_null_object_instance; 95 96 #define VM_CLASS_DEFN(name, ignore_s) ciInstanceKlass* ciEnv::_##name = nullptr; 97 VM_CLASSES_DO(VM_CLASS_DEFN) 98 #undef VM_CLASS_DEFN 99 100 ciSymbol* ciEnv::_unloaded_cisymbol = nullptr; 101 ciInstanceKlass* ciEnv::_unloaded_ciinstance_klass = nullptr; 102 ciObjArrayKlass* ciEnv::_unloaded_ciobjarrayklass = nullptr; 103 104 jobject ciEnv::_ArrayIndexOutOfBoundsException_handle = nullptr; 105 jobject ciEnv::_ArrayStoreException_handle = nullptr; 106 jobject ciEnv::_ClassCastException_handle = nullptr; 107 108 #ifndef PRODUCT 109 static bool firstEnv = true; 110 #endif /* PRODUCT */ 111 112 // ------------------------------------------------------------------ 113 // ciEnv::ciEnv 114 ciEnv::ciEnv(CompileTask* task) 115 : _ciEnv_arena(mtCompiler) { 116 VM_ENTRY_MARK; 117 118 // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc. 119 thread->set_env(this); 120 assert(ciEnv::current() == this, "sanity"); 121 122 _oop_recorder = nullptr; 123 _debug_info = nullptr; 124 _dependencies = nullptr; 125 _failure_reason = nullptr; 126 _inc_decompile_count_on_failure = true; 127 _compilable = MethodCompilable; 128 _break_at_compile = false; 129 _compiler_data = nullptr; 130 #ifndef PRODUCT 131 assert(!firstEnv, "not initialized properly"); 132 #endif /* !PRODUCT */ 133 134 _num_inlined_bytecodes = 0; 135 assert(task == nullptr || thread->task() == task, "sanity"); 136 if (task != nullptr) { 137 task->mark_started(os::elapsed_counter()); 138 } 139 _task = task; 140 _log = nullptr; 141 142 // Temporary buffer for creating symbols and such. 143 _name_buffer = nullptr; 144 _name_buffer_len = 0; 145 146 _arena = &_ciEnv_arena; 147 _factory = new (_arena) ciObjectFactory(_arena, 128); 148 149 // Preload commonly referenced system ciObjects. 150 151 // During VM initialization, these instances have not yet been created. 152 // Assertions ensure that these instances are not accessed before 153 // their initialization. 154 155 assert(Universe::is_fully_initialized(), "should be complete"); 156 157 oop o = Universe::null_ptr_exception_instance(); 158 assert(o != nullptr, "should have been initialized"); 159 _NullPointerException_instance = get_object(o)->as_instance(); 160 o = Universe::arithmetic_exception_instance(); 161 assert(o != nullptr, "should have been initialized"); 162 _ArithmeticException_instance = get_object(o)->as_instance(); 163 164 _ArrayIndexOutOfBoundsException_instance = nullptr; 165 _ArrayStoreException_instance = nullptr; 166 _ClassCastException_instance = nullptr; 167 _the_null_string = nullptr; 168 _the_min_jint_string = nullptr; 169 170 _jvmti_redefinition_count = 0; 171 _jvmti_can_hotswap_or_post_breakpoint = false; 172 _jvmti_can_access_local_variables = false; 173 _jvmti_can_post_on_exceptions = false; 174 _jvmti_can_pop_frame = false; 175 176 _dyno_klasses = nullptr; 177 _dyno_locs = nullptr; 178 _dyno_name[0] = '\0'; 179 } 180 181 // Record components of a location descriptor string. Components are appended by the constructor and 182 // removed by the destructor, like a stack, so scope matters. These location descriptors are used to 183 // locate dynamic classes, and terminate at a Method* or oop field associated with dynamic/hidden class. 184 // 185 // Example use: 186 // 187 // { 188 // RecordLocation fp(this, "field1"); 189 // // location: "field1" 190 // { RecordLocation fp(this, " field2"); // location: "field1 field2" } 191 // // location: "field1" 192 // { RecordLocation fp(this, " field3"); // location: "field1 field3" } 193 // // location: "field1" 194 // } 195 // // location: "" 196 // 197 // Examples of actual locations 198 // @bci compiler/ciReplay/CiReplayBase$TestMain test (I)V 1 <appendix> argL0 ; 199 // // resolve invokedynamic at bci 1 of TestMain.test, then read field "argL0" from appendix 200 // @bci compiler/ciReplay/CiReplayBase$TestMain main ([Ljava/lang/String;)V 0 <appendix> form vmentry <vmtarget> ; 201 // // resolve invokedynamic at bci 0 of TestMain.main, then read field "form.vmentry.method.vmtarget" from appendix 202 // @cpi compiler/ciReplay/CiReplayBase$TestMain 56 form vmentry <vmtarget> ; 203 // // resolve MethodHandle at cpi 56 of TestMain, then read field "vmentry.method.vmtarget" from resolved MethodHandle 204 class RecordLocation { 205 private: 206 char* end; 207 208 ATTRIBUTE_PRINTF(3, 4) 209 void push(ciEnv* ci, const char* fmt, ...) { 210 va_list args; 211 va_start(args, fmt); 212 push_va(ci, fmt, args); 213 va_end(args); 214 } 215 216 public: 217 ATTRIBUTE_PRINTF(3, 0) 218 void push_va(ciEnv* ci, const char* fmt, va_list args) { 219 char *e = ci->_dyno_name + strlen(ci->_dyno_name); 220 char *m = ci->_dyno_name + ARRAY_SIZE(ci->_dyno_name) - 1; 221 os::vsnprintf(e, m - e, fmt, args); 222 assert(strlen(ci->_dyno_name) < (ARRAY_SIZE(ci->_dyno_name) - 1), "overflow"); 223 } 224 225 // append a new component 226 ATTRIBUTE_PRINTF(3, 4) 227 RecordLocation(ciEnv* ci, const char* fmt, ...) { 228 end = ci->_dyno_name + strlen(ci->_dyno_name); 229 va_list args; 230 va_start(args, fmt); 231 push(ci, " "); 232 push_va(ci, fmt, args); 233 va_end(args); 234 } 235 236 // reset to previous state 237 ~RecordLocation() { 238 *end = '\0'; 239 } 240 }; 241 242 ciEnv::ciEnv(Arena* arena) : _ciEnv_arena(mtCompiler) { 243 ASSERT_IN_VM; 244 245 // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc. 246 CompilerThread* current_thread = CompilerThread::current(); 247 assert(current_thread->env() == nullptr, "must be"); 248 current_thread->set_env(this); 249 assert(ciEnv::current() == this, "sanity"); 250 251 _oop_recorder = nullptr; 252 _debug_info = nullptr; 253 _dependencies = nullptr; 254 _failure_reason = nullptr; 255 _inc_decompile_count_on_failure = true; 256 _compilable = MethodCompilable_never; 257 _break_at_compile = false; 258 _compiler_data = nullptr; 259 #ifndef PRODUCT 260 assert(firstEnv, "must be first"); 261 firstEnv = false; 262 #endif /* !PRODUCT */ 263 264 _num_inlined_bytecodes = 0; 265 _task = nullptr; 266 _log = nullptr; 267 268 // Temporary buffer for creating symbols and such. 269 _name_buffer = nullptr; 270 _name_buffer_len = 0; 271 272 _arena = arena; 273 _factory = new (_arena) ciObjectFactory(_arena, 128); 274 275 // Preload commonly referenced system ciObjects. 276 277 // During VM initialization, these instances have not yet been created. 278 // Assertions ensure that these instances are not accessed before 279 // their initialization. 280 281 assert(Universe::is_fully_initialized(), "must be"); 282 283 _NullPointerException_instance = nullptr; 284 _ArithmeticException_instance = nullptr; 285 _ArrayIndexOutOfBoundsException_instance = nullptr; 286 _ArrayStoreException_instance = nullptr; 287 _ClassCastException_instance = nullptr; 288 _the_null_string = nullptr; 289 _the_min_jint_string = nullptr; 290 291 _jvmti_redefinition_count = 0; 292 _jvmti_can_hotswap_or_post_breakpoint = false; 293 _jvmti_can_access_local_variables = false; 294 _jvmti_can_post_on_exceptions = false; 295 _jvmti_can_pop_frame = false; 296 297 _dyno_klasses = nullptr; 298 _dyno_locs = nullptr; 299 } 300 301 ciEnv::~ciEnv() { 302 GUARDED_VM_ENTRY( 303 CompilerThread* current_thread = CompilerThread::current(); 304 _factory->remove_symbols(); 305 // Need safepoint to clear the env on the thread. RedefineClasses might 306 // be reading it. 307 current_thread->set_env(nullptr); 308 ) 309 } 310 311 // ------------------------------------------------------------------ 312 // Cache Jvmti state 313 bool ciEnv::cache_jvmti_state() { 314 VM_ENTRY_MARK; 315 // Get Jvmti capabilities under lock to get consistent values. 316 MutexLocker mu(JvmtiThreadState_lock); 317 _jvmti_redefinition_count = JvmtiExport::redefinition_count(); 318 _jvmti_can_hotswap_or_post_breakpoint = JvmtiExport::can_hotswap_or_post_breakpoint(); 319 _jvmti_can_access_local_variables = JvmtiExport::can_access_local_variables(); 320 _jvmti_can_post_on_exceptions = JvmtiExport::can_post_on_exceptions(); 321 _jvmti_can_pop_frame = JvmtiExport::can_pop_frame(); 322 _jvmti_can_get_owned_monitor_info = JvmtiExport::can_get_owned_monitor_info(); 323 _jvmti_can_walk_any_space = JvmtiExport::can_walk_any_space(); 324 return _task != nullptr && _task->method()->is_old(); 325 } 326 327 bool ciEnv::jvmti_state_changed() const { 328 // Some classes were redefined 329 if (_jvmti_redefinition_count != JvmtiExport::redefinition_count()) { 330 return true; 331 } 332 333 if (!_jvmti_can_access_local_variables && 334 JvmtiExport::can_access_local_variables()) { 335 return true; 336 } 337 if (!_jvmti_can_hotswap_or_post_breakpoint && 338 JvmtiExport::can_hotswap_or_post_breakpoint()) { 339 return true; 340 } 341 if (!_jvmti_can_post_on_exceptions && 342 JvmtiExport::can_post_on_exceptions()) { 343 return true; 344 } 345 if (!_jvmti_can_pop_frame && 346 JvmtiExport::can_pop_frame()) { 347 return true; 348 } 349 if (!_jvmti_can_get_owned_monitor_info && 350 JvmtiExport::can_get_owned_monitor_info()) { 351 return true; 352 } 353 if (!_jvmti_can_walk_any_space && 354 JvmtiExport::can_walk_any_space()) { 355 return true; 356 } 357 358 return false; 359 } 360 361 // ------------------------------------------------------------------ 362 // Cache DTrace flags 363 void ciEnv::cache_dtrace_flags() { 364 // Need lock? 365 _dtrace_method_probes = DTraceMethodProbes; 366 _dtrace_alloc_probes = DTraceAllocProbes; 367 } 368 369 // ------------------------------------------------------------------ 370 // helper for lazy exception creation 371 ciInstance* ciEnv::get_or_create_exception(jobject& handle, Symbol* name) { 372 VM_ENTRY_MARK; 373 if (handle == nullptr) { 374 // Cf. universe.cpp, creation of Universe::_null_ptr_exception_instance. 375 InstanceKlass* ik = SystemDictionary::find_instance_klass(THREAD, name, Handle(), Handle()); 376 jobject objh = nullptr; 377 if (ik != nullptr) { 378 oop obj = ik->allocate_instance(THREAD); 379 if (!HAS_PENDING_EXCEPTION) 380 objh = JNIHandles::make_global(Handle(THREAD, obj)); 381 } 382 if (HAS_PENDING_EXCEPTION) { 383 CLEAR_PENDING_EXCEPTION; 384 } else { 385 handle = objh; 386 } 387 } 388 oop obj = JNIHandles::resolve(handle); 389 return obj == nullptr? nullptr: get_object(obj)->as_instance(); 390 } 391 392 ciInstanceKlass* ciEnv::get_box_klass_for_primitive_type(BasicType type) { 393 switch (type) { 394 case T_BOOLEAN: return Boolean_klass(); 395 case T_BYTE : return Byte_klass(); 396 case T_CHAR : return Character_klass(); 397 case T_SHORT : return Short_klass(); 398 case T_INT : return Integer_klass(); 399 case T_LONG : return Long_klass(); 400 case T_FLOAT : return Float_klass(); 401 case T_DOUBLE : return Double_klass(); 402 403 default: 404 assert(false, "not a primitive: %s", type2name(type)); 405 return nullptr; 406 } 407 } 408 409 ciInstance* ciEnv::ArrayIndexOutOfBoundsException_instance() { 410 if (_ArrayIndexOutOfBoundsException_instance == nullptr) { 411 _ArrayIndexOutOfBoundsException_instance 412 = get_or_create_exception(_ArrayIndexOutOfBoundsException_handle, 413 vmSymbols::java_lang_ArrayIndexOutOfBoundsException()); 414 } 415 return _ArrayIndexOutOfBoundsException_instance; 416 } 417 ciInstance* ciEnv::ArrayStoreException_instance() { 418 if (_ArrayStoreException_instance == nullptr) { 419 _ArrayStoreException_instance 420 = get_or_create_exception(_ArrayStoreException_handle, 421 vmSymbols::java_lang_ArrayStoreException()); 422 } 423 return _ArrayStoreException_instance; 424 } 425 ciInstance* ciEnv::ClassCastException_instance() { 426 if (_ClassCastException_instance == nullptr) { 427 _ClassCastException_instance 428 = get_or_create_exception(_ClassCastException_handle, 429 vmSymbols::java_lang_ClassCastException()); 430 } 431 return _ClassCastException_instance; 432 } 433 434 ciInstance* ciEnv::the_null_string() { 435 if (_the_null_string == nullptr) { 436 VM_ENTRY_MARK; 437 _the_null_string = get_object(Universe::the_null_string())->as_instance(); 438 } 439 return _the_null_string; 440 } 441 442 ciInstance* ciEnv::the_min_jint_string() { 443 if (_the_min_jint_string == nullptr) { 444 VM_ENTRY_MARK; 445 _the_min_jint_string = get_object(Universe::the_min_jint_string())->as_instance(); 446 } 447 return _the_min_jint_string; 448 } 449 450 // ------------------------------------------------------------------ 451 // ciEnv::get_method_from_handle 452 ciMethod* ciEnv::get_method_from_handle(Method* method) { 453 VM_ENTRY_MARK; 454 return get_metadata(method)->as_method(); 455 } 456 457 // ------------------------------------------------------------------ 458 // ciEnv::check_klass_accessiblity 459 // 460 // Note: the logic of this method should mirror the logic of 461 // ConstantPool::verify_constant_pool_resolve. 462 bool ciEnv::check_klass_accessibility(ciKlass* accessing_klass, 463 Klass* resolved_klass) { 464 if (accessing_klass == nullptr || !accessing_klass->is_loaded()) { 465 return true; 466 } 467 if (accessing_klass->is_obj_array_klass()) { 468 accessing_klass = accessing_klass->as_obj_array_klass()->base_element_klass(); 469 } 470 if (!accessing_klass->is_instance_klass()) { 471 return true; 472 } 473 474 if (resolved_klass->is_objArray_klass()) { 475 // Find the element klass, if this is an array. 476 resolved_klass = ObjArrayKlass::cast(resolved_klass)->bottom_klass(); 477 } 478 if (resolved_klass->is_instance_klass()) { 479 return (Reflection::verify_class_access(accessing_klass->get_Klass(), 480 InstanceKlass::cast(resolved_klass), 481 true) == Reflection::ACCESS_OK); 482 } 483 return true; 484 } 485 486 // ------------------------------------------------------------------ 487 // ciEnv::get_klass_by_name_impl 488 ciKlass* ciEnv::get_klass_by_name_impl(ciKlass* accessing_klass, 489 const constantPoolHandle& cpool, 490 ciSymbol* name, 491 bool require_local) { 492 ASSERT_IN_VM; 493 Thread* current = Thread::current(); 494 495 // Now we need to check the SystemDictionary 496 Symbol* sym = name->get_symbol(); 497 if (Signature::has_envelope(sym)) { 498 // This is a name from a signature. Strip off the trimmings. 499 // Call recursive to keep scope of strippedsym. 500 TempNewSymbol strippedsym = Signature::strip_envelope(sym); 501 ciSymbol* strippedname = get_symbol(strippedsym); 502 return get_klass_by_name_impl(accessing_klass, cpool, strippedname, require_local); 503 } 504 505 // Check for prior unloaded klass. The SystemDictionary's answers 506 // can vary over time but the compiler needs consistency. 507 ciKlass* unloaded_klass = check_get_unloaded_klass(accessing_klass, name); 508 if (unloaded_klass != nullptr) { 509 if (require_local) return nullptr; 510 return unloaded_klass; 511 } 512 513 Handle loader; 514 Handle domain; 515 if (accessing_klass != nullptr) { 516 loader = Handle(current, accessing_klass->loader()); 517 domain = Handle(current, accessing_klass->protection_domain()); 518 } 519 520 Klass* found_klass = require_local ? 521 SystemDictionary::find_instance_or_array_klass(current, sym, loader, domain) : 522 SystemDictionary::find_constrained_instance_or_array_klass(current, sym, loader); 523 524 // If we fail to find an array klass, look again for its element type. 525 // The element type may be available either locally or via constraints. 526 // In either case, if we can find the element type in the system dictionary, 527 // we must build an array type around it. The CI requires array klasses 528 // to be loaded if their element klasses are loaded, except when memory 529 // is exhausted. 530 if (Signature::is_array(sym) && 531 (sym->char_at(1) == JVM_SIGNATURE_ARRAY || 532 sym->char_at(1) == JVM_SIGNATURE_CLASS )) { 533 // We have an unloaded array. 534 // Build it on the fly if the element class exists. 535 SignatureStream ss(sym, false); 536 ss.skip_array_prefix(1); 537 // Get element ciKlass recursively. 538 ciKlass* elem_klass = 539 get_klass_by_name_impl(accessing_klass, 540 cpool, 541 get_symbol(ss.as_symbol()), 542 require_local); 543 if (elem_klass != nullptr && elem_klass->is_loaded()) { 544 // Now make an array for it 545 return ciArrayKlass::make(elem_klass); 546 } 547 } 548 549 if (found_klass == nullptr && !cpool.is_null() && cpool->has_preresolution()) { 550 // Look inside the constant pool for pre-resolved class entries. 551 for (int i = cpool->length() - 1; i >= 1; i--) { 552 if (cpool->tag_at(i).is_klass()) { 553 Klass* kls = cpool->resolved_klass_at(i); 554 if (kls->name() == sym) { 555 found_klass = kls; 556 break; 557 } 558 } 559 } 560 } 561 562 if (found_klass != nullptr) { 563 // Found it. Build a CI handle. 564 return get_klass(found_klass); 565 } 566 567 if (require_local) return nullptr; 568 569 // Not yet loaded into the VM, or not governed by loader constraints. 570 // Make a CI representative for it. 571 int i = 0; 572 while (sym->char_at(i) == JVM_SIGNATURE_ARRAY) { 573 i++; 574 } 575 return get_unloaded_klass(accessing_klass, name); 576 } 577 578 // ------------------------------------------------------------------ 579 // ciEnv::get_klass_by_name 580 ciKlass* ciEnv::get_klass_by_name(ciKlass* accessing_klass, 581 ciSymbol* klass_name, 582 bool require_local) { 583 GUARDED_VM_ENTRY(return get_klass_by_name_impl(accessing_klass, 584 constantPoolHandle(), 585 klass_name, 586 require_local);) 587 } 588 589 // ------------------------------------------------------------------ 590 // ciEnv::get_klass_by_index_impl 591 // 592 // Implementation of get_klass_by_index. 593 ciKlass* ciEnv::get_klass_by_index_impl(const constantPoolHandle& cpool, 594 int index, 595 bool& is_accessible, 596 ciInstanceKlass* accessor) { 597 Klass* klass = nullptr; 598 Symbol* klass_name = nullptr; 599 600 if (cpool->tag_at(index).is_symbol()) { 601 klass_name = cpool->symbol_at(index); 602 } else { 603 // Check if it's resolved if it's not a symbol constant pool entry. 604 klass = ConstantPool::klass_at_if_loaded(cpool, index); 605 // Try to look it up by name. 606 if (klass == nullptr) { 607 klass_name = cpool->klass_name_at(index); 608 } 609 } 610 611 if (klass == nullptr) { 612 // Not found in constant pool. Use the name to do the lookup. 613 ciKlass* k = get_klass_by_name_impl(accessor, 614 cpool, 615 get_symbol(klass_name), 616 false); 617 // Calculate accessibility the hard way. 618 if (!k->is_loaded()) { 619 is_accessible = false; 620 } else if (k->loader() != accessor->loader() && 621 get_klass_by_name_impl(accessor, cpool, k->name(), true) == nullptr) { 622 // Loaded only remotely. Not linked yet. 623 is_accessible = false; 624 } else { 625 // Linked locally, and we must also check public/private, etc. 626 is_accessible = check_klass_accessibility(accessor, k->get_Klass()); 627 } 628 return k; 629 } 630 631 // Check for prior unloaded klass. The SystemDictionary's answers 632 // can vary over time but the compiler needs consistency. 633 ciSymbol* name = get_symbol(klass->name()); 634 ciKlass* unloaded_klass = check_get_unloaded_klass(accessor, name); 635 if (unloaded_klass != nullptr) { 636 is_accessible = false; 637 return unloaded_klass; 638 } 639 640 // It is known to be accessible, since it was found in the constant pool. 641 ciKlass* ciKlass = get_klass(klass); 642 is_accessible = true; 643 if (ReplayCompiles && ciKlass == _unloaded_ciinstance_klass) { 644 // Klass was unresolved at replay dump time and therefore not accessible. 645 is_accessible = false; 646 } 647 return ciKlass; 648 } 649 650 // ------------------------------------------------------------------ 651 // ciEnv::get_klass_by_index 652 // 653 // Get a klass from the constant pool. 654 ciKlass* ciEnv::get_klass_by_index(const constantPoolHandle& cpool, 655 int index, 656 bool& is_accessible, 657 ciInstanceKlass* accessor) { 658 GUARDED_VM_ENTRY(return get_klass_by_index_impl(cpool, index, is_accessible, accessor);) 659 } 660 661 // ------------------------------------------------------------------ 662 // ciEnv::unbox_primitive_value 663 // 664 // Unbox a primitive and return it as a ciConstant. 665 ciConstant ciEnv::unbox_primitive_value(ciObject* cibox, BasicType expected_bt) { 666 jvalue value; 667 BasicType bt = java_lang_boxing_object::get_value(cibox->get_oop(), &value); 668 if (bt != expected_bt && expected_bt != T_ILLEGAL) { 669 assert(false, "type mismatch: %s vs %s", type2name(expected_bt), cibox->klass()->name()->as_klass_external_name()); 670 return ciConstant(); 671 } 672 switch (bt) { 673 case T_BOOLEAN: return ciConstant(bt, value.z); 674 case T_BYTE: return ciConstant(bt, value.b); 675 case T_SHORT: return ciConstant(bt, value.s); 676 case T_CHAR: return ciConstant(bt, value.c); 677 case T_INT: return ciConstant(bt, value.i); 678 case T_LONG: return ciConstant(value.j); 679 case T_FLOAT: return ciConstant(value.f); 680 case T_DOUBLE: return ciConstant(value.d); 681 682 default: 683 assert(false, "not a primitive type: %s", type2name(bt)); 684 return ciConstant(); 685 } 686 } 687 688 // ------------------------------------------------------------------ 689 // ciEnv::get_resolved_constant 690 // 691 ciConstant ciEnv::get_resolved_constant(const constantPoolHandle& cpool, int obj_index) { 692 assert(obj_index >= 0, ""); 693 oop obj = cpool->resolved_reference_at(obj_index); 694 if (obj == nullptr) { 695 // Unresolved constant. It is resolved when the corresponding slot contains a non-null reference. 696 // Null constant is represented as a sentinel (non-null) value. 697 return ciConstant(); 698 } else if (obj == Universe::the_null_sentinel()) { 699 return ciConstant(T_OBJECT, get_object(nullptr)); 700 } else { 701 ciObject* ciobj = get_object(obj); 702 if (ciobj->is_array()) { 703 return ciConstant(T_ARRAY, ciobj); 704 } else { 705 int cp_index = cpool->object_to_cp_index(obj_index); 706 BasicType bt = cpool->basic_type_for_constant_at(cp_index); 707 if (is_java_primitive(bt)) { 708 assert(cpool->tag_at(cp_index).is_dynamic_constant(), "sanity"); 709 return unbox_primitive_value(ciobj, bt); 710 } else { 711 assert(ciobj->is_instance(), "should be an instance"); 712 return ciConstant(T_OBJECT, ciobj); 713 } 714 } 715 } 716 } 717 718 // ------------------------------------------------------------------ 719 // ciEnv::get_constant_by_index_impl 720 // 721 // Implementation of get_constant_by_index(). 722 ciConstant ciEnv::get_constant_by_index_impl(const constantPoolHandle& cpool, 723 int index, int obj_index, 724 ciInstanceKlass* accessor) { 725 if (obj_index >= 0) { 726 ciConstant con = get_resolved_constant(cpool, obj_index); 727 if (con.is_valid()) { 728 return con; 729 } 730 } 731 constantTag tag = cpool->tag_at(index); 732 if (tag.is_int()) { 733 return ciConstant(T_INT, (jint)cpool->int_at(index)); 734 } else if (tag.is_long()) { 735 return ciConstant((jlong)cpool->long_at(index)); 736 } else if (tag.is_float()) { 737 return ciConstant((jfloat)cpool->float_at(index)); 738 } else if (tag.is_double()) { 739 return ciConstant((jdouble)cpool->double_at(index)); 740 } else if (tag.is_string()) { 741 EXCEPTION_CONTEXT; 742 assert(obj_index >= 0, "should have an object index"); 743 oop string = cpool->string_at(index, obj_index, THREAD); 744 if (HAS_PENDING_EXCEPTION) { 745 CLEAR_PENDING_EXCEPTION; 746 record_out_of_memory_failure(); 747 return ciConstant(); 748 } 749 ciInstance* constant = get_object(string)->as_instance(); 750 return ciConstant(T_OBJECT, constant); 751 } else if (tag.is_unresolved_klass_in_error()) { 752 return ciConstant(T_OBJECT, get_unloaded_klass_mirror(nullptr)); 753 } else if (tag.is_klass() || tag.is_unresolved_klass()) { 754 bool will_link; 755 ciKlass* klass = get_klass_by_index_impl(cpool, index, will_link, accessor); 756 ciInstance* mirror = (will_link ? klass->java_mirror() : get_unloaded_klass_mirror(klass)); 757 return ciConstant(T_OBJECT, mirror); 758 } else if (tag.is_method_type() || tag.is_method_type_in_error()) { 759 // must execute Java code to link this CP entry into cache[i].f1 760 assert(obj_index >= 0, "should have an object index"); 761 ciSymbol* signature = get_symbol(cpool->method_type_signature_at(index)); 762 ciObject* ciobj = get_unloaded_method_type_constant(signature); 763 return ciConstant(T_OBJECT, ciobj); 764 } else if (tag.is_method_handle() || tag.is_method_handle_in_error()) { 765 // must execute Java code to link this CP entry into cache[i].f1 766 assert(obj_index >= 0, "should have an object index"); 767 bool ignore_will_link; 768 int ref_kind = cpool->method_handle_ref_kind_at(index); 769 int callee_index = cpool->method_handle_klass_index_at(index); 770 ciKlass* callee = get_klass_by_index_impl(cpool, callee_index, ignore_will_link, accessor); 771 ciSymbol* name = get_symbol(cpool->method_handle_name_ref_at(index)); 772 ciSymbol* signature = get_symbol(cpool->method_handle_signature_ref_at(index)); 773 ciObject* ciobj = get_unloaded_method_handle_constant(callee, name, signature, ref_kind); 774 return ciConstant(T_OBJECT, ciobj); 775 } else if (tag.is_dynamic_constant() || tag.is_dynamic_constant_in_error()) { 776 assert(obj_index >= 0, "should have an object index"); 777 return ciConstant(T_OBJECT, unloaded_ciinstance()); // unresolved dynamic constant 778 } else { 779 assert(false, "unknown tag: %d (%s)", tag.value(), tag.internal_name()); 780 return ciConstant(); 781 } 782 } 783 784 // ------------------------------------------------------------------ 785 // ciEnv::get_constant_by_index 786 // 787 // Pull a constant out of the constant pool. How appropriate. 788 // 789 // Implementation note: this query is currently in no way cached. 790 ciConstant ciEnv::get_constant_by_index(const constantPoolHandle& cpool, 791 int pool_index, int cache_index, 792 ciInstanceKlass* accessor) { 793 GUARDED_VM_ENTRY(return get_constant_by_index_impl(cpool, pool_index, cache_index, accessor);) 794 } 795 796 // ------------------------------------------------------------------ 797 // ciEnv::get_field_by_index_impl 798 // 799 // Implementation of get_field_by_index. 800 // 801 // Implementation note: the results of field lookups are cached 802 // in the accessor klass. 803 ciField* ciEnv::get_field_by_index_impl(ciInstanceKlass* accessor, 804 int index, Bytecodes::Code bc) { 805 ciConstantPoolCache* cache = accessor->field_cache(); 806 if (cache == nullptr) { 807 ciField* field = new (arena()) ciField(accessor, index, bc); 808 return field; 809 } else { 810 ciField* field = (ciField*)cache->get(index); 811 if (field == nullptr) { 812 field = new (arena()) ciField(accessor, index, bc); 813 cache->insert(index, field); 814 } 815 return field; 816 } 817 } 818 819 // ------------------------------------------------------------------ 820 // ciEnv::get_field_by_index 821 // 822 // Get a field by index from a klass's constant pool. 823 ciField* ciEnv::get_field_by_index(ciInstanceKlass* accessor, 824 int index, Bytecodes::Code bc) { 825 GUARDED_VM_ENTRY(return get_field_by_index_impl(accessor, index, bc);) 826 } 827 828 // ------------------------------------------------------------------ 829 // ciEnv::lookup_method 830 // 831 // Perform an appropriate method lookup based on accessor, holder, 832 // name, signature, and bytecode. 833 Method* ciEnv::lookup_method(ciInstanceKlass* accessor, 834 ciKlass* holder, 835 Symbol* name, 836 Symbol* sig, 837 Bytecodes::Code bc, 838 constantTag tag) { 839 InstanceKlass* accessor_klass = accessor->get_instanceKlass(); 840 Klass* holder_klass = holder->get_Klass(); 841 842 // Accessibility checks are performed in ciEnv::get_method_by_index_impl. 843 assert(check_klass_accessibility(accessor, holder_klass), "holder not accessible"); 844 845 LinkInfo link_info(holder_klass, name, sig, accessor_klass, 846 LinkInfo::AccessCheck::required, 847 LinkInfo::LoaderConstraintCheck::required, 848 tag); 849 switch (bc) { 850 case Bytecodes::_invokestatic: 851 return LinkResolver::resolve_static_call_or_null(link_info); 852 case Bytecodes::_invokespecial: 853 return LinkResolver::resolve_special_call_or_null(link_info); 854 case Bytecodes::_invokeinterface: 855 return LinkResolver::linktime_resolve_interface_method_or_null(link_info); 856 case Bytecodes::_invokevirtual: 857 return LinkResolver::linktime_resolve_virtual_method_or_null(link_info); 858 default: 859 fatal("Unhandled bytecode: %s", Bytecodes::name(bc)); 860 return nullptr; // silence compiler warnings 861 } 862 } 863 864 865 // ------------------------------------------------------------------ 866 // ciEnv::get_method_by_index_impl 867 ciMethod* ciEnv::get_method_by_index_impl(const constantPoolHandle& cpool, 868 int index, Bytecodes::Code bc, 869 ciInstanceKlass* accessor) { 870 assert(cpool.not_null(), "need constant pool"); 871 assert(accessor != nullptr, "need origin of access"); 872 if (bc == Bytecodes::_invokedynamic) { 873 // FIXME: code generation could allow for null (unlinked) call site 874 // The call site could be made patchable as follows: 875 // Load the appendix argument from the constant pool. 876 // Test the appendix argument and jump to a known deopt routine if it is null. 877 // Jump through a patchable call site, which is initially a deopt routine. 878 // Patch the call site to the nmethod entry point of the static compiled lambda form. 879 // As with other two-component call sites, both values must be independently verified. 880 int indy_index = cpool->decode_invokedynamic_index(index); 881 assert (indy_index >= 0, "should be"); 882 assert(indy_index < cpool->cache()->resolved_indy_entries_length(), "impossible"); 883 Method* adapter = cpool->resolved_indy_entry_at(indy_index)->method(); 884 // Resolved if the adapter is non null. 885 if (adapter != nullptr) { 886 return get_method(adapter); 887 } 888 889 // Fake a method that is equivalent to a declared method. 890 ciInstanceKlass* holder = get_instance_klass(vmClasses::MethodHandle_klass()); 891 ciSymbol* name = ciSymbols::invokeBasic_name(); 892 ciSymbol* signature = get_symbol(cpool->signature_ref_at(index, bc)); 893 return get_unloaded_method(holder, name, signature, accessor); 894 } else { 895 const int holder_index = cpool->klass_ref_index_at(index, bc); 896 bool holder_is_accessible; 897 ciKlass* holder = get_klass_by_index_impl(cpool, holder_index, holder_is_accessible, accessor); 898 899 // Get the method's name and signature. 900 Symbol* name_sym = cpool->name_ref_at(index, bc); 901 Symbol* sig_sym = cpool->signature_ref_at(index, bc); 902 903 if (cpool->has_preresolution() 904 || ((holder == ciEnv::MethodHandle_klass() || holder == ciEnv::VarHandle_klass()) && 905 MethodHandles::is_signature_polymorphic_name(holder->get_Klass(), name_sym))) { 906 // Short-circuit lookups for JSR 292-related call sites. 907 // That is, do not rely only on name-based lookups, because they may fail 908 // if the names are not resolvable in the boot class loader (7056328). 909 switch (bc) { 910 case Bytecodes::_invokevirtual: 911 case Bytecodes::_invokeinterface: 912 case Bytecodes::_invokespecial: 913 case Bytecodes::_invokestatic: 914 { 915 Method* m = ConstantPool::method_at_if_loaded(cpool, index); 916 if (m != nullptr) { 917 return get_method(m); 918 } 919 } 920 break; 921 default: 922 break; 923 } 924 } 925 926 if (holder_is_accessible) { // Our declared holder is loaded. 927 constantTag tag = cpool->tag_ref_at(index, bc); 928 assert(accessor->get_instanceKlass() == cpool->pool_holder(), "not the pool holder?"); 929 Method* m = lookup_method(accessor, holder, name_sym, sig_sym, bc, tag); 930 if (m != nullptr && 931 (bc == Bytecodes::_invokestatic 932 ? m->method_holder()->is_not_initialized() 933 : !m->method_holder()->is_loaded())) { 934 m = nullptr; 935 } 936 if (m != nullptr && ReplayCompiles && !ciReplay::is_loaded(m)) { 937 m = nullptr; 938 } 939 if (m != nullptr) { 940 // We found the method. 941 return get_method(m); 942 } 943 } 944 945 // Either the declared holder was not loaded, or the method could 946 // not be found. Create a dummy ciMethod to represent the failed 947 // lookup. 948 ciSymbol* name = get_symbol(name_sym); 949 ciSymbol* signature = get_symbol(sig_sym); 950 return get_unloaded_method(holder, name, signature, accessor); 951 } 952 } 953 954 955 // ------------------------------------------------------------------ 956 // ciEnv::get_instance_klass_for_declared_method_holder 957 ciInstanceKlass* ciEnv::get_instance_klass_for_declared_method_holder(ciKlass* method_holder) { 958 // For the case of <array>.clone(), the method holder can be a ciArrayKlass 959 // instead of a ciInstanceKlass. For that case simply pretend that the 960 // declared holder is Object.clone since that's where the call will bottom out. 961 // A more correct fix would trickle out through many interfaces in CI, 962 // requiring ciInstanceKlass* to become ciKlass* and many more places would 963 // require checks to make sure the expected type was found. Given that this 964 // only occurs for clone() the more extensive fix seems like overkill so 965 // instead we simply smear the array type into Object. 966 guarantee(method_holder != nullptr, "no method holder"); 967 if (method_holder->is_instance_klass()) { 968 return method_holder->as_instance_klass(); 969 } else if (method_holder->is_array_klass()) { 970 return current()->Object_klass(); 971 } else { 972 ShouldNotReachHere(); 973 } 974 return nullptr; 975 } 976 977 978 // ------------------------------------------------------------------ 979 // ciEnv::get_method_by_index 980 ciMethod* ciEnv::get_method_by_index(const constantPoolHandle& cpool, 981 int index, Bytecodes::Code bc, 982 ciInstanceKlass* accessor) { 983 GUARDED_VM_ENTRY(return get_method_by_index_impl(cpool, index, bc, accessor);) 984 } 985 986 987 // ------------------------------------------------------------------ 988 // ciEnv::name_buffer 989 char *ciEnv::name_buffer(int req_len) { 990 if (_name_buffer_len < req_len) { 991 if (_name_buffer == nullptr) { 992 _name_buffer = (char*)arena()->Amalloc(sizeof(char)*req_len); 993 _name_buffer_len = req_len; 994 } else { 995 _name_buffer = 996 (char*)arena()->Arealloc(_name_buffer, _name_buffer_len, req_len); 997 _name_buffer_len = req_len; 998 } 999 } 1000 return _name_buffer; 1001 } 1002 1003 // ------------------------------------------------------------------ 1004 // ciEnv::is_in_vm 1005 bool ciEnv::is_in_vm() { 1006 return JavaThread::current()->thread_state() == _thread_in_vm; 1007 } 1008 1009 // ------------------------------------------------------------------ 1010 // ciEnv::validate_compile_task_dependencies 1011 // 1012 // Check for changes during compilation (e.g. class loads, evolution, 1013 // breakpoints, call site invalidation). 1014 void ciEnv::validate_compile_task_dependencies(ciMethod* target) { 1015 if (failing()) return; // no need for further checks 1016 1017 Dependencies::DepType result = dependencies()->validate_dependencies(_task); 1018 if (result != Dependencies::end_marker) { 1019 if (result == Dependencies::call_site_target_value) { 1020 _inc_decompile_count_on_failure = false; 1021 record_failure("call site target change"); 1022 } else if (Dependencies::is_klass_type(result)) { 1023 record_failure("concurrent class loading"); 1024 } else { 1025 record_failure("invalid non-klass dependency"); 1026 } 1027 } 1028 } 1029 1030 // ------------------------------------------------------------------ 1031 // ciEnv::register_method 1032 void ciEnv::register_method(ciMethod* target, 1033 int entry_bci, 1034 CodeOffsets* offsets, 1035 int orig_pc_offset, 1036 CodeBuffer* code_buffer, 1037 int frame_words, 1038 OopMapSet* oop_map_set, 1039 ExceptionHandlerTable* handler_table, 1040 ImplicitExceptionTable* inc_table, 1041 AbstractCompiler* compiler, 1042 bool has_unsafe_access, 1043 bool has_wide_vectors, 1044 bool has_monitors, 1045 int immediate_oops_patched, 1046 RTMState rtm_state) { 1047 VM_ENTRY_MARK; 1048 nmethod* nm = nullptr; 1049 { 1050 methodHandle method(THREAD, target->get_Method()); 1051 1052 // We require method counters to store some method state (max compilation levels) required by the compilation policy. 1053 if (method->get_method_counters(THREAD) == nullptr) { 1054 record_failure("can't create method counters"); 1055 // All buffers in the CodeBuffer are allocated in the CodeCache. 1056 // If the code buffer is created on each compile attempt 1057 // as in C2, then it must be freed. 1058 code_buffer->free_blob(); 1059 return; 1060 } 1061 1062 // Check if memory should be freed before allocation 1063 CodeCache::gc_on_allocation(); 1064 1065 // To prevent compile queue updates. 1066 MutexLocker locker(THREAD, MethodCompileQueue_lock); 1067 1068 // Prevent InstanceKlass::add_to_hierarchy from running 1069 // and invalidating our dependencies until we install this method. 1070 // No safepoints are allowed. Otherwise, class redefinition can occur in between. 1071 MutexLocker ml(Compile_lock); 1072 NoSafepointVerifier nsv; 1073 1074 // Change in Jvmti state may invalidate compilation. 1075 if (!failing() && jvmti_state_changed()) { 1076 record_failure("Jvmti state change invalidated dependencies"); 1077 } 1078 1079 // Change in DTrace flags may invalidate compilation. 1080 if (!failing() && 1081 ( (!dtrace_method_probes() && DTraceMethodProbes) || 1082 (!dtrace_alloc_probes() && DTraceAllocProbes) )) { 1083 record_failure("DTrace flags change invalidated dependencies"); 1084 } 1085 1086 if (!failing() && target->needs_clinit_barrier() && 1087 target->holder()->is_in_error_state()) { 1088 record_failure("method holder is in error state"); 1089 } 1090 1091 if (!failing()) { 1092 if (log() != nullptr) { 1093 // Log the dependencies which this compilation declares. 1094 dependencies()->log_all_dependencies(); 1095 } 1096 1097 // Encode the dependencies now, so we can check them right away. 1098 dependencies()->encode_content_bytes(); 1099 1100 // Check for {class loads, evolution, breakpoints, ...} during compilation 1101 validate_compile_task_dependencies(target); 1102 } 1103 #if INCLUDE_RTM_OPT 1104 if (!failing() && (rtm_state != NoRTM) && 1105 (method()->method_data() != nullptr) && 1106 (method()->method_data()->rtm_state() != rtm_state)) { 1107 // Preemptive decompile if rtm state was changed. 1108 record_failure("RTM state change invalidated rtm code"); 1109 } 1110 #endif 1111 1112 if (failing()) { 1113 // While not a true deoptimization, it is a preemptive decompile. 1114 MethodData* mdo = method()->method_data(); 1115 if (mdo != nullptr && _inc_decompile_count_on_failure) { 1116 mdo->inc_decompile_count(); 1117 } 1118 1119 // All buffers in the CodeBuffer are allocated in the CodeCache. 1120 // If the code buffer is created on each compile attempt 1121 // as in C2, then it must be freed. 1122 code_buffer->free_blob(); 1123 return; 1124 } 1125 1126 assert(offsets->value(CodeOffsets::Deopt) != -1, "must have deopt entry"); 1127 assert(offsets->value(CodeOffsets::Exceptions) != -1, "must have exception entry"); 1128 1129 nm = nmethod::new_nmethod(method, 1130 compile_id(), 1131 entry_bci, 1132 offsets, 1133 orig_pc_offset, 1134 debug_info(), dependencies(), code_buffer, 1135 frame_words, oop_map_set, 1136 handler_table, inc_table, 1137 compiler, CompLevel(task()->comp_level())); 1138 1139 // Free codeBlobs 1140 code_buffer->free_blob(); 1141 1142 if (nm != nullptr) { 1143 nm->set_has_unsafe_access(has_unsafe_access); 1144 nm->set_has_wide_vectors(has_wide_vectors); 1145 nm->set_has_monitors(has_monitors); 1146 assert(!method->is_synchronized() || nm->has_monitors(), ""); 1147 #if INCLUDE_RTM_OPT 1148 nm->set_rtm_state(rtm_state); 1149 #endif 1150 1151 if (entry_bci == InvocationEntryBci) { 1152 if (TieredCompilation) { 1153 // If there is an old version we're done with it 1154 CompiledMethod* old = method->code(); 1155 if (TraceMethodReplacement && old != nullptr) { 1156 ResourceMark rm; 1157 char *method_name = method->name_and_sig_as_C_string(); 1158 tty->print_cr("Replacing method %s", method_name); 1159 } 1160 if (old != nullptr) { 1161 old->make_not_used(); 1162 } 1163 } 1164 1165 LogTarget(Info, nmethod, install) lt; 1166 if (lt.is_enabled()) { 1167 ResourceMark rm; 1168 char *method_name = method->name_and_sig_as_C_string(); 1169 lt.print("Installing method (%d) %s ", 1170 task()->comp_level(), method_name); 1171 } 1172 // Allow the code to be executed 1173 MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag); 1174 if (nm->make_in_use()) { 1175 method->set_code(method, nm); 1176 } 1177 } else { 1178 LogTarget(Info, nmethod, install) lt; 1179 if (lt.is_enabled()) { 1180 ResourceMark rm; 1181 char *method_name = method->name_and_sig_as_C_string(); 1182 lt.print("Installing osr method (%d) %s @ %d", 1183 task()->comp_level(), method_name, entry_bci); 1184 } 1185 MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag); 1186 if (nm->make_in_use()) { 1187 method->method_holder()->add_osr_nmethod(nm); 1188 } 1189 } 1190 } 1191 } 1192 1193 NoSafepointVerifier nsv; 1194 if (nm != nullptr) { 1195 // Compilation succeeded, post what we know about it 1196 nm->post_compiled_method(task()); 1197 task()->set_num_inlined_bytecodes(num_inlined_bytecodes()); 1198 } else { 1199 // The CodeCache is full. 1200 record_failure("code cache is full"); 1201 } 1202 1203 // safepoints are allowed again 1204 } 1205 1206 // ------------------------------------------------------------------ 1207 // ciEnv::find_system_klass 1208 ciKlass* ciEnv::find_system_klass(ciSymbol* klass_name) { 1209 VM_ENTRY_MARK; 1210 return get_klass_by_name_impl(nullptr, constantPoolHandle(), klass_name, false); 1211 } 1212 1213 // ------------------------------------------------------------------ 1214 // ciEnv::comp_level 1215 int ciEnv::comp_level() { 1216 if (task() == nullptr) return CompilationPolicy::highest_compile_level(); 1217 return task()->comp_level(); 1218 } 1219 1220 // ------------------------------------------------------------------ 1221 // ciEnv::compile_id 1222 int ciEnv::compile_id() { 1223 if (task() == nullptr) return 0; 1224 return task()->compile_id(); 1225 } 1226 1227 // ------------------------------------------------------------------ 1228 // ciEnv::notice_inlined_method() 1229 void ciEnv::notice_inlined_method(ciMethod* method) { 1230 _num_inlined_bytecodes += method->code_size_for_inlining(); 1231 } 1232 1233 // ------------------------------------------------------------------ 1234 // ciEnv::num_inlined_bytecodes() 1235 int ciEnv::num_inlined_bytecodes() const { 1236 return _num_inlined_bytecodes; 1237 } 1238 1239 // ------------------------------------------------------------------ 1240 // ciEnv::record_failure() 1241 void ciEnv::record_failure(const char* reason) { 1242 if (_failure_reason == nullptr) { 1243 // Record the first failure reason. 1244 _failure_reason = reason; 1245 } 1246 } 1247 1248 void ciEnv::report_failure(const char* reason) { 1249 EventCompilationFailure event; 1250 if (event.should_commit()) { 1251 CompilerEvent::CompilationFailureEvent::post(event, compile_id(), reason); 1252 } 1253 } 1254 1255 // ------------------------------------------------------------------ 1256 // ciEnv::record_method_not_compilable() 1257 void ciEnv::record_method_not_compilable(const char* reason, bool all_tiers) { 1258 int new_compilable = 1259 all_tiers ? MethodCompilable_never : MethodCompilable_not_at_tier ; 1260 1261 // Only note transitions to a worse state 1262 if (new_compilable > _compilable) { 1263 if (log() != nullptr) { 1264 if (all_tiers) { 1265 log()->elem("method_not_compilable"); 1266 } else { 1267 log()->elem("method_not_compilable_at_tier level='%d'", 1268 current()->task()->comp_level()); 1269 } 1270 } 1271 _compilable = new_compilable; 1272 1273 // Reset failure reason; this one is more important. 1274 _failure_reason = nullptr; 1275 record_failure(reason); 1276 } 1277 } 1278 1279 // ------------------------------------------------------------------ 1280 // ciEnv::record_out_of_memory_failure() 1281 void ciEnv::record_out_of_memory_failure() { 1282 // If memory is low, we stop compiling methods. 1283 record_method_not_compilable("out of memory"); 1284 } 1285 1286 ciInstance* ciEnv::unloaded_ciinstance() { 1287 GUARDED_VM_ENTRY(return _factory->get_unloaded_object_constant();) 1288 } 1289 1290 // ------------------------------------------------------------------ 1291 // Replay support 1292 1293 1294 // Lookup location descriptor for the class, if any. 1295 // Returns false if not found. 1296 bool ciEnv::dyno_loc(const InstanceKlass* ik, const char *&loc) const { 1297 bool found = false; 1298 int pos = _dyno_klasses->find_sorted<const InstanceKlass*, klass_compare>(ik, found); 1299 if (!found) { 1300 return false; 1301 } 1302 loc = _dyno_locs->at(pos); 1303 return found; 1304 } 1305 1306 // Associate the current location descriptor with the given class and record for later lookup. 1307 void ciEnv::set_dyno_loc(const InstanceKlass* ik) { 1308 const char *loc = os::strdup(_dyno_name); 1309 bool found = false; 1310 int pos = _dyno_klasses->find_sorted<const InstanceKlass*, klass_compare>(ik, found); 1311 if (found) { 1312 _dyno_locs->at_put(pos, loc); 1313 } else { 1314 _dyno_klasses->insert_before(pos, ik); 1315 _dyno_locs->insert_before(pos, loc); 1316 } 1317 } 1318 1319 // Associate the current location descriptor with the given class and record for later lookup. 1320 // If it turns out that there are multiple locations for the given class, that conflict should 1321 // be handled here. Currently we choose the first location found. 1322 void ciEnv::record_best_dyno_loc(const InstanceKlass* ik) { 1323 if (!ik->is_hidden()) { 1324 return; 1325 } 1326 const char *loc0; 1327 if (!dyno_loc(ik, loc0)) { 1328 set_dyno_loc(ik); 1329 } 1330 } 1331 1332 // Look up the location descriptor for the given class and print it to the output stream. 1333 bool ciEnv::print_dyno_loc(outputStream* out, const InstanceKlass* ik) const { 1334 const char *loc; 1335 if (dyno_loc(ik, loc)) { 1336 out->print("%s", loc); 1337 return true; 1338 } else { 1339 return false; 1340 } 1341 } 1342 1343 // Look up the location descriptor for the given class and return it as a string. 1344 // Returns null if no location is found. 1345 const char *ciEnv::dyno_name(const InstanceKlass* ik) const { 1346 if (ik->is_hidden()) { 1347 stringStream ss; 1348 if (print_dyno_loc(&ss, ik)) { 1349 ss.print(" ;"); // add terminator 1350 const char* call_site = ss.as_string(); 1351 return call_site; 1352 } 1353 } 1354 return nullptr; 1355 } 1356 1357 // Look up the location descriptor for the given class and return it as a string. 1358 // Returns the class name as a fallback if no location is found. 1359 const char *ciEnv::replay_name(ciKlass* k) const { 1360 if (k->is_instance_klass()) { 1361 return replay_name(k->as_instance_klass()->get_instanceKlass()); 1362 } 1363 return k->name()->as_quoted_ascii(); 1364 } 1365 1366 // Look up the location descriptor for the given class and return it as a string. 1367 // Returns the class name as a fallback if no location is found. 1368 const char *ciEnv::replay_name(const InstanceKlass* ik) const { 1369 const char* name = dyno_name(ik); 1370 if (name != nullptr) { 1371 return name; 1372 } 1373 return ik->name()->as_quoted_ascii(); 1374 } 1375 1376 // Process a java.lang.invoke.MemberName object and record any dynamic locations. 1377 void ciEnv::record_member(Thread* thread, oop member) { 1378 assert(java_lang_invoke_MemberName::is_instance(member), "!"); 1379 // Check MemberName.clazz field 1380 oop clazz = java_lang_invoke_MemberName::clazz(member); 1381 if (clazz->klass()->is_instance_klass()) { 1382 RecordLocation fp(this, "clazz"); 1383 InstanceKlass* ik = InstanceKlass::cast(clazz->klass()); 1384 record_best_dyno_loc(ik); 1385 } 1386 // Check MemberName.method.vmtarget field 1387 Method* vmtarget = java_lang_invoke_MemberName::vmtarget(member); 1388 if (vmtarget != nullptr) { 1389 RecordLocation fp2(this, "<vmtarget>"); 1390 InstanceKlass* ik = vmtarget->method_holder(); 1391 record_best_dyno_loc(ik); 1392 } 1393 } 1394 1395 // Read an object field. Lookup is done by name only. 1396 static inline oop obj_field(oop obj, const char* name) { 1397 return ciReplay::obj_field(obj, name); 1398 } 1399 1400 // Process a java.lang.invoke.LambdaForm object and record any dynamic locations. 1401 void ciEnv::record_lambdaform(Thread* thread, oop form) { 1402 assert(java_lang_invoke_LambdaForm::is_instance(form), "!"); 1403 1404 { 1405 // Check LambdaForm.vmentry field 1406 oop member = java_lang_invoke_LambdaForm::vmentry(form); 1407 RecordLocation fp0(this, "vmentry"); 1408 record_member(thread, member); 1409 } 1410 1411 // Check LambdaForm.names array 1412 objArrayOop names = (objArrayOop)obj_field(form, "names"); 1413 if (names != nullptr) { 1414 RecordLocation lp0(this, "names"); 1415 int len = names->length(); 1416 for (int i = 0; i < len; ++i) { 1417 oop name = names->obj_at(i); 1418 RecordLocation lp1(this, "%d", i); 1419 // Check LambdaForm.names[i].function field 1420 RecordLocation lp2(this, "function"); 1421 oop function = obj_field(name, "function"); 1422 if (function != nullptr) { 1423 // Check LambdaForm.names[i].function.member field 1424 oop member = obj_field(function, "member"); 1425 if (member != nullptr) { 1426 RecordLocation lp3(this, "member"); 1427 record_member(thread, member); 1428 } 1429 // Check LambdaForm.names[i].function.resolvedHandle field 1430 oop mh = obj_field(function, "resolvedHandle"); 1431 if (mh != nullptr) { 1432 RecordLocation lp3(this, "resolvedHandle"); 1433 record_mh(thread, mh); 1434 } 1435 // Check LambdaForm.names[i].function.invoker field 1436 oop invoker = obj_field(function, "invoker"); 1437 if (invoker != nullptr) { 1438 RecordLocation lp3(this, "invoker"); 1439 record_mh(thread, invoker); 1440 } 1441 } 1442 } 1443 } 1444 } 1445 1446 // Process a java.lang.invoke.MethodHandle object and record any dynamic locations. 1447 void ciEnv::record_mh(Thread* thread, oop mh) { 1448 { 1449 // Check MethodHandle.form field 1450 oop form = java_lang_invoke_MethodHandle::form(mh); 1451 RecordLocation fp(this, "form"); 1452 record_lambdaform(thread, form); 1453 } 1454 // Check DirectMethodHandle.member field 1455 if (java_lang_invoke_DirectMethodHandle::is_instance(mh)) { 1456 oop member = java_lang_invoke_DirectMethodHandle::member(mh); 1457 RecordLocation fp(this, "member"); 1458 record_member(thread, member); 1459 } else { 1460 // Check <MethodHandle subclass>.argL<n> fields 1461 // Probably BoundMethodHandle.Species_L*, but we only care if the field exists 1462 char arg_name[] = "argLXX"; 1463 int max_arg = 99; 1464 for (int index = 0; index <= max_arg; ++index) { 1465 jio_snprintf(arg_name, sizeof (arg_name), "argL%d", index); 1466 oop arg = obj_field(mh, arg_name); 1467 if (arg != nullptr) { 1468 RecordLocation fp(this, "%s", arg_name); 1469 if (arg->klass()->is_instance_klass()) { 1470 InstanceKlass* ik2 = InstanceKlass::cast(arg->klass()); 1471 record_best_dyno_loc(ik2); 1472 record_call_site_obj(thread, arg); 1473 } 1474 } else { 1475 break; 1476 } 1477 } 1478 } 1479 } 1480 1481 // Process an object found at an invokedynamic/invokehandle call site and record any dynamic locations. 1482 // Types currently supported are MethodHandle and CallSite. 1483 // The object is typically the "appendix" object, or Bootstrap Method (BSM) object. 1484 void ciEnv::record_call_site_obj(Thread* thread, oop obj) 1485 { 1486 if (obj != nullptr) { 1487 if (java_lang_invoke_MethodHandle::is_instance(obj)) { 1488 record_mh(thread, obj); 1489 } else if (java_lang_invoke_ConstantCallSite::is_instance(obj)) { 1490 oop target = java_lang_invoke_CallSite::target(obj); 1491 if (target->klass()->is_instance_klass()) { 1492 RecordLocation fp(this, "target"); 1493 InstanceKlass* ik = InstanceKlass::cast(target->klass()); 1494 record_best_dyno_loc(ik); 1495 } 1496 } 1497 } 1498 } 1499 1500 // Process an adapter Method* found at an invokedynamic/invokehandle call site and record any dynamic locations. 1501 void ciEnv::record_call_site_method(Thread* thread, Method* adapter) { 1502 InstanceKlass* holder = adapter->method_holder(); 1503 if (!holder->is_hidden()) { 1504 return; 1505 } 1506 RecordLocation fp(this, "<adapter>"); 1507 record_best_dyno_loc(holder); 1508 } 1509 1510 // Process an invokedynamic call site and record any dynamic locations. 1511 void ciEnv::process_invokedynamic(const constantPoolHandle &cp, int indy_index, JavaThread* thread) { 1512 int index = cp->decode_invokedynamic_index(indy_index); 1513 ResolvedIndyEntry* indy_info = cp->resolved_indy_entry_at(index); 1514 if (indy_info->method() != nullptr) { 1515 // process the adapter 1516 Method* adapter = indy_info->method(); 1517 record_call_site_method(thread, adapter); 1518 // process the appendix 1519 oop appendix = cp->resolved_reference_from_indy(index); 1520 { 1521 RecordLocation fp(this, "<appendix>"); 1522 record_call_site_obj(thread, appendix); 1523 } 1524 // process the BSM 1525 int pool_index = indy_info->constant_pool_index(); 1526 BootstrapInfo bootstrap_specifier(cp, pool_index, index); 1527 oop bsm = cp->resolve_possibly_cached_constant_at(bootstrap_specifier.bsm_index(), thread); 1528 { 1529 RecordLocation fp(this, "<bsm>"); 1530 record_call_site_obj(thread, bsm); 1531 } 1532 } 1533 } 1534 1535 // Process an invokehandle call site and record any dynamic locations. 1536 void ciEnv::process_invokehandle(const constantPoolHandle &cp, int index, JavaThread* thread) { 1537 const int holder_index = cp->klass_ref_index_at(index, Bytecodes::_invokehandle); 1538 if (!cp->tag_at(holder_index).is_klass()) { 1539 return; // not resolved 1540 } 1541 Klass* holder = ConstantPool::klass_at_if_loaded(cp, holder_index); 1542 Symbol* name = cp->name_ref_at(index, Bytecodes::_invokehandle); 1543 if (MethodHandles::is_signature_polymorphic_name(holder, name)) { 1544 ResolvedMethodEntry* method_entry = cp->resolved_method_entry_at(index); 1545 if (method_entry->is_resolved(Bytecodes::_invokehandle)) { 1546 // process the adapter 1547 Method* adapter = method_entry->method(); 1548 oop appendix = cp->cache()->appendix_if_resolved(method_entry); 1549 record_call_site_method(thread, adapter); 1550 // process the appendix 1551 { 1552 RecordLocation fp(this, "<appendix>"); 1553 record_call_site_obj(thread, appendix); 1554 } 1555 } 1556 } 1557 } 1558 1559 // Search the class hierarchy for dynamic classes reachable through dynamic call sites or 1560 // constant pool entries and record for future lookup. 1561 void ciEnv::find_dynamic_call_sites() { 1562 _dyno_klasses = new (arena()) GrowableArray<const InstanceKlass*>(arena(), 100, 0, nullptr); 1563 _dyno_locs = new (arena()) GrowableArray<const char *>(arena(), 100, 0, nullptr); 1564 1565 // Iterate over the class hierarchy 1566 for (ClassHierarchyIterator iter(vmClasses::Object_klass()); !iter.done(); iter.next()) { 1567 Klass* sub = iter.klass(); 1568 if (sub->is_instance_klass()) { 1569 InstanceKlass *isub = InstanceKlass::cast(sub); 1570 InstanceKlass* ik = isub; 1571 if (!ik->is_linked()) { 1572 continue; 1573 } 1574 if (ik->is_hidden()) { 1575 continue; 1576 } 1577 JavaThread* thread = JavaThread::current(); 1578 const constantPoolHandle pool(thread, ik->constants()); 1579 1580 // Look for invokedynamic/invokehandle call sites 1581 for (int i = 0; i < ik->methods()->length(); ++i) { 1582 Method* m = ik->methods()->at(i); 1583 1584 BytecodeStream bcs(methodHandle(thread, m)); 1585 while (!bcs.is_last_bytecode()) { 1586 Bytecodes::Code opcode = bcs.next(); 1587 opcode = bcs.raw_code(); 1588 switch (opcode) { 1589 case Bytecodes::_invokedynamic: 1590 case Bytecodes::_invokehandle: { 1591 RecordLocation fp(this, "@bci %s %s %s %d", 1592 ik->name()->as_quoted_ascii(), 1593 m->name()->as_quoted_ascii(), m->signature()->as_quoted_ascii(), 1594 bcs.bci()); 1595 if (opcode == Bytecodes::_invokedynamic) { 1596 int index = bcs.get_index_u4(); 1597 process_invokedynamic(pool, index, thread); 1598 } else { 1599 assert(opcode == Bytecodes::_invokehandle, "new switch label added?"); 1600 int cp_cache_index = bcs.get_index_u2(); 1601 process_invokehandle(pool, cp_cache_index, thread); 1602 } 1603 break; 1604 } 1605 default: 1606 break; 1607 } 1608 } 1609 } 1610 1611 // Look for MethodHandle constant pool entries 1612 RecordLocation fp(this, "@cpi %s", ik->name()->as_quoted_ascii()); 1613 int len = pool->length(); 1614 for (int i = 0; i < len; ++i) { 1615 if (pool->tag_at(i).is_method_handle()) { 1616 bool found_it; 1617 oop mh = pool->find_cached_constant_at(i, found_it, thread); 1618 if (mh != nullptr) { 1619 RecordLocation fp(this, "%d", i); 1620 record_mh(thread, mh); 1621 } 1622 } 1623 } 1624 } 1625 } 1626 } 1627 1628 void ciEnv::dump_compile_data(outputStream* out) { 1629 CompileTask* task = this->task(); 1630 if (task) { 1631 #ifdef COMPILER2 1632 if (ReplayReduce && compiler_data() != nullptr) { 1633 // Dump C2 "reduced" inlining data. 1634 ((Compile*)compiler_data())->dump_inline_data_reduced(out); 1635 } 1636 #endif 1637 Method* method = task->method(); 1638 int entry_bci = task->osr_bci(); 1639 int comp_level = task->comp_level(); 1640 out->print("compile "); 1641 get_method(method)->dump_name_as_ascii(out); 1642 out->print(" %d %d", entry_bci, comp_level); 1643 if (compiler_data() != nullptr) { 1644 if (is_c2_compile(comp_level)) { 1645 #ifdef COMPILER2 1646 // Dump C2 inlining data. 1647 ((Compile*)compiler_data())->dump_inline_data(out); 1648 #endif 1649 } else if (is_c1_compile(comp_level)) { 1650 #ifdef COMPILER1 1651 // Dump C1 inlining data. 1652 ((Compilation*)compiler_data())->dump_inline_data(out); 1653 #endif 1654 } 1655 } 1656 out->cr(); 1657 } 1658 } 1659 1660 // Called from VM error reporter, so be careful. 1661 // Don't safepoint or acquire any locks. 1662 // 1663 void ciEnv::dump_replay_data_helper(outputStream* out) { 1664 NoSafepointVerifier no_safepoint; 1665 ResourceMark rm; 1666 1667 dump_replay_data_version(out); 1668 #if INCLUDE_JVMTI 1669 out->print_cr("JvmtiExport can_access_local_variables %d", _jvmti_can_access_local_variables); 1670 out->print_cr("JvmtiExport can_hotswap_or_post_breakpoint %d", _jvmti_can_hotswap_or_post_breakpoint); 1671 out->print_cr("JvmtiExport can_post_on_exceptions %d", _jvmti_can_post_on_exceptions); 1672 #endif // INCLUDE_JVMTI 1673 1674 find_dynamic_call_sites(); 1675 1676 GrowableArray<ciMetadata*>* objects = _factory->get_ci_metadata(); 1677 out->print_cr("# %d ciObject found", objects->length()); 1678 1679 // The very first entry is the InstanceKlass of the root method of the current compilation in order to get the right 1680 // protection domain to load subsequent classes during replay compilation. 1681 ciInstanceKlass::dump_replay_instanceKlass(out, task()->method()->method_holder()); 1682 1683 for (int i = 0; i < objects->length(); i++) { 1684 objects->at(i)->dump_replay_data(out); 1685 } 1686 dump_compile_data(out); 1687 out->flush(); 1688 } 1689 1690 // Called from VM error reporter, so be careful. 1691 // Don't safepoint or acquire any locks. 1692 // 1693 void ciEnv::dump_replay_data_unsafe(outputStream* out) { 1694 GUARDED_VM_ENTRY( 1695 dump_replay_data_helper(out); 1696 ) 1697 } 1698 1699 void ciEnv::dump_replay_data(outputStream* out) { 1700 GUARDED_VM_ENTRY( 1701 MutexLocker ml(Compile_lock); 1702 dump_replay_data_helper(out); 1703 ) 1704 } 1705 1706 void ciEnv::dump_replay_data(int compile_id) { 1707 char buffer[64]; 1708 int ret = jio_snprintf(buffer, sizeof(buffer), "replay_pid%d_compid%d.log", os::current_process_id(), compile_id); 1709 if (ret > 0) { 1710 int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666); 1711 if (fd != -1) { 1712 FILE* replay_data_file = os::fdopen(fd, "w"); 1713 if (replay_data_file != nullptr) { 1714 fileStream replay_data_stream(replay_data_file, /*need_close=*/true); 1715 dump_replay_data(&replay_data_stream); 1716 tty->print_cr("# Compiler replay data is saved as: %s", buffer); 1717 } else { 1718 tty->print_cr("# Can't open file to dump replay data."); 1719 close(fd); 1720 } 1721 } 1722 } 1723 } 1724 1725 void ciEnv::dump_inline_data(int compile_id) { 1726 char buffer[64]; 1727 int ret = jio_snprintf(buffer, sizeof(buffer), "inline_pid%d_compid%d.log", os::current_process_id(), compile_id); 1728 if (ret > 0) { 1729 int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666); 1730 if (fd != -1) { 1731 FILE* inline_data_file = os::fdopen(fd, "w"); 1732 if (inline_data_file != nullptr) { 1733 fileStream replay_data_stream(inline_data_file, /*need_close=*/true); 1734 GUARDED_VM_ENTRY( 1735 MutexLocker ml(Compile_lock); 1736 dump_replay_data_version(&replay_data_stream); 1737 dump_compile_data(&replay_data_stream); 1738 ) 1739 replay_data_stream.flush(); 1740 tty->print("# Compiler inline data is saved as: "); 1741 tty->print_cr("%s", buffer); 1742 } else { 1743 tty->print_cr("# Can't open file to dump inline data."); 1744 close(fd); 1745 } 1746 } 1747 } 1748 } 1749 1750 void ciEnv::dump_replay_data_version(outputStream* out) { 1751 out->print_cr("version %d", REPLAY_VERSION); 1752 }