< prev index next >

src/hotspot/share/runtime/deoptimization.cpp

Print this page

  33 #include "code/scopeDesc.hpp"
  34 #include "compiler/compilationPolicy.hpp"
  35 #include "compiler/compilerDefinitions.inline.hpp"
  36 #include "gc/shared/collectedHeap.hpp"
  37 #include "gc/shared/memAllocator.hpp"
  38 #include "interpreter/bytecode.inline.hpp"
  39 #include "interpreter/bytecodeStream.hpp"
  40 #include "interpreter/interpreter.hpp"
  41 #include "interpreter/oopMapCache.hpp"
  42 #include "jvm.h"
  43 #include "logging/log.hpp"
  44 #include "logging/logLevel.hpp"
  45 #include "logging/logMessage.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/allocation.inline.hpp"
  48 #include "memory/oopFactory.hpp"
  49 #include "memory/resourceArea.hpp"
  50 #include "memory/universe.hpp"
  51 #include "oops/constantPool.hpp"
  52 #include "oops/fieldStreams.inline.hpp"



  53 #include "oops/method.hpp"
  54 #include "oops/objArrayKlass.hpp"
  55 #include "oops/objArrayOop.inline.hpp"
  56 #include "oops/oop.inline.hpp"
  57 #include "oops/typeArrayOop.inline.hpp"
  58 #include "oops/verifyOopClosure.hpp"
  59 #include "prims/jvmtiDeferredUpdates.hpp"
  60 #include "prims/jvmtiExport.hpp"
  61 #include "prims/jvmtiThreadState.hpp"
  62 #include "prims/methodHandles.hpp"
  63 #include "prims/vectorSupport.hpp"
  64 #include "runtime/atomicAccess.hpp"
  65 #include "runtime/basicLock.inline.hpp"
  66 #include "runtime/continuation.hpp"
  67 #include "runtime/continuationEntry.inline.hpp"
  68 #include "runtime/deoptimization.hpp"
  69 #include "runtime/escapeBarrier.hpp"
  70 #include "runtime/fieldDescriptor.inline.hpp"
  71 #include "runtime/frame.inline.hpp"
  72 #include "runtime/handles.inline.hpp"

 281 // The actual reallocation of previously eliminated objects occurs in realloc_objects,
 282 // which is called from the method fetch_unroll_info_helper below.
 283 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* current, int exec_mode))
 284   // fetch_unroll_info() is called at the beginning of the deoptimization
 285   // handler. Note this fact before we start generating temporary frames
 286   // that can confuse an asynchronous stack walker. This counter is
 287   // decremented at the end of unpack_frames().
 288   current->inc_in_deopt_handler();
 289 
 290   if (exec_mode == Unpack_exception) {
 291     // When we get here, a callee has thrown an exception into a deoptimized
 292     // frame. That throw might have deferred stack watermark checking until
 293     // after unwinding. So we deal with such deferred requests here.
 294     StackWatermarkSet::after_unwind(current);
 295   }
 296 
 297   return fetch_unroll_info_helper(current, exec_mode);
 298 JRT_END
 299 
 300 #if COMPILER2_OR_JVMCI


















 301 // print information about reallocated objects
 302 static void print_objects(JavaThread* deoptee_thread,
 303                           GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
 304   ResourceMark rm;
 305   stringStream st;  // change to logStream with logging
 306   st.print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(deoptee_thread));
 307   fieldDescriptor fd;
 308 
 309   for (int i = 0; i < objects->length(); i++) {
 310     ObjectValue* sv = (ObjectValue*) objects->at(i);
 311     Handle obj = sv->value();
 312 
 313     if (obj.is_null()) {
 314       st.print_cr("     nullptr");
 315       continue;
 316     }
 317 
 318     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());

 319 
 320     st.print("     object <" INTPTR_FORMAT "> of type ", p2i(sv->value()()));
 321     k->print_value_on(&st);
 322     st.print_cr(" allocated (%zu bytes)", obj->size() * HeapWordSize);
 323 
 324     if (Verbose && k != nullptr) {
 325       k->oop_print_on(obj(), &st);
 326     }
 327   }
 328   tty->print_raw(st.freeze());
 329 }
 330 
 331 static bool rematerialize_objects(JavaThread* thread, int exec_mode, nmethod* compiled_method,
 332                                   frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk,
 333                                   bool& deoptimized_objects) {
 334   bool realloc_failures = false;
 335   assert (chunk->at(0)->scope() != nullptr,"expect only compiled java frames");
 336 
 337   JavaThread* deoptee_thread = chunk->at(0)->thread();
 338   assert(exec_mode == Deoptimization::Unpack_none || (deoptee_thread == thread),
 339          "a frame can only be deoptimized by the owner thread");
 340 
 341   GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects_to_rematerialize(deoptee, map);
 342 
 343   // The flag return_oop() indicates call sites which return oop
 344   // in compiled code. Such sites include java method calls,
 345   // runtime calls (for example, used to allocate new objects/arrays
 346   // on slow code path) and any other calls generated in compiled code.
 347   // It is not guaranteed that we can get such information here only
 348   // by analyzing bytecode in deoptimized frames. This is why this flag
 349   // is set during method compilation (see Compile::Process_OopMap_Node()).
 350   // If the previous frame was popped or if we are dispatching an exception,
 351   // we don't have an oop result.
 352   bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt);
 353   Handle return_value;











 354   if (save_oop_result) {
 355     // Reallocation may trigger GC. If deoptimization happened on return from
 356     // call which returns oop we need to save it since it is not in oopmap.
 357     oop result = deoptee.saved_oop_result(&map);
 358     assert(oopDesc::is_oop_or_null(result), "must be oop");
 359     return_value = Handle(thread, result);
 360     assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
 361     if (TraceDeoptimization) {
 362       tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread));
 363       tty->cr();
 364     }
 365   }
 366   if (objects != nullptr) {
 367     if (exec_mode == Deoptimization::Unpack_none) {
 368       assert(thread->thread_state() == _thread_in_vm, "assumption");
 369       JavaThread* THREAD = thread; // For exception macros.
 370       // Clear pending OOM if reallocation fails and return true indicating allocation failure
 371       realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, CHECK_AND_CLEAR_(true));








 372       deoptimized_objects = true;
 373     } else {
 374       JavaThread* current = thread; // For JRT_BLOCK
 375       JRT_BLOCK
 376       realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD);








 377       JRT_END
 378     }
 379     guarantee(compiled_method != nullptr, "deopt must be associated with an nmethod");
 380     bool is_jvmci = compiled_method->is_compiled_by_jvmci();
 381     Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, is_jvmci);
 382     if (TraceDeoptimization) {
 383       print_objects(deoptee_thread, objects, realloc_failures);
 384     }
 385   }
 386   if (save_oop_result) {
 387     // Restore result.
 388     deoptee.set_saved_oop_result(&map, return_value());

 389   }
 390   return realloc_failures;
 391 }
 392 
 393 static void restore_eliminated_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures,
 394                                      frame& deoptee, int exec_mode, bool& deoptimized_objects) {
 395   JavaThread* deoptee_thread = chunk->at(0)->thread();
 396   assert(!EscapeBarrier::objs_are_deoptimized(deoptee_thread, deoptee.id()), "must relock just once");
 397   assert(thread == Thread::current(), "should be");
 398   HandleMark hm(thread);
 399 #ifndef PRODUCT
 400   bool first = true;
 401 #endif // !PRODUCT
 402   // Start locking from outermost/oldest frame
 403   for (int i = (chunk->length() - 1); i >= 0; i--) {
 404     compiledVFrame* cvf = chunk->at(i);
 405     assert (cvf->scope() != nullptr,"expect only compiled java frames");
 406     GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
 407     if (monitors->is_nonempty()) {
 408       bool relocked = Deoptimization::relock_objects(thread, monitors, deoptee_thread, deoptee,

 702   // its caller's stack by. If the caller is a compiled frame then
 703   // we pretend that the callee has no parameters so that the
 704   // extension counts for the full amount of locals and not just
 705   // locals-parms. This is because without a c2i adapter the parm
 706   // area as created by the compiled frame will not be usable by
 707   // the interpreter. (Depending on the calling convention there
 708   // may not even be enough space).
 709 
 710   // QQQ I'd rather see this pushed down into last_frame_adjust
 711   // and have it take the sender (aka caller).
 712 
 713   if (!deopt_sender.is_interpreted_frame() || caller_was_method_handle) {
 714     caller_adjustment = last_frame_adjust(0, callee_locals);
 715   } else if (callee_locals > callee_parameters) {
 716     // The caller frame may need extending to accommodate
 717     // non-parameter locals of the first unpacked interpreted frame.
 718     // Compute that adjustment.
 719     caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
 720   }
 721 
 722   // If the sender is deoptimized the we must retrieve the address of the handler
 723   // since the frame will "magically" show the original pc before the deopt
 724   // and we'd undo the deopt.
 725 
 726   frame_pcs[0] = Continuation::is_cont_barrier_frame(deoptee) ? StubRoutines::cont_returnBarrier() : deopt_sender.raw_pc();
 727   if (Continuation::is_continuation_enterSpecial(deopt_sender)) {
 728     ContinuationEntry::from_frame(deopt_sender)->set_argsize(0);
 729   }
 730 
 731   assert(CodeCache::find_blob(frame_pcs[0]) != nullptr, "bad pc");
 732 
 733 #if INCLUDE_JVMCI
 734   if (exceptionObject() != nullptr) {
 735     current->set_exception_oop(exceptionObject());
 736     exec_mode = Unpack_exception;
 737     assert(array->element(0)->rethrow_exception(), "must be");
 738   }
 739 #endif
 740 
 741   if (current->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) {
 742     assert(current->has_pending_exception(), "should have thrown OOME");

1219        case T_LONG:    return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1220        default:;
1221      }
1222    }
1223    return nullptr;
1224 }
1225 #endif // INCLUDE_JVMCI
1226 
1227 #if COMPILER2_OR_JVMCI
1228 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) {
1229   Handle pending_exception(THREAD, thread->pending_exception());
1230   const char* exception_file = thread->exception_file();
1231   int exception_line = thread->exception_line();
1232   thread->clear_pending_exception();
1233 
1234   bool failures = false;
1235 
1236   for (int i = 0; i < objects->length(); i++) {
1237     assert(objects->at(i)->is_object(), "invalid debug information");
1238     ObjectValue* sv = (ObjectValue*) objects->at(i);
1239 
1240     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1241     oop obj = nullptr;









1242 

1243     bool cache_init_error = false;
1244     if (k->is_instance_klass()) {
1245 #if INCLUDE_JVMCI
1246       nmethod* nm = fr->cb()->as_nmethod_or_null();
1247       if (nm->is_compiled_by_jvmci() && sv->is_auto_box()) {
1248         AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv;
1249         obj = get_cached_box(abv, fr, reg_map, cache_init_error, THREAD);
1250         if (obj != nullptr) {
1251           // Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it.
1252           abv->set_cached(true);
1253         } else if (cache_init_error) {
1254           // Results in an OOME which is valid (as opposed to a class initialization error)
1255           // and is fine for the rare case a cache initialization failing.
1256           failures = true;
1257         }
1258       }
1259 #endif // INCLUDE_JVMCI
1260 
1261       InstanceKlass* ik = InstanceKlass::cast(k);
1262       if (obj == nullptr && !cache_init_error) {
1263         InternalOOMEMark iom(THREAD);
1264         if (EnableVectorSupport && VectorSupport::is_vector(ik)) {
1265           obj = VectorSupport::allocate_vector(ik, fr, reg_map, sv, THREAD);
1266         } else {
1267           obj = ik->allocate_instance(THREAD);
1268         }
1269       }




1270     } else if (k->is_typeArray_klass()) {
1271       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1272       assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
1273       int len = sv->field_size() / type2size[ak->element_type()];
1274       InternalOOMEMark iom(THREAD);
1275       obj = ak->allocate_instance(len, THREAD);
1276     } else if (k->is_objArray_klass()) {
1277       ObjArrayKlass* ak = ObjArrayKlass::cast(k);
1278       InternalOOMEMark iom(THREAD);
1279       obj = ak->allocate_instance(sv->field_size(), THREAD);
1280     }
1281 
1282     if (obj == nullptr) {
1283       failures = true;
1284     }
1285 
1286     assert(sv->value().is_null(), "redundant reallocation");
1287     assert(obj != nullptr || HAS_PENDING_EXCEPTION || cache_init_error, "allocation should succeed or we should get an exception");
1288     CLEAR_PENDING_EXCEPTION;
1289     sv->set_value(obj);
1290   }
1291 
1292   if (failures) {
1293     THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
1294   } else if (pending_exception.not_null()) {
1295     thread->set_pending_exception(pending_exception(), exception_file, exception_line);
1296   }
1297 
1298   return failures;
1299 }
1300 















1301 #if INCLUDE_JVMCI
1302 /**
1303  * For primitive types whose kind gets "erased" at runtime (shorts become stack ints),
1304  * we need to somehow be able to recover the actual kind to be able to write the correct
1305  * amount of bytes.
1306  * For that purpose, this method assumes that, for an entry spanning n bytes at index i,
1307  * the entries at index n + 1 to n + i are 'markers'.
1308  * For example, if we were writing a short at index 4 of a byte array of size 8, the
1309  * expected form of the array would be:
1310  *
1311  * {b0, b1, b2, b3, INT, marker, b6, b7}
1312  *
1313  * Thus, in order to get back the size of the entry, we simply need to count the number
1314  * of marked entries
1315  *
1316  * @param virtualArray the virtualized byte array
1317  * @param i index of the virtual entry we are recovering
1318  * @return The number of bytes the entry spans
1319  */
1320 static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) {

1452       default:
1453         ShouldNotReachHere();
1454     }
1455     index++;
1456   }
1457 }
1458 
1459 // restore fields of an eliminated object array
1460 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
1461   for (int i = 0; i < sv->field_size(); i++) {
1462     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1463     assert(value->type() == T_OBJECT, "object element expected");
1464     obj->obj_at_put(i, value->get_obj()());
1465   }
1466 }
1467 
1468 class ReassignedField {
1469 public:
1470   int _offset;
1471   BasicType _type;



1472 public:
1473   ReassignedField() {
1474     _offset = 0;
1475     _type = T_ILLEGAL;
1476   }
1477 };
1478 
1479 // Gets the fields of `klass` that are eliminated by escape analysis and need to be reassigned
1480 static GrowableArray<ReassignedField>* get_reassigned_fields(InstanceKlass* klass, GrowableArray<ReassignedField>* fields, bool is_jvmci) {
1481   InstanceKlass* super = klass->super();
1482   if (super != nullptr) {
1483     get_reassigned_fields(super, fields, is_jvmci);
1484   }
1485   for (AllFieldStream fs(klass); !fs.done(); fs.next()) {
1486     if (!fs.access_flags().is_static() && (is_jvmci || !fs.field_flags().is_injected())) {
1487       ReassignedField field;
1488       field._offset = fs.offset();
1489       field._type = Signature::basic_type(fs.signature());






1490       fields->append(field);
1491     }
1492   }
1493   return fields;
1494 }
1495 
1496 // Restore fields of an eliminated instance object employing the same field order used by the compiler.
1497 static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool is_jvmci) {

1498   GrowableArray<ReassignedField>* fields = get_reassigned_fields(klass, new GrowableArray<ReassignedField>(), is_jvmci);
1499   for (int i = 0; i < fields->length(); i++) {



















1500     ScopeValue* scope_field = sv->field_at(svIndex);
1501     StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1502     int offset = fields->at(i)._offset;
1503     BasicType type = fields->at(i)._type;
1504     switch (type) {
1505       case T_OBJECT: case T_ARRAY:

1506         assert(value->type() == T_OBJECT, "Agreement.");
1507         obj->obj_field_put(offset, value->get_obj()());
1508         break;
1509 
1510       case T_INT: case T_FLOAT: { // 4 bytes.
1511         assert(value->type() == T_INT, "Agreement.");
1512         bool big_value = false;
1513         if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {
1514           if (scope_field->is_location()) {
1515             Location::Type type = ((LocationValue*) scope_field)->location().type();
1516             if (type == Location::dbl || type == Location::lng) {
1517               big_value = true;
1518             }
1519           }
1520           if (scope_field->is_constant_int()) {
1521             ScopeValue* next_scope_field = sv->field_at(svIndex + 1);
1522             if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1523               big_value = true;
1524             }
1525           }

1556       case T_CHAR:
1557         assert(value->type() == T_INT, "Agreement.");
1558         obj->char_field_put(offset, (jchar)value->get_jint());
1559         break;
1560 
1561       case T_BYTE:
1562         assert(value->type() == T_INT, "Agreement.");
1563         obj->byte_field_put(offset, (jbyte)value->get_jint());
1564         break;
1565 
1566       case T_BOOLEAN:
1567         assert(value->type() == T_INT, "Agreement.");
1568         obj->bool_field_put(offset, (jboolean)value->get_jint());
1569         break;
1570 
1571       default:
1572         ShouldNotReachHere();
1573     }
1574     svIndex++;
1575   }

1576   return svIndex;
1577 }
1578 























1579 // restore fields of all eliminated objects and arrays
1580 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool is_jvmci) {
1581   for (int i = 0; i < objects->length(); i++) {
1582     assert(objects->at(i)->is_object(), "invalid debug information");
1583     ObjectValue* sv = (ObjectValue*) objects->at(i);
1584     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());


1585     Handle obj = sv->value();
1586     assert(obj.not_null() || realloc_failures, "reallocation was missed");
1587 #ifndef PRODUCT
1588     if (PrintDeoptimizationDetails) {
1589       tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());
1590     }
1591 #endif // !PRODUCT
1592 
1593     if (obj.is_null()) {
1594       continue;
1595     }
1596 
1597 #if INCLUDE_JVMCI
1598     // Don't reassign fields of boxes that came from a cache. Caches may be in CDS.
1599     if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) {
1600       continue;
1601     }
1602 #endif // INCLUDE_JVMCI
1603     if (EnableVectorSupport && VectorSupport::is_vector(k)) {
1604       assert(sv->field_size() == 1, "%s not a vector", k->name()->as_C_string());
1605       ScopeValue* payload = sv->field_at(0);
1606       if (payload->is_location() &&
1607           payload->as_LocationValue()->location().type() == Location::vector) {
1608 #ifndef PRODUCT
1609         if (PrintDeoptimizationDetails) {
1610           tty->print_cr("skip field reassignment for this vector - it should be assigned already");
1611           if (Verbose) {
1612             Handle obj = sv->value();
1613             k->oop_print_on(obj(), tty);
1614           }
1615         }
1616 #endif // !PRODUCT
1617         continue; // Such vector's value was already restored in VectorSupport::allocate_vector().
1618       }
1619       // Else fall-through to do assignment for scalar-replaced boxed vector representation
1620       // which could be restored after vector object allocation.
1621     }
1622     if (k->is_instance_klass()) {
1623       InstanceKlass* ik = InstanceKlass::cast(k);
1624       reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), is_jvmci);



