1 /*
  2  * Copyright (c) 1999, 2026, 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 #ifndef SHARE_CI_CIENV_HPP
 26 #define SHARE_CI_CIENV_HPP
 27 
 28 #include "ci/ciClassList.hpp"
 29 #include "ci/ciObjectFactory.hpp"
 30 #include "classfile/vmClassMacros.hpp"
 31 #include "code/debugInfoRec.hpp"
 32 #include "code/dependencies.hpp"
 33 #include "code/exceptionHandlerTable.hpp"
 34 #include "compiler/cHeapStringHolder.hpp"
 35 #include "compiler/compiler_globals.hpp"
 36 #include "compiler/compilerThread.hpp"
 37 #include "oops/methodData.hpp"
 38 #include "runtime/javaThread.hpp"
 39 
 40 class CompileTask;
 41 class OopMapSet;
 42 
 43 // ciEnv
 44 //
 45 // This class is the top level broker for requests from the compiler
 46 // to the VM.
 47 class ciEnv : StackObj {
 48   CI_PACKAGE_ACCESS_TO
 49   friend class CompileBroker;
 50   friend class Dependencies;  // for get_object, during logging
 51   friend class RecordLocation;
 52   friend class PrepareExtraDataClosure;
 53 
 54 private:
 55   Arena*           _arena;       // Alias for _ciEnv_arena except in init_shared_objects()
 56   Arena            _ciEnv_arena;
 57   ciObjectFactory* _factory;
 58   OopRecorder*     _oop_recorder;
 59   DebugInformationRecorder* _debug_info;
 60   Dependencies*    _dependencies;
 61   CHeapStringHolder _failure_reason;
 62   bool             _inc_decompile_count_on_failure;
 63   int              _compilable;
 64   bool             _break_at_compile;
 65   int              _num_inlined_bytecodes;
 66   CompileTask*     _task;           // faster access to CompilerThread::task
 67   CompileLog*      _log;            // faster access to CompilerThread::log
 68   void*            _compiler_data;  // compiler-specific stuff, if any
 69 
 70   char* _name_buffer;
 71   int   _name_buffer_len;
 72 
 73   // Cache Jvmti state
 74   uint64_t _jvmti_redefinition_count;
 75   bool  _jvmti_can_hotswap_or_post_breakpoint;
 76   bool  _jvmti_can_access_local_variables;
 77   bool  _jvmti_can_post_on_exceptions;
 78   bool  _jvmti_can_pop_frame;
 79   bool  _jvmti_can_get_owned_monitor_info; // includes can_get_owned_monitor_stack_depth_info
 80   bool  _jvmti_can_walk_any_space;
 81 
 82   // Cache DTrace flags
 83   bool  _dtrace_method_probes;
 84   bool  _dtrace_alloc_probes;
 85 
 86   // Distinguished instances of certain ciObjects..
 87   static ciObject*              _null_object_instance;
 88 
 89 #define VM_CLASS_DECL(name, ignore_s) static ciInstanceKlass* _##name;
 90   VM_CLASSES_DO(VM_CLASS_DECL)
 91 #undef VM_CLASS_DECL
 92 
 93   static ciSymbol*        _unloaded_cisymbol;
 94   static ciInstanceKlass* _unloaded_ciinstance_klass;
 95   static ciObjArrayKlass* _unloaded_ciobjarrayklass;
 96 
 97   ciInstance* _NullPointerException_instance;
 98   ciInstance* _ArithmeticException_instance;
 99   ciInstance* _ArrayIndexOutOfBoundsException_instance;
100   ciInstance* _ArrayStoreException_instance;
101   ciInstance* _ClassCastException_instance;
102 
103   ciInstance* _the_null_string;      // The Java string "null"
104   ciInstance* _the_min_jint_string; // The Java string "-2147483648"
105 
106   // Look up a klass by name from a particular class loader (the accessor's).
107   // If require_local, result must be defined in that class loader, or null.
108   // If !require_local, a result from remote class loader may be reported,
109   // if sufficient class loader constraints exist such that initiating
110   // a class loading request from the given loader is bound to return
111   // the class defined in the remote loader (or throw an error).
112   //
113   // Return an unloaded klass if !require_local and no class at all is found.
114   //
115   // The CI treats a klass as loaded if it is consistently defined in
116   // another loader, even if it hasn't yet been loaded in all loaders
117   // that could potentially see it via delegation.
118   ciKlass* get_klass_by_name(ciKlass* accessing_klass,
119                              ciSymbol* klass_name,
120                              bool require_local);
121 
122   // Constant pool access.
123   ciKlass*   get_klass_by_index(const constantPoolHandle& cpool,
124                                 int klass_index,
125                                 bool& is_accessible,
126                                 ciInstanceKlass* loading_klass);
127   ciConstant get_constant_by_index(const constantPoolHandle& cpool,
128                                    int pool_index, int cache_index,
129                                    ciInstanceKlass* accessor);
130   ciField*   get_field_by_index(ciInstanceKlass* loading_klass,
131                                 int field_index, Bytecodes::Code bc);
132   ciMethod*  get_method_by_index(const constantPoolHandle& cpool,
133                                  int method_index, Bytecodes::Code bc,
134                                  ciInstanceKlass* loading_klass);
135 
136   // Implementation methods for loading and constant pool access.
137   ciKlass* get_klass_by_name_impl(ciKlass* accessing_klass,
138                                   const constantPoolHandle& cpool,
139                                   ciSymbol* klass_name,
140                                   bool require_local);
141   ciKlass*   get_klass_by_index_impl(const constantPoolHandle& cpool,
142                                      int klass_index,
143                                      bool& is_accessible,
144                                      ciInstanceKlass* loading_klass);
145   ciConstant get_constant_by_index_impl(const constantPoolHandle& cpool,
146                                         int pool_index, int cache_index,
147                                         ciInstanceKlass* loading_klass);
148   ciField*   get_field_by_index_impl(ciInstanceKlass* loading_klass,
149                                      int field_index, Bytecodes::Code bc);
150   ciMethod*  get_method_by_index_impl(const constantPoolHandle& cpool,
151                                       int method_index, Bytecodes::Code bc,
152                                       ciInstanceKlass* loading_klass);
153 
154   // Helper methods
155   bool       check_klass_accessibility(ciKlass* accessing_klass,
156                                       Klass* resolved_klass);
157   Method*    lookup_method(ciInstanceKlass* accessor,
158                            ciKlass*         holder,
159                            Symbol*          name,
160                            Symbol*          sig,
161                            Bytecodes::Code  bc,
162                            constantTag      tag);
163 
164   ciConstant unbox_primitive_value(ciObject* cibox, BasicType expected_bt = T_ILLEGAL);
165   ciConstant get_resolved_constant(const constantPoolHandle& cpool, int obj_index);
166 
167   // Get a ciObject from the object factory.  Ensures uniqueness
168   // of ciObjects.
169   ciObject* get_object(oop o) {
170     if (o == nullptr) {
171       return _null_object_instance;
172     } else {
173       return _factory->get(o);
174     }
175   }
176 
177   ciSymbol* get_symbol(Symbol* o) {
178     if (o == nullptr) {
179       ShouldNotReachHere();
180       return nullptr;
181     } else {
182       return _factory->get_symbol(o);
183     }
184   }
185 
186   ciMetadata* get_metadata(Metadata* o) {
187     if (o == nullptr) {
188       return nullptr;
189     } else {
190       return _factory->get_metadata(o);
191     }
192   }
193 
194   ciMetadata* cached_metadata(Metadata* o) {
195     return _factory->cached_metadata(o);
196   }
197 
198   ciInstance* get_instance(oop o) {
199     if (o == nullptr) return nullptr;
200     return get_object(o)->as_instance();
201   }
202   ciObjArrayKlass* get_obj_array_klass(Klass* o) {
203     if (o == nullptr) return nullptr;
204     assert(o->is_unrefined_objArray_klass(), "must be exact");
205     return get_metadata(o)->as_obj_array_klass();
206   }
207   ciFlatArrayKlass* get_flat_array_klass(Klass* o) {
208     if (o == nullptr) return nullptr;
209     return get_metadata(o)->as_flat_array_klass();
210   }
211   ciRefArrayKlass* get_ref_array_klass(Klass* o) {
212     if (o == nullptr) return nullptr;
213     return get_metadata(o)->as_ref_array_klass();
214   }
215   ciTypeArrayKlass* get_type_array_klass(Klass* o) {
216     if (o == nullptr) return nullptr;
217     return get_metadata(o)->as_type_array_klass();
218   }
219   ciKlass* get_klass(Klass* o) {
220     if (o == nullptr) return nullptr;
221     return get_metadata(o)->as_klass();
222   }
223   ciInstanceKlass* get_instance_klass(Klass* o) {
224     if (o == nullptr) return nullptr;
225     return get_metadata(o)->as_instance_klass();
226   }
227   ciMethod* get_method(Method* o) {
228     if (o == nullptr) return nullptr;
229     return get_metadata(o)->as_method();
230   }
231   ciMethodData* get_method_data(MethodData* o) {
232     if (o == nullptr) return nullptr;
233     return get_metadata(o)->as_method_data();
234   }
235 
236   ciMethod* get_method_from_handle(Method* method);
237 
238   // Get a ciMethod representing either an unfound method or
239   // a method with an unloaded holder.  Ensures uniqueness of
240   // the result.
241   ciMethod* get_unloaded_method(ciKlass*         holder,
242                                 ciSymbol*        name,
243                                 ciSymbol*        signature,
244                                 ciInstanceKlass* accessor) {
245     ciInstanceKlass* declared_holder = get_instance_klass_for_declared_method_holder(holder);
246     return _factory->get_unloaded_method(declared_holder, name, signature, accessor);
247   }
248   InstanceKlass::ClassState get_cached_init_state(uint id) {
249     return (InstanceKlass::ClassState)_factory->cached_init_state(id);
250   }
251 
252   // Get a ciKlass representing an unloaded klass.
253   // Ensures uniqueness of the result.
254   ciKlass* get_unloaded_klass(ciKlass*  accessing_klass,
255                               ciSymbol* name) {
256     return _factory->get_unloaded_klass(accessing_klass, name, true);
257   }
258 
259   // Get a ciKlass representing an unloaded klass mirror.
260   // Result is not necessarily unique, but will be unloaded.
261   ciInstance* get_unloaded_klass_mirror(ciKlass* type) {
262     return _factory->get_unloaded_klass_mirror(type);
263   }
264 
265   // Get a ciInstance representing an unresolved method handle constant.
266   ciInstance* get_unloaded_method_handle_constant(ciKlass*  holder,
267                                                   ciSymbol* name,
268                                                   ciSymbol* signature,
269                                                   int       ref_kind) {
270     return _factory->get_unloaded_method_handle_constant(holder, name, signature, ref_kind);
271   }
272 
273   // Get a ciInstance representing an unresolved method type constant.
274   ciInstance* get_unloaded_method_type_constant(ciSymbol* signature) {
275     return _factory->get_unloaded_method_type_constant(signature);
276   }
277 
278   // See if we already have an unloaded klass for the given name
279   // or return null if not.
280   ciKlass *check_get_unloaded_klass(ciKlass*  accessing_klass, ciSymbol* name) {
281     return _factory->get_unloaded_klass(accessing_klass, name, false);
282   }
283 
284   // Get a ciReturnAddress corresponding to the given bci.
285   // Ensures uniqueness of the result.
286   ciReturnAddress* get_return_address(int bci) {
287     return _factory->get_return_address(bci);
288   }
289 
290   // Get a ciMethodData representing the methodData for a method
291   // with none.
292   ciMethodData* get_empty_methodData() {
293     return _factory->get_empty_methodData();
294   }
295 
296   // General utility : get a buffer of some required length.
297   // Used in symbol creation.
298   char* name_buffer(int req_len);
299 
300   // Is this thread currently in the VM state?
301   static bool is_in_vm();
302 
303   // Helper routine for determining the validity of a compilation with
304   // respect to method dependencies (e.g. concurrent class loading).
305   void validate_compile_task_dependencies(ciMethod* target);
306 public:
307   enum {
308     MethodCompilable,
309     MethodCompilable_not_at_tier,
310     MethodCompilable_never
311   };
312 
313   ciEnv(CompileTask* task);
314   // Used only during initialization of the ci
315   ciEnv(Arena* arena);
316   ~ciEnv();
317 
318   OopRecorder* oop_recorder() { return _oop_recorder; }
319   void set_oop_recorder(OopRecorder* r) { _oop_recorder = r; }
320 
321   DebugInformationRecorder* debug_info() { return _debug_info; }
322   void set_debug_info(DebugInformationRecorder* i) { _debug_info = i; }
323 
324   Dependencies* dependencies() { return _dependencies; }
325   void set_dependencies(Dependencies* d) { _dependencies = d; }
326 
327   // This is true if the compilation is not going to produce code.
328   // (It is reasonable to retry failed compilations.)
329   bool failing() const { return _failure_reason.get() != nullptr; }
330 
331   // Reason this compilation is failing, such as "too many basic blocks".
332   const char* failure_reason() const { return _failure_reason.get(); }
333 
334   // Return state of appropriate compatibility
335   int compilable() { return _compilable; }
336 
337   const char* retry_message() const {
338     switch (_compilable) {
339       case ciEnv::MethodCompilable_not_at_tier:
340         return "retry at different tier";
341       case ciEnv::MethodCompilable_never:
342         return "not retryable";
343       case ciEnv::MethodCompilable:
344         return nullptr;
345       default:
346         ShouldNotReachHere();
347         return nullptr;
348     }
349   }
350 
351   bool break_at_compile() { return _break_at_compile; }
352   void set_break_at_compile(bool z) { _break_at_compile = z; }
353 
354   // Cache Jvmti state
355   bool  cache_jvmti_state();
356   bool  jvmti_state_changed() const;
357   bool  should_retain_local_variables() const {
358     return _jvmti_can_access_local_variables || _jvmti_can_pop_frame;
359   }
360   bool  jvmti_can_hotswap_or_post_breakpoint() const { return _jvmti_can_hotswap_or_post_breakpoint; }
361   bool  jvmti_can_post_on_exceptions()         const { return _jvmti_can_post_on_exceptions; }
362   bool  jvmti_can_get_owned_monitor_info()     const { return _jvmti_can_get_owned_monitor_info; }
363   bool  jvmti_can_walk_any_space()             const { return _jvmti_can_walk_any_space; }
364 
365   // Cache DTrace flags
366   void  cache_dtrace_flags();
367   bool  dtrace_method_probes()   const { return _dtrace_method_probes; }
368   bool  dtrace_alloc_probes()    const { return _dtrace_alloc_probes; }
369 
370   // The compiler task which has created this env.
371   // May be useful to find out compile_id, comp_level, etc.
372   CompileTask* task() const { return _task; }
373 
374   // Handy forwards to the task:
375   int comp_level();   // task()->comp_level()
376   int compile_id();  // task()->compile_id()
377 
378   // Register the result of a compilation.
379   void register_method(ciMethod*                 target,
380                        int                       entry_bci,
381                        CodeOffsets*              offsets,
382                        int                       orig_pc_offset,
383                        CodeBuffer*               code_buffer,
384                        int                       frame_words,
385                        OopMapSet*                oop_map_set,
386                        ExceptionHandlerTable*    handler_table,
387                        ImplicitExceptionTable*   inc_table,
388                        AbstractCompiler*         compiler,
389                        bool                      has_unsafe_access,
390                        bool                      has_wide_vectors,
391                        bool                      has_monitors,
392                        bool                      has_scoped_access,
393                        int                       immediate_oops_patched);
394 
395   // Access to certain well known ciObjects.
396 #define VM_CLASS_FUNC(name, ignore_s) \
397   ciInstanceKlass* name() { \
398     return _##name;\
399   }
400   VM_CLASSES_DO(VM_CLASS_FUNC)
401 #undef VM_CLASS_FUNC
402 
403   ciInstance* NullPointerException_instance() {
404     assert(_NullPointerException_instance != nullptr, "initialization problem");
405     return _NullPointerException_instance;
406   }
407   ciInstance* ArithmeticException_instance() {
408     assert(_ArithmeticException_instance != nullptr, "initialization problem");
409     return _ArithmeticException_instance;
410   }
411   ciInstance* ArrayIndexOutOfBoundsException_instance() {
412     assert(_ArrayIndexOutOfBoundsException_instance != nullptr, "initialization problem");
413     return _ArrayIndexOutOfBoundsException_instance;
414   }
415   ciInstance* ArrayStoreException_instance() {
416     assert(_ArrayStoreException_instance != nullptr, "initialization problem");
417     return _ArrayStoreException_instance;
418   }
419   ciInstance* ClassCastException_instance() {
420     assert(_ClassCastException_instance != nullptr, "initialization problem");
421     return _ClassCastException_instance;
422   }
423 
424   ciInstance* the_null_string();
425   ciInstance* the_min_jint_string();
426 
427   static ciSymbol* unloaded_cisymbol() {
428     return _unloaded_cisymbol;
429   }
430   static ciObjArrayKlass* unloaded_ciobjarrayklass() {
431     return _unloaded_ciobjarrayklass;
432   }
433   static ciInstanceKlass* unloaded_ciinstance_klass() {
434     return _unloaded_ciinstance_klass;
435   }
436   ciInstance* unloaded_ciinstance();
437 
438   ciInstanceKlass* get_box_klass_for_primitive_type(BasicType type);
439 
440   ciKlass*  find_system_klass(ciSymbol* klass_name);
441 
442   // Note:  To find a class from its name string, use ciSymbol::make,
443   // but consider adding to vmSymbols.hpp instead.
444 
445   // converts the ciKlass* representing the holder of a method into a
446   // ciInstanceKlass*.  This is needed since the holder of a method in
447   // the bytecodes could be an array type.  Basically this converts
448   // array types into java/lang/Object and other types stay as they are.
449   static ciInstanceKlass* get_instance_klass_for_declared_method_holder(ciKlass* klass);
450 
451   // Access to the compile-lifetime allocation arena.
452   Arena*    arena() { return _arena; }
453 
454   // What is the current compilation environment?
455   static ciEnv* current() { return CompilerThread::current()->env(); }
456 
457   // Overload with current thread argument
458   static ciEnv* current(CompilerThread *thread) { return thread->env(); }
459 
460   // Per-compiler data.  (Used by C2 to publish the Compile* pointer.)
461   void* compiler_data() const { return _compiler_data; }
462   void set_compiler_data(void* x) { _compiler_data = x; }
463 
464   // Notice that a method has been inlined in the current compile;
465   // used only for statistics.
466   void notice_inlined_method(ciMethod* method);
467 
468   // Total number of bytecodes in inlined methods in this compile
469   int num_inlined_bytecodes() const;
470 
471   // Output stream for logging compilation info.
472   CompileLog* log() { return _log; }
473   void set_log(CompileLog* log) { _log = log; }
474 
475   void record_failure(const char* reason);      // Record failure and report later
476   void report_failure(const char* reason);      // Report failure immediately
477   void record_method_not_compilable(const char* reason, bool all_tiers = false);
478   void record_out_of_memory_failure();
479 
480   // RedefineClasses support
481   void metadata_do(MetadataClosure* f) { _factory->metadata_do(f); }
482 
483   // Replay support
484 private:
485   static int klass_compare(const InstanceKlass* const &ik1, const InstanceKlass* const &ik2) {
486     if (ik1 > ik2) {
487       return 1;
488     } else if (ik1 < ik2) {
489       return -1;
490     } else {
491       return 0;
492     }
493   }
494   bool dyno_loc(const InstanceKlass* ik, const char *&loc) const;
495   void set_dyno_loc(const InstanceKlass* ik);
496   void record_best_dyno_loc(const InstanceKlass* ik);
497   bool print_dyno_loc(outputStream* out, const InstanceKlass* ik) const;
498 
499   GrowableArray<const InstanceKlass*>* _dyno_klasses;
500   GrowableArray<const char *>*         _dyno_locs;
501 
502 #define MAX_DYNO_NAME_LENGTH 1024
503   char _dyno_name[MAX_DYNO_NAME_LENGTH+1];
504 
505 public:
506   // Dump the compilation replay data for the ciEnv to the stream.
507   void dump_replay_data(int compile_id);
508   void dump_inline_data(int compile_id);
509   void dump_replay_data(outputStream* out);
510   void dump_replay_data_unsafe(outputStream* out);
511   void dump_replay_data_helper(outputStream* out);
512   void dump_compile_data(outputStream* out);
513   void dump_replay_data_version(outputStream* out);
514 
515   ciWrapper* make_early_larval_wrapper(ciType* type) const {
516     return _factory->make_early_larval_wrapper(type);
517   }
518 
519   ciWrapper* make_null_free_wrapper(ciType* type) const {
520     return _factory->make_null_free_wrapper(type);
521   }
522 
523   const char *dyno_name(const InstanceKlass* ik) const;
524   const char *replay_name(const InstanceKlass* ik) const;
525   const char *replay_name(ciKlass* i) const;
526 
527   void record_lambdaform(Thread* thread, oop obj);
528   void record_member(Thread* thread, oop obj);
529   void record_mh(Thread* thread, oop obj);
530   void record_call_site_obj(Thread* thread, oop obj);
531   void record_call_site_method(Thread* thread, Method* adapter);
532   void process_invokedynamic(const constantPoolHandle &cp, int index, JavaThread* thread);
533   void process_invokehandle(const constantPoolHandle &cp, int index, JavaThread* thread);
534   void find_dynamic_call_sites();
535 };
536 
537 #endif // SHARE_CI_CIENV_HPP