1 /*
  2  * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 #include "interpreter/bytecodeStream.hpp"
 27 #include "interpreter/oopMapCache.hpp"
 28 #include "logging/log.hpp"
 29 #include "logging/logStream.hpp"
 30 #include "memory/allocation.inline.hpp"
 31 #include "memory/resourceArea.hpp"
 32 #include "oops/generateOopMap.hpp"
 33 #include "oops/oop.inline.hpp"
 34 #include "runtime/atomic.hpp"
 35 #include "runtime/handles.inline.hpp"
 36 #include "runtime/safepoint.hpp"
 37 #include "runtime/signature.hpp"
 38 #include "utilities/globalCounter.inline.hpp"
 39 
 40 class OopMapCacheEntry: private InterpreterOopMap {
 41   friend class InterpreterOopMap;
 42   friend class OopMapForCacheEntry;
 43   friend class OopMapCache;
 44   friend class VerifyClosure;
 45 
 46  private:
 47   OopMapCacheEntry* _next;
 48 
 49  protected:
 50   // Initialization
 51   void fill(const methodHandle& method, int bci);
 52   // fills the bit mask for native calls
 53   void fill_for_native(const methodHandle& method);
 54   void set_mask(CellTypeState* vars, CellTypeState* stack, int stack_top);
 55 
 56   // Deallocate bit masks and initialize fields
 57   void flush();
 58 
 59   static void deallocate(OopMapCacheEntry* const entry);
 60 
 61  private:
 62   void allocate_bit_mask();   // allocates the bit mask on C heap f necessary
 63   void deallocate_bit_mask(); // allocates the bit mask on C heap f necessary
 64   bool verify_mask(CellTypeState *vars, CellTypeState *stack, int max_locals, int stack_top);
 65 
 66  public:
 67   OopMapCacheEntry() : InterpreterOopMap() {
 68     _next = nullptr;
 69   }
 70 };
 71 
 72 
 73 // Implementation of OopMapForCacheEntry
 74 // (subclass of GenerateOopMap, initializes an OopMapCacheEntry for a given method and bci)
 75 
 76 class OopMapForCacheEntry: public GenerateOopMap {
 77   OopMapCacheEntry *_entry;
 78   int               _bci;
 79   int               _stack_top;
 80 
 81   virtual bool report_results() const     { return false; }
 82   virtual bool possible_gc_point          (BytecodeStream *bcs);
 83   virtual void fill_stackmap_prolog       (int nof_gc_points);
 84   virtual void fill_stackmap_epilog       ();
 85   virtual void fill_stackmap_for_opcodes  (BytecodeStream *bcs,
 86                                            CellTypeState* vars,
 87                                            CellTypeState* stack,
 88                                            int stack_top);
 89   virtual void fill_init_vars             (GrowableArray<intptr_t> *init_vars);
 90 
 91  public:
 92   OopMapForCacheEntry(const methodHandle& method, int bci, OopMapCacheEntry *entry);
 93 
 94   // Computes stack map for (method,bci) and initialize entry
 95   bool compute_map(Thread* current);
 96   int  size();
 97 };
 98 
 99 
100 OopMapForCacheEntry::OopMapForCacheEntry(const methodHandle& method, int bci, OopMapCacheEntry* entry) : GenerateOopMap(method) {
101   _bci       = bci;
102   _entry     = entry;
103   _stack_top = -1;
104 }
105 
106 
107 bool OopMapForCacheEntry::compute_map(Thread* current) {
108   assert(!method()->is_native(), "cannot compute oop map for native methods");
109   // First check if it is a method where the stackmap is always empty
110   if (method()->code_size() == 0 || method()->max_locals() + method()->max_stack() == 0) {
111     _entry->set_mask_size(0);
112   } else {
113     ResourceMark rm;
114     if (!GenerateOopMap::compute_map(current)) {
115       fatal("Unrecoverable verification or out-of-memory error");
116       return false;
117     }
118     result_for_basicblock(_bci);
119   }
120   return true;
121 }
122 
123 
124 bool OopMapForCacheEntry::possible_gc_point(BytecodeStream *bcs) {
125   return false; // We are not reporting any result. We call result_for_basicblock directly
126 }
127 
128 
129 void OopMapForCacheEntry::fill_stackmap_prolog(int nof_gc_points) {
130   // Do nothing
131 }
132 
133 
134 void OopMapForCacheEntry::fill_stackmap_epilog() {
135   // Do nothing
136 }
137 
138 
139 void OopMapForCacheEntry::fill_init_vars(GrowableArray<intptr_t> *init_vars) {
140   // Do nothing
141 }
142 
143 
144 void OopMapForCacheEntry::fill_stackmap_for_opcodes(BytecodeStream *bcs,
145                                                     CellTypeState* vars,
146                                                     CellTypeState* stack,
147                                                     int stack_top) {
148   // Only interested in one specific bci
149   if (bcs->bci() == _bci) {
150     _entry->set_mask(vars, stack, stack_top);
151     _stack_top = stack_top;
152   }
153 }
154 
155 
156 int OopMapForCacheEntry::size() {
157   assert(_stack_top != -1, "compute_map must be called first");
158   return ((method()->is_static()) ? 0 : 1) + method()->max_locals() + _stack_top;
159 }
160 
161 
162 // Implementation of InterpreterOopMap and OopMapCacheEntry
163 
164 class VerifyClosure : public OffsetClosure {
165  private:
166   OopMapCacheEntry* _entry;
167   bool              _failed;
168 
169  public:
170   VerifyClosure(OopMapCacheEntry* entry)         { _entry = entry; _failed = false; }
171   void offset_do(int offset)                     { if (!_entry->is_oop(offset)) _failed = true; }
172   bool failed() const                            { return _failed; }
173 };
174 
175 InterpreterOopMap::InterpreterOopMap() {
176   initialize();
177 }
178 
179 InterpreterOopMap::~InterpreterOopMap() {
180   if (has_valid_mask() && mask_size() > small_mask_limit) {
181     assert(_bit_mask[0] != 0, "should have pointer to C heap");
182     FREE_C_HEAP_ARRAY(uintptr_t, _bit_mask[0]);
183   }
184 }
185 
186 bool InterpreterOopMap::is_empty() const {
187   bool result = _method == nullptr;
188   assert(_method != nullptr || (_bci == 0 &&
189     (_mask_size == 0 || _mask_size == USHRT_MAX) &&
190     _bit_mask[0] == 0), "Should be completely empty");
191   return result;
192 }
193 
194 void InterpreterOopMap::initialize() {
195   _method    = nullptr;
196   _mask_size = USHRT_MAX;  // This value should cause a failure quickly
197   _bci       = 0;
198   _expression_stack_size = 0;
199   _num_oops  = 0;
200   for (int i = 0; i < N; i++) _bit_mask[i] = 0;
201 }
202 
203 void InterpreterOopMap::iterate_oop(OffsetClosure* oop_closure) const {
204   int n = number_of_entries();
205   int word_index = 0;
206   uintptr_t value = 0;
207   uintptr_t mask = 0;
208   // iterate over entries
209   for (int i = 0; i < n; i++, mask <<= bits_per_entry) {
210     // get current word
211     if (mask == 0) {
212       value = bit_mask()[word_index++];
213       mask = 1;
214     }
215     // test for oop
216     if ((value & (mask << oop_bit_number)) != 0) oop_closure->offset_do(i);
217   }
218 }
219 
220 void InterpreterOopMap::print() const {
221   int n = number_of_entries();
222   tty->print("oop map for ");
223   method()->print_value();
224   tty->print(" @ %d = [%d] { ", bci(), n);
225   for (int i = 0; i < n; i++) {
226     if (is_dead(i)) tty->print("%d+ ", i);
227     else
228     if (is_oop(i)) tty->print("%d ", i);
229   }
230   tty->print_cr("}");
231 }
232 
233 class MaskFillerForNative: public NativeSignatureIterator {
234  private:
235   uintptr_t * _mask;                             // the bit mask to be filled
236   int         _size;                             // the mask size in bits
237   int         _num_oops;
238 
239   void set_one(int i) {
240     _num_oops++;
241     i *= InterpreterOopMap::bits_per_entry;
242     assert(0 <= i && i < _size, "offset out of bounds");
243     _mask[i / BitsPerWord] |= (((uintptr_t) 1 << InterpreterOopMap::oop_bit_number) << (i % BitsPerWord));
244   }
245 
246  public:
247   void pass_byte()                               { /* ignore */ }
248   void pass_short()                              { /* ignore */ }
249   void pass_int()                                { /* ignore */ }
250   void pass_long()                               { /* ignore */ }
251   void pass_float()                              { /* ignore */ }
252   void pass_double()                             { /* ignore */ }
253   void pass_object()                             { set_one(offset()); }
254 
255   MaskFillerForNative(const methodHandle& method, uintptr_t* mask, int size) : NativeSignatureIterator(method) {
256     _mask   = mask;
257     _size   = size;
258     _num_oops = 0;
259     // initialize with 0
260     int i = (size + BitsPerWord - 1) / BitsPerWord;
261     while (i-- > 0) _mask[i] = 0;
262   }
263 
264   void generate() {
265     iterate();
266   }
267 
268   int num_oops() { return _num_oops; }
269 };
270 
271 bool OopMapCacheEntry::verify_mask(CellTypeState* vars, CellTypeState* stack, int max_locals, int stack_top) {
272   // Check mask includes map
273   VerifyClosure blk(this);
274   iterate_oop(&blk);
275   if (blk.failed()) return false;
276 
277   // Check if map is generated correctly
278   // (Use ?: operator to make sure all 'true' & 'false' are represented exactly the same so we can use == afterwards)
279   const bool log = log_is_enabled(Trace, interpreter, oopmap);
280   LogStream st(Log(interpreter, oopmap)::trace());
281 
282   if (log) st.print("Locals (%d): ", max_locals);
283   for(int i = 0; i < max_locals; i++) {
284     bool v1 = is_oop(i)               ? true : false;
285     bool v2 = vars[i].is_reference()  ? true : false;
286     assert(v1 == v2, "locals oop mask generation error");
287     if (log) st.print("%d", v1 ? 1 : 0);
288   }
289   if (log) st.cr();
290 
291   if (log) st.print("Stack (%d): ", stack_top);
292   for(int j = 0; j < stack_top; j++) {
293     bool v1 = is_oop(max_locals + j)  ? true : false;
294     bool v2 = stack[j].is_reference() ? true : false;
295     assert(v1 == v2, "stack oop mask generation error");
296     if (log) st.print("%d", v1 ? 1 : 0);
297   }
298   if (log) st.cr();
299   return true;
300 }
301 
302 void OopMapCacheEntry::allocate_bit_mask() {
303   if (mask_size() > small_mask_limit) {
304     assert(_bit_mask[0] == 0, "bit mask should be new or just flushed");
305     _bit_mask[0] = (intptr_t)
306       NEW_C_HEAP_ARRAY(uintptr_t, mask_word_size(), mtClass);
307   }
308 }
309 
310 void OopMapCacheEntry::deallocate_bit_mask() {
311   if (mask_size() > small_mask_limit && _bit_mask[0] != 0) {
312     assert(!Thread::current()->resource_area()->contains((void*)_bit_mask[0]),
313       "This bit mask should not be in the resource area");
314     FREE_C_HEAP_ARRAY(uintptr_t, _bit_mask[0]);
315     debug_only(_bit_mask[0] = 0;)
316   }
317 }
318 
319 
320 void OopMapCacheEntry::fill_for_native(const methodHandle& mh) {
321   assert(mh->is_native(), "method must be native method");
322   set_mask_size(mh->size_of_parameters() * bits_per_entry);
323   allocate_bit_mask();
324   // fill mask for parameters
325   MaskFillerForNative mf(mh, bit_mask(), mask_size());
326   mf.generate();
327   _num_oops = mf.num_oops();
328 }
329 
330 
331 void OopMapCacheEntry::fill(const methodHandle& method, int bci) {
332   // Flush entry to deallocate an existing entry
333   flush();
334   set_method(method());
335   set_bci(checked_cast<unsigned short>(bci));  // bci is always u2
336   if (method->is_native()) {
337     // Native method activations have oops only among the parameters and one
338     // extra oop following the parameters (the mirror for static native methods).
339     fill_for_native(method);
340   } else {
341     OopMapForCacheEntry gen(method, bci, this);
342     if (!gen.compute_map(Thread::current())) {
343       fatal("Unrecoverable verification or out-of-memory error");
344     }
345   }
346 }
347 
348 
349 void OopMapCacheEntry::set_mask(CellTypeState *vars, CellTypeState *stack, int stack_top) {
350   // compute bit mask size
351   int max_locals = method()->max_locals();
352   int n_entries = max_locals + stack_top;
353   set_mask_size(n_entries * bits_per_entry);
354   allocate_bit_mask();
355   set_expression_stack_size(stack_top);
356 
357   // compute bits
358   int word_index = 0;
359   uintptr_t value = 0;
360   uintptr_t mask = 1;
361 
362   _num_oops = 0;
363   CellTypeState* cell = vars;
364   for (int entry_index = 0; entry_index < n_entries; entry_index++, mask <<= bits_per_entry, cell++) {
365     // store last word
366     if (mask == 0) {
367       bit_mask()[word_index++] = value;
368       value = 0;
369       mask = 1;
370     }
371 
372     // switch to stack when done with locals
373     if (entry_index == max_locals) {
374       cell = stack;
375     }
376 
377     // set oop bit
378     if ( cell->is_reference()) {
379       value |= (mask << oop_bit_number );
380       _num_oops++;
381     }
382 
383     // set dead bit
384     if (!cell->is_live()) {
385       value |= (mask << dead_bit_number);
386       assert(!cell->is_reference(), "dead value marked as oop");
387     }
388   }
389 
390   // make sure last word is stored
391   bit_mask()[word_index] = value;
392 
393   // verify bit mask
394   assert(verify_mask(vars, stack, max_locals, stack_top), "mask could not be verified");
395 }
396 
397 void OopMapCacheEntry::flush() {
398   deallocate_bit_mask();
399   initialize();
400 }
401 
402 void OopMapCacheEntry::deallocate(OopMapCacheEntry* const entry) {
403   entry->flush();
404   FREE_C_HEAP_OBJ(entry);
405 }
406 
407 // Implementation of OopMapCache
408 
409 void InterpreterOopMap::copy_from(const OopMapCacheEntry* src) {
410   // The expectation is that this InterpreterOopMap is recently created
411   // and empty. It is used to get a copy of a cached entry.
412   assert(!has_valid_mask(), "InterpreterOopMap object can only be filled once");
413   assert(src->has_valid_mask(), "Cannot copy entry with an invalid mask");
414 
415   set_method(src->method());
416   set_bci(src->bci());
417   set_mask_size(src->mask_size());
418   set_expression_stack_size(src->expression_stack_size());
419   _num_oops = src->num_oops();
420 
421   // Is the bit mask contained in the entry?
422   if (src->mask_size() <= small_mask_limit) {
423     memcpy(_bit_mask, src->_bit_mask, mask_word_size() * BytesPerWord);
424   } else {
425     _bit_mask[0] = (uintptr_t) NEW_C_HEAP_ARRAY(uintptr_t, mask_word_size(), mtClass);
426     memcpy((void*) _bit_mask[0], (void*) src->_bit_mask[0], mask_word_size() * BytesPerWord);
427   }
428 }
429 
430 inline unsigned int OopMapCache::hash_value_for(const methodHandle& method, int bci) const {
431   // We use method->code_size() rather than method->identity_hash() below since
432   // the mark may not be present if a pointer to the method is already reversed.
433   return   ((unsigned int) bci)
434          ^ ((unsigned int) method->max_locals()         << 2)
435          ^ ((unsigned int) method->code_size()          << 4)
436          ^ ((unsigned int) method->size_of_parameters() << 6);
437 }
438 
439 OopMapCacheEntry* volatile OopMapCache::_old_entries = nullptr;
440 
441 OopMapCache::OopMapCache() {
442   for(int i = 0; i < size; i++) _array[i] = nullptr;
443 }
444 
445 
446 OopMapCache::~OopMapCache() {
447   // Deallocate oop maps that are allocated out-of-line
448   flush();
449 }
450 
451 OopMapCacheEntry* OopMapCache::entry_at(int i) const {
452   return Atomic::load_acquire(&(_array[i % size]));
453 }
454 
455 bool OopMapCache::put_at(int i, OopMapCacheEntry* entry, OopMapCacheEntry* old) {
456   return Atomic::cmpxchg(&_array[i % size], old, entry) == old;
457 }
458 
459 void OopMapCache::flush() {
460   for (int i = 0; i < size; i++) {
461     OopMapCacheEntry* entry = _array[i];
462     if (entry != nullptr) {
463       _array[i] = nullptr;  // no barrier, only called in OopMapCache destructor
464       OopMapCacheEntry::deallocate(entry);
465     }
466   }
467 }
468 
469 void OopMapCache::flush_obsolete_entries() {
470   assert(SafepointSynchronize::is_at_safepoint(), "called by RedefineClasses in a safepoint");
471   for (int i = 0; i < size; i++) {
472     OopMapCacheEntry* entry = _array[i];
473     if (entry != nullptr && !entry->is_empty() && entry->method()->is_old()) {
474       // Cache entry is occupied by an old redefined method and we don't want
475       // to pin it down so flush the entry.
476       if (log_is_enabled(Debug, redefine, class, oopmap)) {
477         ResourceMark rm;
478         log_debug(redefine, class, interpreter, oopmap)
479           ("flush: %s(%s): cached entry @%d",
480            entry->method()->name()->as_C_string(), entry->method()->signature()->as_C_string(), i);
481       }
482       _array[i] = nullptr;
483       OopMapCacheEntry::deallocate(entry);
484     }
485   }
486 }
487 
488 // Lookup or compute/cache the entry.
489 void OopMapCache::lookup(const methodHandle& method,
490                          int bci,
491                          InterpreterOopMap* entry_for) {
492   int probe = hash_value_for(method, bci);
493 
494   if (log_is_enabled(Debug, interpreter, oopmap)) {
495     static int count = 0;
496     ResourceMark rm;
497     log_debug(interpreter, oopmap)
498           ("%d - Computing oopmap at bci %d for %s at hash %d", ++count, bci,
499            method()->name_and_sig_as_C_string(), probe);
500   }
501 
502   // Search hashtable for match.
503   // Need a critical section to avoid race against concurrent reclamation.
504   {
505     GlobalCounter::CriticalSection cs(Thread::current());
506     for (int i = 0; i < probe_depth; i++) {
507       OopMapCacheEntry *entry = entry_at(probe + i);
508       if (entry != nullptr && !entry->is_empty() && entry->match(method, bci)) {
509         entry_for->copy_from(entry);
510         assert(!entry_for->is_empty(), "A non-empty oop map should be returned");
511         log_debug(interpreter, oopmap)("- found at hash %d", probe + i);
512         return;
513       }
514     }
515   }
516 
517   // Entry is not in hashtable.
518   // Compute entry
519 
520   OopMapCacheEntry* tmp = NEW_C_HEAP_OBJ(OopMapCacheEntry, mtClass);
521   tmp->initialize();
522   tmp->fill(method, bci);
523   entry_for->copy_from(tmp);
524 
525   if (method->should_not_be_cached()) {
526     // It is either not safe or not a good idea to cache this Method*
527     // at this time. We give the caller of lookup() a copy of the
528     // interesting info via parameter entry_for, but we don't add it to
529     // the cache. See the gory details in Method*.cpp.
530     OopMapCacheEntry::deallocate(tmp);
531     return;
532   }
533 
534   // First search for an empty slot
535   for (int i = 0; i < probe_depth; i++) {
536     OopMapCacheEntry* entry = entry_at(probe + i);
537     if (entry == nullptr) {
538       if (put_at(probe + i, tmp, nullptr)) {
539         assert(!entry_for->is_empty(), "A non-empty oop map should be returned");
540         return;
541       }
542     }
543   }
544 
545   log_debug(interpreter, oopmap)("*** collision in oopmap cache - flushing item ***");
546 
547   // No empty slot (uncommon case). Use (some approximation of a) LRU algorithm
548   // where the first entry in the collision array is replaced with the new one.
549   OopMapCacheEntry* old = entry_at(probe + 0);
550   if (put_at(probe + 0, tmp, old)) {
551     // Cannot deallocate old entry on the spot: it can still be used by readers
552     // that got a reference to it before we were able to replace it in the map.
553     // Instead of synchronizing on GlobalCounter here and incurring heavy thread
554     // walk, we do this clean up out of band.
555     enqueue_for_cleanup(old);
556   } else {
557     OopMapCacheEntry::deallocate(tmp);
558   }
559 
560   assert(!entry_for->is_empty(), "A non-empty oop map should be returned");
561   return;
562 }
563 
564 void OopMapCache::enqueue_for_cleanup(OopMapCacheEntry* entry) {
565   while (true) {
566     OopMapCacheEntry* head = Atomic::load(&_old_entries);
567     entry->_next = head;
568     if (Atomic::cmpxchg(&_old_entries, head, entry) == head) {
569       // Enqueued successfully.
570       break;
571     }
572   }
573 
574   if (log_is_enabled(Debug, interpreter, oopmap)) {
575     ResourceMark rm;
576     log_debug(interpreter, oopmap)("enqueue %s at bci %d for cleanup",
577                           entry->method()->name_and_sig_as_C_string(), entry->bci());
578   }
579 }
580 
581 bool OopMapCache::has_cleanup_work() {
582   return Atomic::load(&_old_entries) != nullptr;
583 }
584 
585 void OopMapCache::try_trigger_cleanup() {
586   // See we can take the lock for the notification without blocking.
587   // This allows triggering the cleanup from GC paths, that can hold
588   // the service lock for e.g. oop iteration in service thread.
589   if (has_cleanup_work() && Service_lock->try_lock_without_rank_check()) {
590     Service_lock->notify_all();
591     Service_lock->unlock();
592   }
593 }
594 
595 void OopMapCache::cleanup() {
596   OopMapCacheEntry* entry = Atomic::xchg(&_old_entries, (OopMapCacheEntry*)nullptr);
597   if (entry == nullptr) {
598     // No work.
599     return;
600   }
601 
602   // About to delete the entries than might still be accessed by other threads
603   // on lookup path. Need to sync up with them before proceeding.
604   GlobalCounter::write_synchronize();
605 
606   while (entry != nullptr) {
607     if (log_is_enabled(Debug, interpreter, oopmap)) {
608       ResourceMark rm;
609       log_debug(interpreter, oopmap)("cleanup entry %s at bci %d",
610                           entry->method()->name_and_sig_as_C_string(), entry->bci());
611     }
612     OopMapCacheEntry* next = entry->_next;
613     OopMapCacheEntry::deallocate(entry);
614     entry = next;
615   }
616 }
617 
618 void OopMapCache::compute_one_oop_map(const methodHandle& method, int bci, InterpreterOopMap* entry) {
619   // Due to the invariants above it's tricky to allocate a temporary OopMapCacheEntry on the stack
620   OopMapCacheEntry* tmp = NEW_C_HEAP_OBJ(OopMapCacheEntry, mtClass);
621   tmp->initialize();
622   tmp->fill(method, bci);
623   if (tmp->has_valid_mask()) {
624     entry->copy_from(tmp);
625   }
626   OopMapCacheEntry::deallocate(tmp);
627 }