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