1 /*
2 * Copyright (c) 1997, 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_OOPS_GENERATEOOPMAP_HPP
26 #define SHARE_OOPS_GENERATEOOPMAP_HPP
27
28 #include "memory/allocation.hpp"
29 #include "oops/method.hpp"
30 #include "oops/oopsHierarchy.hpp"
31 #include "runtime/signature.hpp"
32 #include "utilities/bitMap.hpp"
33
34 // Forward definition
35 class BytecodeStream;
36 class GenerateOopMap;
37 class BasicBlock;
38 class CellTypeState;
39 class StackMap;
40
41 // These two should be removed. But requires some code to be cleaned up
42 #define MAXARGSIZE 256 // This should be enough
43 #define MAX_LOCAL_VARS 65536 // 16-bit entry
44
45 typedef void (*jmpFct_t)(GenerateOopMap *c, int bcpDelta, int* data);
46
47
48 // RetTable
49 //
50 // Contains mapping between jsr targets and there return addresses. One-to-many mapping
51 //
52 class RetTableEntry : public ResourceObj {
53 private:
54 static int _init_nof_jsrs; // Default size of jsrs list
55 int _target_bci; // Target PC address of jump (bytecode index)
56 GrowableArray<int> * _jsrs; // List of return addresses (bytecode index)
57 RetTableEntry *_next; // Link to next entry
58 public:
59 RetTableEntry(int target, RetTableEntry *next);
60
61 // Query
62 int target_bci() const { return _target_bci; }
63 int nof_jsrs() const { return _jsrs->length(); }
64 int jsrs(int i) const { assert(i>=0 && i<nof_jsrs(), "Index out of bounds"); return _jsrs->at(i); }
65
66 // Update entry
67 void add_jsr (int return_bci) { _jsrs->append(return_bci); }
68 void add_delta (int bci, int delta);
69 RetTableEntry * next() const { return _next; }
70 };
71
72
73 class RetTable {
74 private:
75 RetTableEntry *_first;
76 static int _init_nof_entries;
77
78 void add_jsr(int return_bci, int target_bci); // Adds entry to list
79 public:
80 RetTable() { _first = nullptr; }
81 void compute_ret_table(const methodHandle& method);
82 void update_ret_table(int bci, int delta);
83 RetTableEntry* find_jsrs_for_target(int targBci);
84 };
85
86 //
87 // CellTypeState
88 //
89 class CellTypeState {
90 private:
91 unsigned int _state;
92
93 // Masks for separating the BITS and INFO portions of a CellTypeState
94 enum { info_mask = right_n_bits(27),
95 bits_mask = (int)(~info_mask) };
96
97 // These constant are used for manipulating the BITS portion of a
98 // CellTypeState
99 enum { uninit_bit = (int)(nth_bit(31)),
100 ref_bit = nth_bit(30),
101 val_bit = nth_bit(29),
102 addr_bit = nth_bit(28),
103 live_bits_mask = (int)(bits_mask & ~uninit_bit) };
104
105 // These constants are used for manipulating the INFO portion of a
106 // CellTypeState
107 enum { top_info_bit = nth_bit(26),
108 not_bottom_info_bit = nth_bit(25),
109 info_data_mask = right_n_bits(25),
110 info_conflict = info_mask };
111
112 // Within the INFO data, these values are used to distinguish different
113 // kinds of references.
114 enum { ref_not_lock_bit = nth_bit(24), // 0 if this reference is locked as a monitor
115 ref_slot_bit = nth_bit(23), // 1 if this reference is a "slot" reference,
116 // 0 if it is a "line" reference.
117 ref_data_mask = right_n_bits(23) };
118
119 // Within the INFO data, these values are used to distinguish different
120 // kinds of value types.
121 enum { valuetype_slot_bit = nth_bit(24), // 1 if this reference is a "slot" value type,
122 // 0 if it is a "line" value type.
123 valuetype_data_mask = right_n_bits(24) };
124
125 // These values are used to initialize commonly used CellTypeState
126 // constants.
127 enum { bottom_value = 0,
128 uninit_value = (int)(uninit_bit | info_conflict),
129 ref_value = ref_bit,
130 ref_conflict = ref_bit | info_conflict,
131 val_value = val_bit | info_conflict,
132 addr_value = addr_bit,
133 addr_conflict = addr_bit | info_conflict };
134
135 public:
136
137 // Since some C++ constructors generate poor code for declarations of the
138 // form...
139 //
140 // CellTypeState vector[length];
141 //
142 // ...we avoid making a constructor for this class. CellTypeState values
143 // should be constructed using one of the make_* methods:
144
145 static CellTypeState make_any(int state) {
146 CellTypeState s;
147 s._state = state;
148 // Causes SS10 warning.
149 // assert(s.is_valid_state(), "check to see if CellTypeState is valid");
150 return s;
151 }
152
153 static CellTypeState make_bottom() {
154 return make_any(0);
155 }
156
157 static CellTypeState make_top() {
158 return make_any(AllBits);
159 }
160
161 static CellTypeState make_addr(int bci) {
162 assert((bci >= 0) && (bci < info_data_mask), "check to see if ret addr is valid");
163 return make_any(addr_bit | not_bottom_info_bit | (bci & info_data_mask));
164 }
165
166 static CellTypeState make_slot_ref(int slot_num) {
167 assert(slot_num >= 0 && slot_num < ref_data_mask, "slot out of range");
168 return make_any(ref_bit | not_bottom_info_bit | ref_not_lock_bit | ref_slot_bit |
169 (slot_num & ref_data_mask));
170 }
171
172 static CellTypeState make_line_ref(int bci) {
173 assert(bci >= 0 && bci < ref_data_mask, "line out of range");
174 return make_any(ref_bit | not_bottom_info_bit | ref_not_lock_bit |
175 (bci & ref_data_mask));
176 }
177
178 static CellTypeState make_lock_ref(int bci) {
179 assert(bci >= 0 && bci < ref_data_mask, "line out of range");
180 return make_any(ref_bit | not_bottom_info_bit | (bci & ref_data_mask));
181 }
182
183 // Query methods:
184 bool is_bottom() const { return _state == 0; }
185 bool is_live() const { return ((_state & live_bits_mask) != 0); }
186 bool is_valid_state() const {
187 // Uninitialized and value cells must contain no data in their info field:
188 if ((can_be_uninit() || can_be_value()) && !is_info_top()) {
189 return false;
190 }
191 // The top bit is only set when all info bits are set:
192 if (is_info_top() && ((_state & info_mask) != info_mask)) {
193 return false;
194 }
195 // The not_bottom_bit must be set when any other info bit is set:
196 if (is_info_bottom() && ((_state & info_mask) != 0)) {
197 return false;
198 }
199 return true;
200 }
201
202 bool is_address() const { return ((_state & bits_mask) == addr_bit); }
203 bool is_reference() const { return ((_state & bits_mask) == ref_bit); }
204 bool is_value() const { return ((_state & bits_mask) == val_bit); }
205 bool is_uninit() const { return ((_state & bits_mask) == (uint)uninit_bit); }
206
207 bool can_be_address() const { return ((_state & addr_bit) != 0); }
208 bool can_be_reference() const { return ((_state & ref_bit) != 0); }
209 bool can_be_value() const { return ((_state & val_bit) != 0); }
210 bool can_be_uninit() const { return ((_state & uninit_bit) != 0); }
211
212 bool is_info_bottom() const { return ((_state & not_bottom_info_bit) == 0); }
213 bool is_info_top() const { return ((_state & top_info_bit) != 0); }
214 int get_info() const {
215 assert((!is_info_top() && !is_info_bottom()),
216 "check to make sure top/bottom info is not used");
217 return (_state & info_data_mask);
218 }
219
220 bool is_good_address() const { return is_address() && !is_info_top(); }
221 bool is_lock_reference() const {
222 return ((_state & (bits_mask | top_info_bit | ref_not_lock_bit)) == ref_bit);
223 }
224 bool is_nonlock_reference() const {
225 return ((_state & (bits_mask | top_info_bit | ref_not_lock_bit)) == (ref_bit | ref_not_lock_bit));
226 }
227
228 bool equal(CellTypeState a) const { return _state == a._state; }
229 bool equal_kind(CellTypeState a) const {
230 return (_state & bits_mask) == (a._state & bits_mask);
231 }
232
233 char to_char() const;
234
235 // Merge
236 CellTypeState merge (CellTypeState cts, int slot) const;
237
238 // Debugging output
239 void print(outputStream *os);
240
241 // Default values of common values
242 static CellTypeState bottom;
243 static CellTypeState uninit;
244 static CellTypeState ref;
245 static CellTypeState value;
246 static CellTypeState refUninit;
247 static CellTypeState varUninit;
248 static CellTypeState top;
249 static CellTypeState addr;
250 };
251
252
253 //
254 // BasicBlockStruct
255 //
256 class BasicBlock: ResourceObj {
257 private:
258 bool _changed; // Reached a fixpoint or not
259 public:
260 enum Constants {
261 _dead_basic_block = -2,
262 _unreached = -1 // Alive but not yet reached by analysis
263 // >=0 // Alive and has a merged state
264 };
265
266 int _bci; // Start of basic block
267 int _end_bci; // Bci of last instruction in basicblock
268 int _max_locals; // Determines split between vars and stack
269 int _max_stack; // Determines split between stack and monitors
270 CellTypeState* _state; // State (vars, stack) at entry.
271 int _stack_top; // -1 indicates bottom stack value.
272 int _monitor_top; // -1 indicates bottom monitor stack value.
273
274 CellTypeState* vars() { return _state; }
275 CellTypeState* stack() { return _state + _max_locals; }
276
277 bool changed() { return _changed; }
278 void set_changed(bool s) { _changed = s; }
279
280 bool is_reachable() const { return _stack_top >= 0; } // Analysis has reached this basicblock
281
282 // All basicblocks that are unreachable are going to have a _stack_top == _dead_basic_block.
283 // This info. is setup in a pre-parse before the real abstract interpretation starts.
284 bool is_dead() const { return _stack_top == _dead_basic_block; }
285 bool is_alive() const { return _stack_top != _dead_basic_block; }
286 void mark_as_alive() { assert(is_dead(), "must be dead"); _stack_top = _unreached; }
287 };
288
289
290 //
291 // GenerateOopMap
292 //
293 // Main class used to compute the pointer-maps in a Method
294 //
295 class GenerateOopMap {
296 protected:
297
298 // _monitor_top is set to this constant to indicate that a monitor matching
299 // problem was encountered prior to this point in control flow.
300 enum { bad_monitors = -1 };
301
302 // Main variables
303 methodHandle _method; // The method we are examine
304 RetTable _rt; // Contains the return address mappings
305 int _max_locals; // Cached value of no. of locals
306 int _max_stack; // Cached value of max. stack depth
307 int _max_monitors; // Cached value of max. monitor stack depth
308 int _has_exceptions; // True, if exceptions exist for method
309 bool _got_error; // True, if an error occurred during interpretation.
310 Handle _exception; // Exception if got_error is true.
311 bool _did_rewriting; // was bytecodes rewritten
312 bool _did_relocation; // was relocation necessary
313 bool _monitor_safe; // The monitors in this method have been determined
314 // to be safe.
315 bool _all_exception_edges; // All bytecodes can reach containing exception handler.
316
317 // Working Cell type state
318 int _state_len; // Size of states
319 CellTypeState *_state; // list of states
320 char *_state_vec_buf; // Buffer used to print a readable version of a state
321 int _stack_top;
322 int _monitor_top;
323
324 // Timing and statistics
325 static elapsedTimer _total_oopmap_time; // Holds cumulative oopmap generation time
326 static uint64_t _total_byte_count; // Holds cumulative number of bytes inspected
327
328 // Cell type methods
329 void init_state();
330 void make_context_uninitialized ();
331 int methodsig_to_effect (Symbol* signature, bool isStatic, CellTypeState* effect);
332 bool merge_local_state_vectors (CellTypeState* cts, CellTypeState* bbts);
333 bool merge_monitor_state_vectors(CellTypeState* cts, CellTypeState* bbts);
334 void copy_state (CellTypeState *dst, CellTypeState *src);
335 void merge_state_into_bb (BasicBlock *bb);
336 static void merge_state (GenerateOopMap *gom, int bcidelta, int* data);
337 void set_var (int localNo, CellTypeState cts);
338 CellTypeState get_var (int localNo);
339 CellTypeState pop ();
340 void push (CellTypeState cts);
341 CellTypeState monitor_pop ();
342 void monitor_push (CellTypeState cts);
343 CellTypeState * vars () { return _state; }
344 CellTypeState * stack () { return _state+_max_locals; }
345 CellTypeState * monitors () { return _state+_max_locals+_max_stack; }
346
347 void replace_all_CTS_matches (CellTypeState match,
348 CellTypeState replace);
349 void print_states (outputStream *os, CellTypeState *vector, int num);
350 void print_current_state (outputStream *os,
351 BytecodeStream *itr,
352 bool detailed);
353 void report_monitor_mismatch (const char *msg);
354
355 // Basicblock info
356 BasicBlock * _basic_blocks; // Array of basicblock info
357 int _bb_count;
358 ResourceBitMap _bb_hdr_bits;
359
360 // Basicblocks methods
361 void initialize_bb ();
362 void mark_bbheaders();
363 bool is_bb_header (int bci) const {
364 return _bb_hdr_bits.at(bci);
365 }
366 int bb_count () const { return _bb_count; }
367 void set_bbmark_bit (int bci);
368 BasicBlock * get_basic_block_at (int bci) const;
369 BasicBlock * get_basic_block_containing (int bci) const;
370 void interp_bb (BasicBlock *bb);
371 void restore_state (BasicBlock *bb);
372 int next_bb_start_pc (BasicBlock *bb);
373 void update_basic_blocks (int bci, int delta, int new_method_size);
374 static void bb_mark_fct (GenerateOopMap *c, int deltaBci, int *data);
375
376 // Dead code detection
377 void mark_reachable_code();
378 static void reachable_basicblock (GenerateOopMap *c, int deltaBci, int *data);
379
380 // Interpretation methods (primary)
381 void do_interpretation ();
382 void init_basic_blocks ();
383 void setup_method_entry_state ();
384 void interp_all ();
385
386 // Interpretation methods (secondary)
387 void interp1 (BytecodeStream *itr);
388 void do_exception_edge (BytecodeStream *itr);
389 void check_type (CellTypeState expected, CellTypeState actual);
390 void ppstore (CellTypeState *in, int loc_no);
391 void ppload (CellTypeState *out, int loc_no);
392 void ppush1 (CellTypeState in);
393 void ppush (CellTypeState *in);
394 void ppop1 (CellTypeState out);
395 void ppop (CellTypeState *out);
396 void ppop_any (int poplen);
397 void pp (CellTypeState *in, CellTypeState *out);
398 void pp_new_ref (CellTypeState *in, int bci);
399 void ppdupswap (int poplen, const char *out);
400 void do_ldc (int bci);
401 void do_astore (int idx);
402 void do_jsr (int delta);
403 void do_field (int is_get, int is_static, int idx, int bci, Bytecodes::Code bc);
404 void do_method (int is_static, int idx, int bci, Bytecodes::Code bc);
405 void do_multianewarray (int dims, int bci);
406 void do_monitorenter (int bci);
407 void do_monitorexit (int bci);
408 void do_return_monitor_check ();
409 void do_checkcast ();
410 CellTypeState *signature_to_effect (const Symbol* sig, int bci, CellTypeState *out);
411 int copy_cts (CellTypeState *dst, CellTypeState *src);
412
413 // Error handling
414 void error_work (const char *format, va_list ap) ATTRIBUTE_PRINTF(2, 0);
415 void report_error (const char *format, ...) ATTRIBUTE_PRINTF(2, 3);
416 void verify_error (const char *format, ...) ATTRIBUTE_PRINTF(2, 3);
417 bool got_error() { return _got_error; }
418
419 // Create result set
420 bool _report_result;
421 bool _report_result_for_send; // Unfortunately, stackmaps for sends are special, so we need some extra
422 BytecodeStream *_itr_send; // variables to handle them properly.
423
424 void report_result ();
425
426 // Initvars
427 GrowableArray<intptr_t> * _init_vars;
428
429 void initialize_vars ();
430 void add_to_ref_init_set (int localNo);
431
432 // Conflicts rewrite logic
433 bool _conflict; // True, if a conflict occurred during interpretation
434 int _nof_refval_conflicts; // No. of conflicts that require rewrites
435 int * _new_var_map;
436
437 void record_refval_conflict (int varNo);
438 void rewrite_refval_conflicts ();
439 void rewrite_refval_conflict (int from, int to);
440 bool rewrite_refval_conflict_inst (BytecodeStream *i, int from, int to);
441 bool rewrite_load_or_store (BytecodeStream *i, Bytecodes::Code bc, Bytecodes::Code bc0, unsigned int varNo);
442
443 void expand_current_instr (int bci, int ilen, int newIlen, u_char inst_buffer[]);
444 bool is_astore (BytecodeStream *itr, int *index);
445 bool is_aload (BytecodeStream *itr, int *index);
446
447 // List of bci's where a return address is on top of the stack
448 GrowableArray<int>* _ret_adr_tos;
449
450 bool stack_top_holds_ret_addr (int bci);
451 void compute_ret_adr_at_TOS ();
452 void update_ret_adr_at_TOS (int bci, int delta);
453
454 int binsToHold (int no) { return ((no+(BitsPerWord-1))/BitsPerWord); }
455 char *state_vec_to_string (CellTypeState* vec, int len);
456
457 // Helper method. If the current instruction
458 // is a control transfer, then calls the jmpFct all possible destinations.
459 void ret_jump_targets_do (BytecodeStream *bcs, jmpFct_t jmpFct, int varNo,int *data);
460 bool jump_targets_do (BytecodeStream *bcs, jmpFct_t jmpFct, int *data);
461
462 friend class RelocCallback;
463 public:
464 GenerateOopMap(const methodHandle& method, bool all_exception_edges);
465
466 // Compute the map - returns true on success and false on error.
467 bool compute_map(Thread* current);
468 // Returns the exception related to any error, if the map was computed by a suitable JavaThread.
469 Handle exception() { return _exception; }
470
471 void result_for_basicblock(int bci); // Do a callback on fill_stackmap_for_opcodes for basicblock containing bci
472
473 // Query
474 int max_locals() const { return _max_locals; }
475 Method* method() const { return _method(); }
476 methodHandle method_as_handle() const { return _method; }
477
478 bool did_rewriting() { return _did_rewriting; }
479 bool did_relocation() { return _did_relocation; }
480
481 static void print_time();
482
483 // Monitor query
484 bool monitor_safe() { return _monitor_safe; }
485
486 // Specialization methods. Intended use:
487 // - fill_stackmap_for_opcodes is called once for each bytecode index in order (0...code_length-1)
488 //
489 // All these methods are used during a call to: compute_map. Note: Non of the return results are valid
490 // after compute_map returns, since all values are allocated as resource objects.
491 //
492 // All virtual method must be implemented in subclasses
493 virtual bool allow_rewrites () const { return false; }
494 virtual bool report_results () const { return true; }
495 virtual bool report_init_vars () const { return true; }
496 virtual void fill_stackmap_for_opcodes (BytecodeStream *bcs,
497 CellTypeState* vars,
498 CellTypeState* stack,
499 int stackTop) { ShouldNotReachHere(); }
500 };
501
502 //
503 // Subclass of the GenerateOopMap Class that just do rewrites of the method, if needed.
504 // It does not store any oopmaps.
505 //
506 class ResolveOopMapConflicts: public GenerateOopMap {
507 private:
508
509 virtual bool report_results() const { return false; }
510 virtual bool report_init_vars() const { return true; }
511 virtual bool allow_rewrites() const { return true; }
512 virtual void fill_stackmap_for_opcodes (BytecodeStream *bcs,
513 CellTypeState* vars,
514 CellTypeState* stack,
515 int stack_top) {}
516
517 #ifndef PRODUCT
518 // Statistics
519 static int _nof_invocations;
520 static int _nof_rewrites;
521 static int _nof_relocations;
522 #endif
523
524 public:
525 ResolveOopMapConflicts(const methodHandle& method) : GenerateOopMap(method, true) { }
526 methodHandle do_potential_rewrite(TRAPS);
527 };
528
529
530 //
531 // Subclass used by the compiler to generate pairing information
532 //
533 class GeneratePairingInfo: public GenerateOopMap {
534 private:
535
536 virtual bool report_results() const { return false; }
537 virtual bool report_init_vars() const { return false; }
538 virtual bool allow_rewrites() const { return false; }
539 virtual void fill_stackmap_for_opcodes (BytecodeStream *bcs,
540 CellTypeState* vars,
541 CellTypeState* stack,
542 int stack_top) {}
543 public:
544 GeneratePairingInfo(const methodHandle& method) : GenerateOopMap(method, false) {};
545
546 // Call compute_map() to generate info.
547 };
548
549 #endif // SHARE_OOPS_GENERATEOOPMAP_HPP