1625     } else if (k->is_typeArray_klass()) {
1626       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1627       reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
1628     } else if (k->is_objArray_klass()) {
1629       reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
1630     }
1631   }
1632   // These objects may escape when we return to Interpreter after deoptimization.
1633   // We need barrier so that stores that initialize these objects can't be reordered
1634   // with subsequent stores that make these objects accessible by other threads.
1635   OrderAccess::storestore();
1636 }
1637 
1638 
1639 // relock objects for which synchronization was eliminated
1640 bool Deoptimization::relock_objects(JavaThread* thread, GrowableArray<MonitorInfo*>* monitors,
1641                                     JavaThread* deoptee_thread, frame& fr, int exec_mode, bool realloc_failures) {
1642   bool relocked_objects = false;
1643   for (int i = 0; i < monitors->length(); i++) {
1644     MonitorInfo* mon_info = monitors->at(i);
1645     if (mon_info->eliminated()) {
1646       assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
1647       relocked_objects = true;
1648       if (!mon_info->owner_is_scalar_replaced()) {

1786     xtty->begin_head("deoptimized thread='%zu' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));
1787     nm->log_identity(xtty);
1788     xtty->end_head();
1789     for (ScopeDesc* sd = nm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1790       xtty->begin_elem("jvms bci='%d'", sd->bci());
1791       xtty->method(sd->method());
1792       xtty->end_elem();
1793       if (sd->is_top())  break;
1794     }
1795     xtty->tail("deoptimized");
1796   }
1797 
1798   Continuation::notify_deopt(thread, fr.sp());
1799 
1800   // Patch the compiled method so that when execution returns to it we will
1801   // deopt the execution state and return to the interpreter.
1802   fr.deoptimize(thread);
1803 }
1804 
1805 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) {
1806   // Deoptimize only if the frame comes from compile code.
1807   // Do not deoptimize the frame which is already patched
1808   // during the execution of the loops below.
1809   if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1810     return;
1811   }
1812   ResourceMark rm;
1813   deoptimize_single_frame(thread, fr, reason);
1814 }
1815 
1816 address Deoptimization::deoptimize_for_missing_exception_handler(nmethod* nm, bool make_not_entrant) {
1817   // there is no exception handler for this pc => deoptimize
1818   if (make_not_entrant) {
1819     nm->make_not_entrant(nmethod::InvalidationReason::MISSING_EXCEPTION_HANDLER);
1820   }
1821 
1822   // Use Deoptimization::deoptimize for all of its side-effects:
1823   // gathering traps statistics, logging...
1824   // it also patches the return pc but we do not care about that
1825   // since we return a continuation to the deopt_blob below.
1826   JavaThread* thread = JavaThread::current();

  33 #include "code/scopeDesc.hpp"
  34 #include "compiler/compilationPolicy.hpp"
  35 #include "compiler/compilerDefinitions.inline.hpp"
  36 #include "gc/shared/collectedHeap.hpp"
  37 #include "gc/shared/memAllocator.hpp"
  38 #include "interpreter/bytecode.inline.hpp"
  39 #include "interpreter/bytecodeStream.hpp"
  40 #include "interpreter/interpreter.hpp"
  41 #include "interpreter/oopMapCache.hpp"
  42 #include "jvm.h"
  43 #include "logging/log.hpp"
  44 #include "logging/logLevel.hpp"
  45 #include "logging/logMessage.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/allocation.inline.hpp"
  48 #include "memory/oopFactory.hpp"
  49 #include "memory/resourceArea.hpp"
  50 #include "memory/universe.hpp"
  51 #include "oops/constantPool.hpp"
  52 #include "oops/fieldStreams.inline.hpp"
  53 #include "oops/flatArrayKlass.hpp"
  54 #include "oops/flatArrayOop.hpp"
  55 #include "oops/inlineKlass.inline.hpp"
  56 #include "oops/method.hpp"
  57 #include "oops/objArrayKlass.hpp"
  58 #include "oops/objArrayOop.inline.hpp"
  59 #include "oops/oop.inline.hpp"
  60 #include "oops/typeArrayOop.inline.hpp"
  61 #include "oops/verifyOopClosure.hpp"
  62 #include "prims/jvmtiDeferredUpdates.hpp"
  63 #include "prims/jvmtiExport.hpp"
  64 #include "prims/jvmtiThreadState.hpp"
  65 #include "prims/methodHandles.hpp"
  66 #include "prims/vectorSupport.hpp"
  67 #include "runtime/atomicAccess.hpp"
  68 #include "runtime/basicLock.inline.hpp"
  69 #include "runtime/continuation.hpp"
  70 #include "runtime/continuationEntry.inline.hpp"
  71 #include "runtime/deoptimization.hpp"
  72 #include "runtime/escapeBarrier.hpp"
  73 #include "runtime/fieldDescriptor.inline.hpp"
  74 #include "runtime/frame.inline.hpp"
  75 #include "runtime/handles.inline.hpp"

 284 // The actual reallocation of previously eliminated objects occurs in realloc_objects,
 285 // which is called from the method fetch_unroll_info_helper below.
 286 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* current, int exec_mode))
 287   // fetch_unroll_info() is called at the beginning of the deoptimization
 288   // handler. Note this fact before we start generating temporary frames
 289   // that can confuse an asynchronous stack walker. This counter is
 290   // decremented at the end of unpack_frames().
 291   current->inc_in_deopt_handler();
 292 
 293   if (exec_mode == Unpack_exception) {
 294     // When we get here, a callee has thrown an exception into a deoptimized
 295     // frame. That throw might have deferred stack watermark checking until
 296     // after unwinding. So we deal with such deferred requests here.
 297     StackWatermarkSet::after_unwind(current);
 298   }
 299 
 300   return fetch_unroll_info_helper(current, exec_mode);
 301 JRT_END
 302 
 303 #if COMPILER2_OR_JVMCI
 304 
 305 static Klass* get_refined_array_klass(Klass* k, frame* fr, RegisterMap* map, ObjectValue* sv, TRAPS) {
 306   // If it's an array, get the properties
 307   if (k->is_array_klass() && !k->is_typeArray_klass()) {
 308     assert(!k->is_refArray_klass() && !k->is_flatArray_klass(), "Unexpected refined klass");
 309     nmethod* nm = fr->cb()->as_nmethod_or_null();
 310     if (nm->is_compiled_by_c2()) {
 311       assert(sv->has_properties(), "Property information is missing");
 312       ArrayKlass::ArrayProperties props = static_cast<ArrayKlass::ArrayProperties>(StackValue::create_stack_value(fr, map, sv->properties())->get_jint());
 313       k = ObjArrayKlass::cast(k)->klass_with_properties(props, THREAD);
 314     } else {
 315       // TODO Graal needs to be fixed. Just go with the default properties for now
 316       k = ObjArrayKlass::cast(k)->klass_with_properties(ArrayKlass::ArrayProperties::DEFAULT, THREAD);
 317     }
 318   }
 319   return k;
 320 }
 321 
 322 // print information about reallocated objects
 323 static void print_objects(JavaThread* deoptee_thread, frame* deoptee, RegisterMap* map,
 324                           GrowableArray<ScopeValue*>* objects, bool realloc_failures, TRAPS) {
 325   ResourceMark rm;
 326   stringStream st;  // change to logStream with logging
 327   st.print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(deoptee_thread));
 328   fieldDescriptor fd;
 329 
 330   for (int i = 0; i < objects->length(); i++) {
 331     ObjectValue* sv = (ObjectValue*) objects->at(i);
 332     Handle obj = sv->value();
 333 
 334     if (obj.is_null()) {
 335       st.print_cr("     nullptr");
 336       continue;
 337     }
 338 
 339     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
 340     k = get_refined_array_klass(k, deoptee, map, sv, THREAD);
 341 
 342     st.print("     object <" INTPTR_FORMAT "> of type ", p2i(sv->value()()));
 343     k->print_value_on(&st);
 344     st.print_cr(" allocated (%zu bytes)", obj->size() * HeapWordSize);
 345 
 346     if (Verbose && k != nullptr) {
 347       k->oop_print_on(obj(), &st);
 348     }
 349   }
 350   tty->print_raw(st.freeze());
 351 }
 352 
 353 static bool rematerialize_objects(JavaThread* thread, int exec_mode, nmethod* compiled_method,
 354                                   frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk,
 355                                   bool& deoptimized_objects) {
 356   bool realloc_failures = false;
 357   assert (chunk->at(0)->scope() != nullptr,"expect only compiled java frames");
 358 
 359   JavaThread* deoptee_thread = chunk->at(0)->thread();
 360   assert(exec_mode == Deoptimization::Unpack_none || (deoptee_thread == thread),
 361          "a frame can only be deoptimized by the owner thread");
 362 
 363   GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects_to_rematerialize(deoptee, map);
 364 
 365   // The flag return_oop() indicates call sites which return oop
 366   // in compiled code. Such sites include java method calls,
 367   // runtime calls (for example, used to allocate new objects/arrays
 368   // on slow code path) and any other calls generated in compiled code.
 369   // It is not guaranteed that we can get such information here only
 370   // by analyzing bytecode in deoptimized frames. This is why this flag
 371   // is set during method compilation (see Compile::Process_OopMap_Node()).
 372   // If the previous frame was popped or if we are dispatching an exception,
 373   // we don't have an oop result.
 374   ScopeDesc* scope = chunk->at(0)->scope();
 375   bool save_oop_result = scope->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt);
 376   // In case of the return of multiple values, we must take care
 377   // of all oop return values.
 378   GrowableArray<Handle> return_oops;
 379   InlineKlass* vk = nullptr;
 380   if (save_oop_result && scope->return_scalarized()) {
 381     vk = InlineKlass::returned_inline_klass(map);
 382     if (vk != nullptr) {
 383       vk->save_oop_fields(map, return_oops);
 384       save_oop_result = false;
 385     }
 386   }
 387   if (save_oop_result) {
 388     // Reallocation may trigger GC. If deoptimization happened on return from
 389     // call which returns oop we need to save it since it is not in oopmap.
 390     oop result = deoptee.saved_oop_result(&map);
 391     assert(oopDesc::is_oop_or_null(result), "must be oop");
 392     return_oops.push(Handle(thread, result));
 393     assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
 394     if (TraceDeoptimization) {
 395       tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread));
 396       tty->cr();
 397     }
 398   }
 399   if (objects != nullptr || vk != nullptr) {
 400     if (exec_mode == Deoptimization::Unpack_none) {
 401       assert(thread->thread_state() == _thread_in_vm, "assumption");
 402       JavaThread* THREAD = thread; // For exception macros.
 403       // Clear pending OOM if reallocation fails and return true indicating allocation failure
 404       if (vk != nullptr) {
 405         realloc_failures = Deoptimization::realloc_inline_type_result(vk, map, return_oops, CHECK_AND_CLEAR_(true));
 406       }
 407       if (objects != nullptr) {
 408         realloc_failures = realloc_failures || Deoptimization::realloc_objects(thread, &deoptee, &map, objects, CHECK_AND_CLEAR_(true));
 409         guarantee(compiled_method != nullptr, "deopt must be associated with an nmethod");
 410         bool is_jvmci = compiled_method->is_compiled_by_jvmci();
 411         Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, is_jvmci, CHECK_AND_CLEAR_(true));
 412       }
 413       deoptimized_objects = true;
 414     } else {
 415       JavaThread* current = thread; // For JRT_BLOCK
 416       JRT_BLOCK
 417       if (vk != nullptr) {
 418         realloc_failures = Deoptimization::realloc_inline_type_result(vk, map, return_oops, THREAD);
 419       }
 420       if (objects != nullptr) {
 421         realloc_failures = realloc_failures || Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD);
 422         guarantee(compiled_method != nullptr, "deopt must be associated with an nmethod");
 423         bool is_jvmci = compiled_method->is_compiled_by_jvmci();
 424         Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, is_jvmci, THREAD);
 425       }
 426       JRT_END
 427     }
 428     if (TraceDeoptimization && objects != nullptr) {
 429       print_objects(deoptee_thread, &deoptee, &map, objects, realloc_failures, thread);



 430     }
 431   }
 432   if (save_oop_result || vk != nullptr) {
 433     // Restore result.
 434     assert(return_oops.length() == 1, "no inline type");
 435     deoptee.set_saved_oop_result(&map, return_oops.pop()());
 436   }
 437   return realloc_failures;
 438 }
 439 
 440 static void restore_eliminated_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures,
 441                                      frame& deoptee, int exec_mode, bool& deoptimized_objects) {
 442   JavaThread* deoptee_thread = chunk->at(0)->thread();
 443   assert(!EscapeBarrier::objs_are_deoptimized(deoptee_thread, deoptee.id()), "must relock just once");
 444   assert(thread == Thread::current(), "should be");
 445   HandleMark hm(thread);
 446 #ifndef PRODUCT
 447   bool first = true;
 448 #endif // !PRODUCT
 449   // Start locking from outermost/oldest frame
 450   for (int i = (chunk->length() - 1); i >= 0; i--) {
 451     compiledVFrame* cvf = chunk->at(i);
 452     assert (cvf->scope() != nullptr,"expect only compiled java frames");
 453     GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
 454     if (monitors->is_nonempty()) {
 455       bool relocked = Deoptimization::relock_objects(thread, monitors, deoptee_thread, deoptee,

 749   // its caller's stack by. If the caller is a compiled frame then
 750   // we pretend that the callee has no parameters so that the
 751   // extension counts for the full amount of locals and not just
 752   // locals-parms. This is because without a c2i adapter the parm
 753   // area as created by the compiled frame will not be usable by
 754   // the interpreter. (Depending on the calling convention there
 755   // may not even be enough space).
 756 
 757   // QQQ I'd rather see this pushed down into last_frame_adjust
 758   // and have it take the sender (aka caller).
 759 
 760   if (!deopt_sender.is_interpreted_frame() || caller_was_method_handle) {
 761     caller_adjustment = last_frame_adjust(0, callee_locals);
 762   } else if (callee_locals > callee_parameters) {
 763     // The caller frame may need extending to accommodate
 764     // non-parameter locals of the first unpacked interpreted frame.
 765     // Compute that adjustment.
 766     caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
 767   }
 768 
 769   // If the sender is deoptimized we must retrieve the address of the handler
 770   // since the frame will "magically" show the original pc before the deopt
 771   // and we'd undo the deopt.
 772 
 773   frame_pcs[0] = Continuation::is_cont_barrier_frame(deoptee) ? StubRoutines::cont_returnBarrier() : deopt_sender.raw_pc();
 774   if (Continuation::is_continuation_enterSpecial(deopt_sender)) {
 775     ContinuationEntry::from_frame(deopt_sender)->set_argsize(0);
 776   }
 777 
 778   assert(CodeCache::find_blob(frame_pcs[0]) != nullptr, "bad pc");
 779 
 780 #if INCLUDE_JVMCI
 781   if (exceptionObject() != nullptr) {
 782     current->set_exception_oop(exceptionObject());
 783     exec_mode = Unpack_exception;
 784     assert(array->element(0)->rethrow_exception(), "must be");
 785   }
 786 #endif
 787 
 788   if (current->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) {
 789     assert(current->has_pending_exception(), "should have thrown OOME");

1266        case T_LONG:    return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1267        default:;
1268      }
1269    }
1270    return nullptr;
1271 }
1272 #endif // INCLUDE_JVMCI
1273 
1274 #if COMPILER2_OR_JVMCI
1275 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) {
1276   Handle pending_exception(THREAD, thread->pending_exception());
1277   const char* exception_file = thread->exception_file();
1278   int exception_line = thread->exception_line();
1279   thread->clear_pending_exception();
1280 
1281   bool failures = false;
1282 
1283   for (int i = 0; i < objects->length(); i++) {
1284     assert(objects->at(i)->is_object(), "invalid debug information");
1285     ObjectValue* sv = (ObjectValue*) objects->at(i);

1286     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1287     k = get_refined_array_klass(k, fr, reg_map, sv, THREAD);
1288 
1289     // Check if the object may be null and has an additional null_marker input that needs
1290     // to be checked before using the field values. Skip re-allocation if it is null.
1291     if (k->is_inline_klass() && sv->has_properties()) {
1292       jint null_marker = StackValue::create_stack_value(fr, reg_map, sv->properties())->get_jint();
1293       if (null_marker == 0) {
1294         continue;
1295       }
1296     }
1297 
1298     oop obj = nullptr;
1299     bool cache_init_error = false;
1300     if (k->is_instance_klass()) {
1301 #if INCLUDE_JVMCI
1302       nmethod* nm = fr->cb()->as_nmethod_or_null();
1303       if (nm->is_compiled_by_jvmci() && sv->is_auto_box()) {
1304         AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv;
1305         obj = get_cached_box(abv, fr, reg_map, cache_init_error, THREAD);
1306         if (obj != nullptr) {
1307           // Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it.
1308           abv->set_cached(true);
1309         } else if (cache_init_error) {
1310           // Results in an OOME which is valid (as opposed to a class initialization error)
1311           // and is fine for the rare case a cache initialization failing.
1312           failures = true;
1313         }
1314       }
1315 #endif // INCLUDE_JVMCI
1316 
1317       InstanceKlass* ik = InstanceKlass::cast(k);
1318       if (obj == nullptr && !cache_init_error) {
1319         InternalOOMEMark iom(THREAD);
1320         if (EnableVectorSupport && VectorSupport::is_vector(ik)) {
1321           obj = VectorSupport::allocate_vector(ik, fr, reg_map, sv, THREAD);
1322         } else {
1323           obj = ik->allocate_instance(THREAD);
1324         }
1325       }
1326     } else if (k->is_flatArray_klass()) {
1327       FlatArrayKlass* ak = FlatArrayKlass::cast(k);
1328       // Inline type array must be zeroed because not all memory is reassigned
1329       obj = ak->allocate_instance(sv->field_size(), ak->properties(), THREAD);
1330     } else if (k->is_typeArray_klass()) {
1331       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1332       assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
1333       int len = sv->field_size() / type2size[ak->element_type()];
1334       InternalOOMEMark iom(THREAD);
1335       obj = ak->allocate_instance(len, THREAD);
1336     } else if (k->is_refArray_klass()) {
1337       RefArrayKlass* ak = RefArrayKlass::cast(k);
1338       InternalOOMEMark iom(THREAD);
1339       obj = ak->allocate_instance(sv->field_size(), ak->properties(), THREAD);
1340     }
1341 
1342     if (obj == nullptr) {
1343       failures = true;
1344     }
1345 
1346     assert(sv->value().is_null(), "redundant reallocation");
1347     assert(obj != nullptr || HAS_PENDING_EXCEPTION || cache_init_error, "allocation should succeed or we should get an exception");
1348     CLEAR_PENDING_EXCEPTION;
1349     sv->set_value(obj);
1350   }
1351 
1352   if (failures) {
1353     THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
1354   } else if (pending_exception.not_null()) {
1355     thread->set_pending_exception(pending_exception(), exception_file, exception_line);
1356   }
1357 
1358   return failures;
1359 }
1360 
1361 // We're deoptimizing at the return of a call, inline type fields are
1362 // in registers. When we go back to the interpreter, it will expect a
1363 // reference to an inline type instance. Allocate and initialize it from
1364 // the register values here.
1365 bool Deoptimization::realloc_inline_type_result(InlineKlass* vk, const RegisterMap& map, GrowableArray<Handle>& return_oops, TRAPS) {
1366   oop new_vt = vk->realloc_result(map, return_oops, THREAD);
1367   if (new_vt == nullptr) {
1368     CLEAR_PENDING_EXCEPTION;
1369     THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), true);
1370   }
1371   return_oops.clear();
1372   return_oops.push(Handle(THREAD, new_vt));
1373   return false;
1374 }
1375 
1376 #if INCLUDE_JVMCI
1377 /**
1378  * For primitive types whose kind gets "erased" at runtime (shorts become stack ints),
1379  * we need to somehow be able to recover the actual kind to be able to write the correct
1380  * amount of bytes.
1381  * For that purpose, this method assumes that, for an entry spanning n bytes at index i,
1382  * the entries at index n + 1 to n + i are 'markers'.
1383  * For example, if we were writing a short at index 4 of a byte array of size 8, the
1384  * expected form of the array would be:
1385  *
1386  * {b0, b1, b2, b3, INT, marker, b6, b7}
1387  *
1388  * Thus, in order to get back the size of the entry, we simply need to count the number
1389  * of marked entries
1390  *
1391  * @param virtualArray the virtualized byte array
1392  * @param i index of the virtual entry we are recovering
1393  * @return The number of bytes the entry spans
1394  */
1395 static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) {

1527       default:
1528         ShouldNotReachHere();
1529     }
1530     index++;
1531   }
1532 }
1533 
1534 // restore fields of an eliminated object array
1535 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
1536   for (int i = 0; i < sv->field_size(); i++) {
1537     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1538     assert(value->type() == T_OBJECT, "object element expected");
1539     obj->obj_at_put(i, value->get_obj()());
1540   }
1541 }
1542 
1543 class ReassignedField {
1544 public:
1545   int _offset;
1546   BasicType _type;
1547   InstanceKlass* _klass;
1548   bool _is_flat;
1549   bool _is_null_free;
1550 public:
1551   ReassignedField() : _offset(0), _type(T_ILLEGAL), _klass(nullptr), _is_flat(false), _is_null_free(false) { }



1552 };
1553 
1554 // Gets the fields of `klass` that are eliminated by escape analysis and need to be reassigned
1555 static GrowableArray<ReassignedField>* get_reassigned_fields(InstanceKlass* klass, GrowableArray<ReassignedField>* fields, bool is_jvmci) {
1556   InstanceKlass* super = klass->super();
1557   if (super != nullptr) {
1558     get_reassigned_fields(super, fields, is_jvmci);
1559   }
1560   for (AllFieldStream fs(klass); !fs.done(); fs.next()) {
1561     if (!fs.access_flags().is_static() && (is_jvmci || !fs.field_flags().is_injected())) {
1562       ReassignedField field;
1563       field._offset = fs.offset();
1564       field._type = Signature::basic_type(fs.signature());
1565       if (fs.is_flat()) {
1566         field._is_flat = true;
1567         field._is_null_free = fs.is_null_free_inline_type();
1568         // Resolve klass of flat inline type field
1569         field._klass = InlineKlass::cast(klass->get_inline_type_field_klass(fs.index()));
1570       }
1571       fields->append(field);
1572     }
1573   }
1574   return fields;
1575 }
1576 
1577 // Restore fields of an eliminated instance object employing the same field order used by the
1578 // compiler when it scalarizes an object at safepoints.
1579 static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool is_jvmci, int base_offset, TRAPS) {
1580   GrowableArray<ReassignedField>* fields = get_reassigned_fields(klass, new GrowableArray<ReassignedField>(), is_jvmci);
1581   for (int i = 0; i < fields->length(); i++) {
1582     BasicType type = fields->at(i)._type;
1583     int offset = base_offset + fields->at(i)._offset;
1584     // Check for flat inline type field before accessing the ScopeValue because it might not have any fields
1585     if (fields->at(i)._is_flat) {
1586       // Recursively re-assign flat inline type fields
1587       InstanceKlass* vk = fields->at(i)._klass;
1588       assert(vk != nullptr, "must be resolved");
1589       offset -= InlineKlass::cast(vk)->payload_offset(); // Adjust offset to omit oop header
1590       svIndex = reassign_fields_by_klass(vk, fr, reg_map, sv, svIndex, obj, is_jvmci, offset, CHECK_0);
1591       if (!fields->at(i)._is_null_free) {
1592         ScopeValue* scope_field = sv->field_at(svIndex);
1593         StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1594         int nm_offset = offset + InlineKlass::cast(vk)->null_marker_offset();
1595         obj->bool_field_put(nm_offset, value->get_jint() & 1);
1596         svIndex++;
1597       }
1598       continue; // Continue because we don't need to increment svIndex
1599     }
1600 
1601     ScopeValue* scope_field = sv->field_at(svIndex);
1602     StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);


1603     switch (type) {
1604       case T_OBJECT:
1605       case T_ARRAY:
1606         assert(value->type() == T_OBJECT, "Agreement.");
1607         obj->obj_field_put(offset, value->get_obj()());
1608         break;
1609 
1610       case T_INT: case T_FLOAT: { // 4 bytes.
1611         assert(value->type() == T_INT, "Agreement.");
1612         bool big_value = false;
1613         if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {
1614           if (scope_field->is_location()) {
1615             Location::Type type = ((LocationValue*) scope_field)->location().type();
1616             if (type == Location::dbl || type == Location::lng) {
1617               big_value = true;
1618             }
1619           }
1620           if (scope_field->is_constant_int()) {
1621             ScopeValue* next_scope_field = sv->field_at(svIndex + 1);
1622             if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1623               big_value = true;
1624             }
1625           }

1656       case T_CHAR:
1657         assert(value->type() == T_INT, "Agreement.");
1658         obj->char_field_put(offset, (jchar)value->get_jint());
1659         break;
1660 
1661       case T_BYTE:
1662         assert(value->type() == T_INT, "Agreement.");
1663         obj->byte_field_put(offset, (jbyte)value->get_jint());
1664         break;
1665 
1666       case T_BOOLEAN:
1667         assert(value->type() == T_INT, "Agreement.");
1668         obj->bool_field_put(offset, (jboolean)value->get_jint());
1669         break;
1670 
1671       default:
1672         ShouldNotReachHere();
1673     }
1674     svIndex++;
1675   }
1676 
1677   return svIndex;
1678 }
1679 
1680 // restore fields of an eliminated inline type array
1681 void Deoptimization::reassign_flat_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, flatArrayOop obj, FlatArrayKlass* vak, bool is_jvmci, TRAPS) {
1682   InlineKlass* vk = vak->element_klass();
1683   assert(vk->maybe_flat_in_array(), "should only be used for flat inline type arrays");
1684   // Adjust offset to omit oop header
1685   int base_offset = arrayOopDesc::base_offset_in_bytes(T_FLAT_ELEMENT) - vk->payload_offset();
1686   // Initialize all elements of the flat inline type array
1687   for (int i = 0; i < sv->field_size(); i++) {
1688     ObjectValue* val = sv->field_at(i)->as_ObjectValue();
1689     int offset = base_offset + (i << Klass::layout_helper_log2_element_size(vak->layout_helper()));
1690     reassign_fields_by_klass(vk, fr, reg_map, val, 0, (oop)obj, is_jvmci, offset, CHECK);
1691     if (!obj->is_null_free_array()) {
1692       jboolean null_marker_value;
1693       if (val->has_properties()) {
1694         null_marker_value = StackValue::create_stack_value(fr, reg_map, val->properties())->get_jint() & 1;
1695       } else {
1696         null_marker_value = 1;
1697       }
1698       obj->bool_field_put(offset + vk->null_marker_offset(), null_marker_value);
1699     }
1700   }
1701 }
1702 
1703 // restore fields of all eliminated objects and arrays
1704 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool is_jvmci, TRAPS) {
1705   for (int i = 0; i < objects->length(); i++) {
1706     assert(objects->at(i)->is_object(), "invalid debug information");
1707     ObjectValue* sv = (ObjectValue*) objects->at(i);
1708     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1709     k = get_refined_array_klass(k, fr, reg_map, sv, THREAD);
1710 
1711     Handle obj = sv->value();
1712     assert(obj.not_null() || realloc_failures || sv->has_properties(), "reallocation was missed");
1713 #ifndef PRODUCT
1714     if (PrintDeoptimizationDetails) {
1715       tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());
1716     }
1717 #endif // !PRODUCT
1718 
1719     if (obj.is_null()) {
1720       continue;
1721     }
1722 
1723 #if INCLUDE_JVMCI
1724     // Don't reassign fields of boxes that came from a cache. Caches may be in CDS.
1725     if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) {
1726       continue;
1727     }
1728 #endif // INCLUDE_JVMCI
1729     if (EnableVectorSupport && VectorSupport::is_vector(k)) {
1730       assert(sv->field_size() == 1, "%s not a vector", k->name()->as_C_string());
1731       ScopeValue* payload = sv->field_at(0);
1732       if (payload->is_location() &&
1733           payload->as_LocationValue()->location().type() == Location::vector) {
1734 #ifndef PRODUCT
1735         if (PrintDeoptimizationDetails) {
1736           tty->print_cr("skip field reassignment for this vector - it should be assigned already");
1737           if (Verbose) {
1738             Handle obj = sv->value();
1739             k->oop_print_on(obj(), tty);
1740           }
1741         }
1742 #endif // !PRODUCT
1743         continue; // Such vector's value was already restored in VectorSupport::allocate_vector().
1744       }
1745       // Else fall-through to do assignment for scalar-replaced boxed vector representation
1746       // which could be restored after vector object allocation.
1747     }
1748     if (k->is_instance_klass()) {
1749       InstanceKlass* ik = InstanceKlass::cast(k);
1750       reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), is_jvmci, 0, CHECK);
1751     } else if (k->is_flatArray_klass()) {
1752       FlatArrayKlass* vak = FlatArrayKlass::cast(k);
1753       reassign_flat_array_elements(fr, reg_map, sv, (flatArrayOop) obj(), vak, is_jvmci, CHECK);
1754     } else if (k->is_typeArray_klass()) {
1755       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1756       reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
1757     } else if (k->is_refArray_klass()) {
1758       reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
1759     }
1760   }
1761   // These objects may escape when we return to Interpreter after deoptimization.
1762   // We need barrier so that stores that initialize these objects can't be reordered
1763   // with subsequent stores that make these objects accessible by other threads.
1764   OrderAccess::storestore();
1765 }
1766 
1767 
1768 // relock objects for which synchronization was eliminated
1769 bool Deoptimization::relock_objects(JavaThread* thread, GrowableArray<MonitorInfo*>* monitors,
1770                                     JavaThread* deoptee_thread, frame& fr, int exec_mode, bool realloc_failures) {
1771   bool relocked_objects = false;
1772   for (int i = 0; i < monitors->length(); i++) {
1773     MonitorInfo* mon_info = monitors->at(i);
1774     if (mon_info->eliminated()) {
1775       assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
1776       relocked_objects = true;
1777       if (!mon_info->owner_is_scalar_replaced()) {

1915     xtty->begin_head("deoptimized thread='%zu' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));
1916     nm->log_identity(xtty);
1917     xtty->end_head();
1918     for (ScopeDesc* sd = nm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1919       xtty->begin_elem("jvms bci='%d'", sd->bci());
1920       xtty->method(sd->method());
1921       xtty->end_elem();
1922       if (sd->is_top())  break;
1923     }
1924     xtty->tail("deoptimized");
1925   }
1926 
1927   Continuation::notify_deopt(thread, fr.sp());
1928 
1929   // Patch the compiled method so that when execution returns to it we will
1930   // deopt the execution state and return to the interpreter.
1931   fr.deoptimize(thread);
1932 }
1933 
1934 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) {
1935   // Deoptimize only if the frame comes from compiled code.
1936   // Do not deoptimize the frame which is already patched
1937   // during the execution of the loops below.
1938   if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1939     return;
1940   }
1941   ResourceMark rm;
1942   deoptimize_single_frame(thread, fr, reason);
1943 }
1944 
1945 address Deoptimization::deoptimize_for_missing_exception_handler(nmethod* nm, bool make_not_entrant) {
1946   // there is no exception handler for this pc => deoptimize
1947   if (make_not_entrant) {
1948     nm->make_not_entrant(nmethod::InvalidationReason::MISSING_EXCEPTION_HANDLER);
1949   }
1950 
1951   // Use Deoptimization::deoptimize for all of its side-effects:
1952   // gathering traps statistics, logging...
1953   // it also patches the return pc but we do not care about that
1954   // since we return a continuation to the deopt_blob below.
1955   JavaThread* thread = JavaThread::current();
< prev index next >