1 /*
   2  * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "classfile/javaClasses.inline.hpp"
  26 #include "classfile/symbolTable.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmClasses.hpp"
  29 #include "code/codeCache.hpp"
  30 #include "code/debugInfoRec.hpp"
  31 #include "code/nmethod.hpp"
  32 #include "code/pcDesc.hpp"
  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.hpp"
  39 #include "interpreter/bytecode.inline.hpp"
  40 #include "interpreter/bytecodeStream.hpp"
  41 #include "interpreter/interpreter.hpp"
  42 #include "interpreter/oopMapCache.hpp"
  43 #include "jvm.h"
  44 #include "logging/log.hpp"
  45 #include "logging/logLevel.hpp"
  46 #include "logging/logMessage.hpp"
  47 #include "logging/logStream.hpp"
  48 #include "memory/allocation.inline.hpp"
  49 #include "memory/oopFactory.hpp"
  50 #include "memory/resourceArea.hpp"
  51 #include "memory/universe.hpp"
  52 #include "oops/constantPool.hpp"
  53 #include "oops/flatArrayKlass.hpp"
  54 #include "oops/flatArrayOop.hpp"
  55 #include "oops/fieldStreams.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/inlineKlass.inline.hpp"
  61 #include "oops/typeArrayOop.inline.hpp"
  62 #include "oops/verifyOopClosure.hpp"
  63 #include "prims/jvmtiDeferredUpdates.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "prims/methodHandles.hpp"
  67 #include "prims/vectorSupport.hpp"
  68 #include "runtime/atomic.hpp"
  69 #include "runtime/basicLock.inline.hpp"
  70 #include "runtime/continuation.hpp"
  71 #include "runtime/continuationEntry.inline.hpp"
  72 #include "runtime/deoptimization.hpp"
  73 #include "runtime/escapeBarrier.hpp"
  74 #include "runtime/fieldDescriptor.hpp"
  75 #include "runtime/fieldDescriptor.inline.hpp"
  76 #include "runtime/frame.inline.hpp"
  77 #include "runtime/handles.inline.hpp"
  78 #include "runtime/interfaceSupport.inline.hpp"
  79 #include "runtime/javaThread.hpp"
  80 #include "runtime/jniHandles.inline.hpp"
  81 #include "runtime/keepStackGCProcessed.hpp"
  82 #include "runtime/lightweightSynchronizer.hpp"
  83 #include "runtime/lockStack.inline.hpp"
  84 #include "runtime/objectMonitor.inline.hpp"
  85 #include "runtime/osThread.hpp"
  86 #include "runtime/safepointVerifiers.hpp"
  87 #include "runtime/sharedRuntime.hpp"
  88 #include "runtime/signature.hpp"
  89 #include "runtime/stackFrameStream.inline.hpp"
  90 #include "runtime/stackValue.hpp"
  91 #include "runtime/stackWatermarkSet.hpp"
  92 #include "runtime/stubRoutines.hpp"
  93 #include "runtime/synchronizer.inline.hpp"
  94 #include "runtime/threadSMR.hpp"
  95 #include "runtime/threadWXSetters.inline.hpp"
  96 #include "runtime/vframe.hpp"
  97 #include "runtime/vframeArray.hpp"
  98 #include "runtime/vframe_hp.hpp"
  99 #include "runtime/vmOperations.hpp"
 100 #include "utilities/checkedCast.hpp"
 101 #include "utilities/events.hpp"
 102 #include "utilities/growableArray.hpp"
 103 #include "utilities/macros.hpp"
 104 #include "utilities/preserveException.hpp"
 105 #include "utilities/xmlstream.hpp"
 106 #if INCLUDE_JFR
 107 #include "jfr/jfr.inline.hpp"
 108 #include "jfr/jfrEvents.hpp"
 109 #include "jfr/metadata/jfrSerializer.hpp"
 110 #endif
 111 
 112 uint64_t DeoptimizationScope::_committed_deopt_gen = 0;
 113 uint64_t DeoptimizationScope::_active_deopt_gen    = 1;
 114 bool     DeoptimizationScope::_committing_in_progress = false;
 115 
 116 DeoptimizationScope::DeoptimizationScope() : _required_gen(0) {
 117   DEBUG_ONLY(_deopted = false;)
 118 
 119   MutexLocker ml(NMethodState_lock, Mutex::_no_safepoint_check_flag);
 120   // If there is nothing to deopt _required_gen is the same as comitted.
 121   _required_gen = DeoptimizationScope::_committed_deopt_gen;
 122 }
 123 
 124 DeoptimizationScope::~DeoptimizationScope() {
 125   assert(_deopted, "Deopt not executed");
 126 }
 127 
 128 void DeoptimizationScope::mark(nmethod* nm, bool inc_recompile_counts) {
 129   if (!nm->can_be_deoptimized()) {
 130     return;
 131   }
 132 
 133   ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
 134 
 135   // If it's already marked but we still need it to be deopted.
 136   if (nm->is_marked_for_deoptimization()) {
 137     dependent(nm);
 138     return;
 139   }
 140 
 141   nmethod::DeoptimizationStatus status =
 142     inc_recompile_counts ? nmethod::deoptimize : nmethod::deoptimize_noupdate;
 143   Atomic::store(&nm->_deoptimization_status, status);
 144 
 145   // Make sure active is not committed
 146   assert(DeoptimizationScope::_committed_deopt_gen < DeoptimizationScope::_active_deopt_gen, "Must be");
 147   assert(nm->_deoptimization_generation == 0, "Is already marked");
 148 
 149   nm->_deoptimization_generation = DeoptimizationScope::_active_deopt_gen;
 150   _required_gen                  = DeoptimizationScope::_active_deopt_gen;
 151 }
 152 
 153 void DeoptimizationScope::dependent(nmethod* nm) {
 154   ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
 155 
 156   // A method marked by someone else may have a _required_gen lower than what we marked with.
 157   // Therefore only store it if it's higher than _required_gen.
 158   if (_required_gen < nm->_deoptimization_generation) {
 159     _required_gen = nm->_deoptimization_generation;
 160   }
 161 }
 162 
 163 void DeoptimizationScope::deoptimize_marked() {
 164   assert(!_deopted, "Already deopted");
 165 
 166   // We are not alive yet.
 167   if (!Universe::is_fully_initialized()) {
 168     DEBUG_ONLY(_deopted = true;)
 169     return;
 170   }
 171 
 172   // Safepoints are a special case, handled here.
 173   if (SafepointSynchronize::is_at_safepoint()) {
 174     DeoptimizationScope::_committed_deopt_gen = DeoptimizationScope::_active_deopt_gen;
 175     DeoptimizationScope::_active_deopt_gen++;
 176     Deoptimization::deoptimize_all_marked();
 177     DEBUG_ONLY(_deopted = true;)
 178     return;
 179   }
 180 
 181   uint64_t comitting = 0;
 182   bool wait = false;
 183   while (true) {
 184     {
 185       ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
 186 
 187       // First we check if we or someone else already deopted the gen we want.
 188       if (DeoptimizationScope::_committed_deopt_gen >= _required_gen) {
 189         DEBUG_ONLY(_deopted = true;)
 190         return;
 191       }
 192       if (!_committing_in_progress) {
 193         // The version we are about to commit.
 194         comitting = DeoptimizationScope::_active_deopt_gen;
 195         // Make sure new marks use a higher gen.
 196         DeoptimizationScope::_active_deopt_gen++;
 197         _committing_in_progress = true;
 198         wait = false;
 199       } else {
 200         // Another thread is handshaking and committing a gen.
 201         wait = true;
 202       }
 203     }
 204     if (wait) {
 205       // Wait and let the concurrent handshake be performed.
 206       ThreadBlockInVM tbivm(JavaThread::current());
 207       os::naked_yield();
 208     } else {
 209       // Performs the handshake.
 210       Deoptimization::deoptimize_all_marked(); // May safepoint and an additional deopt may have occurred.
 211       DEBUG_ONLY(_deopted = true;)
 212       {
 213         ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
 214 
 215         // Make sure that committed doesn't go backwards.
 216         // Should only happen if we did a deopt during a safepoint above.
 217         if (DeoptimizationScope::_committed_deopt_gen < comitting) {
 218           DeoptimizationScope::_committed_deopt_gen = comitting;
 219         }
 220         _committing_in_progress = false;
 221 
 222         assert(DeoptimizationScope::_committed_deopt_gen >= _required_gen, "Must be");
 223 
 224         return;
 225       }
 226     }
 227   }
 228 }
 229 
 230 Deoptimization::UnrollBlock::UnrollBlock(int  size_of_deoptimized_frame,
 231                                          int  caller_adjustment,
 232                                          int  caller_actual_parameters,
 233                                          int  number_of_frames,
 234                                          intptr_t* frame_sizes,
 235                                          address* frame_pcs,
 236                                          BasicType return_type,
 237                                          int exec_mode) {
 238   _size_of_deoptimized_frame = size_of_deoptimized_frame;
 239   _caller_adjustment         = caller_adjustment;
 240   _caller_actual_parameters  = caller_actual_parameters;
 241   _number_of_frames          = number_of_frames;
 242   _frame_sizes               = frame_sizes;
 243   _frame_pcs                 = frame_pcs;
 244   _register_block            = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);
 245   _return_type               = return_type;
 246   _initial_info              = 0;
 247   // PD (x86 only)
 248   _counter_temp              = 0;
 249   _unpack_kind               = exec_mode;
 250   _sender_sp_temp            = 0;
 251 
 252   _total_frame_sizes         = size_of_frames();
 253   assert(exec_mode >= 0 && exec_mode < Unpack_LIMIT, "Unexpected exec_mode");
 254 }
 255 
 256 Deoptimization::UnrollBlock::~UnrollBlock() {
 257   FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes);
 258   FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs);
 259   FREE_C_HEAP_ARRAY(intptr_t, _register_block);
 260 }
 261 
 262 int Deoptimization::UnrollBlock::size_of_frames() const {
 263   // Account first for the adjustment of the initial frame
 264   intptr_t result = _caller_adjustment;
 265   for (int index = 0; index < number_of_frames(); index++) {
 266     result += frame_sizes()[index];
 267   }
 268   return checked_cast<int>(result);
 269 }
 270 
 271 void Deoptimization::UnrollBlock::print() {
 272   ResourceMark rm;
 273   stringStream st;
 274   st.print_cr("UnrollBlock");
 275   st.print_cr("  size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
 276   st.print(   "  frame_sizes: ");
 277   for (int index = 0; index < number_of_frames(); index++) {
 278     st.print("%zd ", frame_sizes()[index]);
 279   }
 280   st.cr();
 281   tty->print_raw(st.freeze());
 282 }
 283 
 284 // In order to make fetch_unroll_info work properly with escape
 285 // analysis, the method was changed from JRT_LEAF to JRT_BLOCK_ENTRY.
 286 // The actual reallocation of previously eliminated objects occurs in realloc_objects,
 287 // which is called from the method fetch_unroll_info_helper below.
 288 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* current, int exec_mode))
 289   // fetch_unroll_info() is called at the beginning of the deoptimization
 290   // handler. Note this fact before we start generating temporary frames
 291   // that can confuse an asynchronous stack walker. This counter is
 292   // decremented at the end of unpack_frames().
 293   current->inc_in_deopt_handler();
 294 
 295   if (exec_mode == Unpack_exception) {
 296     // When we get here, a callee has thrown an exception into a deoptimized
 297     // frame. That throw might have deferred stack watermark checking until
 298     // after unwinding. So we deal with such deferred requests here.
 299     StackWatermarkSet::after_unwind(current);
 300   }
 301 
 302   return fetch_unroll_info_helper(current, exec_mode);
 303 JRT_END
 304 
 305 #if COMPILER2_OR_JVMCI
 306 
 307 static Klass* get_refined_array_klass(Klass* k, frame* fr, RegisterMap* map, ObjectValue* sv, TRAPS) {
 308   // If it's an array, get the properties
 309   if (k->is_array_klass() && !k->is_typeArray_klass()) {
 310     assert(!k->is_refArray_klass() && !k->is_flatArray_klass(), "Unexpected refined klass");
 311     nmethod* nm = fr->cb()->as_nmethod_or_null();
 312     if (nm->is_compiled_by_c2()) {
 313       assert(sv->has_properties(), "Property information is missing");
 314       ArrayKlass::ArrayProperties props = static_cast<ArrayKlass::ArrayProperties>(StackValue::create_stack_value(fr, map, sv->properties())->get_jint());
 315       k = ObjArrayKlass::cast(k)->klass_with_properties(props, THREAD);
 316     } else {
 317       // TODO Graal needs to be fixed. Just go with the default properties for now
 318       k = ObjArrayKlass::cast(k)->klass_with_properties(ArrayKlass::ArrayProperties::DEFAULT, THREAD);
 319     }
 320   }
 321   return k;
 322 }
 323 
 324 // print information about reallocated objects
 325 static void print_objects(JavaThread* deoptee_thread, frame* deoptee, RegisterMap* map,
 326                           GrowableArray<ScopeValue*>* objects, bool realloc_failures, TRAPS) {
 327   ResourceMark rm;
 328   stringStream st;  // change to logStream with logging
 329   st.print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(deoptee_thread));
 330   fieldDescriptor fd;
 331 
 332   for (int i = 0; i < objects->length(); i++) {
 333     ObjectValue* sv = (ObjectValue*) objects->at(i);
 334     Handle obj = sv->value();
 335 
 336     if (obj.is_null()) {
 337       st.print_cr("     nullptr");
 338       continue;
 339     }
 340 
 341     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
 342     k = get_refined_array_klass(k, deoptee, map, sv, THREAD);
 343 
 344     st.print("     object <" INTPTR_FORMAT "> of type ", p2i(sv->value()()));
 345     k->print_value_on(&st);
 346     st.print_cr(" allocated (%zu bytes)", obj->size() * HeapWordSize);
 347 
 348     if (Verbose && k != nullptr) {
 349       k->oop_print_on(obj(), &st);
 350     }
 351   }
 352   tty->print_raw(st.freeze());
 353 }
 354 
 355 static bool rematerialize_objects(JavaThread* thread, int exec_mode, nmethod* compiled_method,
 356                                   frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk,
 357                                   bool& deoptimized_objects) {
 358   bool realloc_failures = false;
 359   assert (chunk->at(0)->scope() != nullptr,"expect only compiled java frames");
 360 
 361   JavaThread* deoptee_thread = chunk->at(0)->thread();
 362   assert(exec_mode == Deoptimization::Unpack_none || (deoptee_thread == thread),
 363          "a frame can only be deoptimized by the owner thread");
 364 
 365   GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects_to_rematerialize(deoptee, map);
 366 
 367   // The flag return_oop() indicates call sites which return oop
 368   // in compiled code. Such sites include java method calls,
 369   // runtime calls (for example, used to allocate new objects/arrays
 370   // on slow code path) and any other calls generated in compiled code.
 371   // It is not guaranteed that we can get such information here only
 372   // by analyzing bytecode in deoptimized frames. This is why this flag
 373   // is set during method compilation (see Compile::Process_OopMap_Node()).
 374   // If the previous frame was popped or if we are dispatching an exception,
 375   // we don't have an oop result.
 376   ScopeDesc* scope = chunk->at(0)->scope();
 377   bool save_oop_result = scope->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt);
 378   // In case of the return of multiple values, we must take care
 379   // of all oop return values.
 380   GrowableArray<Handle> return_oops;
 381   InlineKlass* vk = nullptr;
 382   if (save_oop_result && scope->return_scalarized()) {
 383     vk = InlineKlass::returned_inline_klass(map);
 384     if (vk != nullptr) {
 385       vk->save_oop_fields(map, return_oops);
 386       save_oop_result = false;
 387     }
 388   }
 389   if (save_oop_result) {
 390     // Reallocation may trigger GC. If deoptimization happened on return from
 391     // call which returns oop we need to save it since it is not in oopmap.
 392     oop result = deoptee.saved_oop_result(&map);
 393     assert(oopDesc::is_oop_or_null(result), "must be oop");
 394     return_oops.push(Handle(thread, result));
 395     assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
 396     if (TraceDeoptimization) {
 397       tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread));
 398       tty->cr();
 399     }
 400   }
 401   if (objects != nullptr || vk != nullptr) {
 402     if (exec_mode == Deoptimization::Unpack_none) {
 403       assert(thread->thread_state() == _thread_in_vm, "assumption");
 404       JavaThread* THREAD = thread; // For exception macros.
 405       // Clear pending OOM if reallocation fails and return true indicating allocation failure
 406       if (vk != nullptr) {
 407         realloc_failures = Deoptimization::realloc_inline_type_result(vk, map, return_oops, CHECK_AND_CLEAR_(true));
 408       }
 409       if (objects != nullptr) {
 410         realloc_failures = realloc_failures || Deoptimization::realloc_objects(thread, &deoptee, &map, objects, CHECK_AND_CLEAR_(true));
 411         guarantee(compiled_method != nullptr, "deopt must be associated with an nmethod");
 412         bool is_jvmci = compiled_method->is_compiled_by_jvmci();
 413         Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, is_jvmci, CHECK_AND_CLEAR_(true));
 414       }
 415       deoptimized_objects = true;
 416     } else {
 417       JavaThread* current = thread; // For JRT_BLOCK
 418       JRT_BLOCK
 419       if (vk != nullptr) {
 420         realloc_failures = Deoptimization::realloc_inline_type_result(vk, map, return_oops, THREAD);
 421       }
 422       if (objects != nullptr) {
 423         realloc_failures = realloc_failures || Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD);
 424         guarantee(compiled_method != nullptr, "deopt must be associated with an nmethod");
 425         bool is_jvmci = compiled_method->is_compiled_by_jvmci();
 426         Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, is_jvmci, THREAD);
 427       }
 428       JRT_END
 429     }
 430     if (TraceDeoptimization && objects != nullptr) {
 431       print_objects(deoptee_thread, &deoptee, &map, objects, realloc_failures, thread);
 432     }
 433   }
 434   if (save_oop_result || vk != nullptr) {
 435     // Restore result.
 436     assert(return_oops.length() == 1, "no inline type");
 437     deoptee.set_saved_oop_result(&map, return_oops.pop()());
 438   }
 439   return realloc_failures;
 440 }
 441 
 442 static void restore_eliminated_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures,
 443                                      frame& deoptee, int exec_mode, bool& deoptimized_objects) {
 444   JavaThread* deoptee_thread = chunk->at(0)->thread();
 445   assert(!EscapeBarrier::objs_are_deoptimized(deoptee_thread, deoptee.id()), "must relock just once");
 446   assert(thread == Thread::current(), "should be");
 447   HandleMark hm(thread);
 448 #ifndef PRODUCT
 449   bool first = true;
 450 #endif // !PRODUCT
 451   // Start locking from outermost/oldest frame
 452   for (int i = (chunk->length() - 1); i >= 0; i--) {
 453     compiledVFrame* cvf = chunk->at(i);
 454     assert (cvf->scope() != nullptr,"expect only compiled java frames");
 455     GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
 456     if (monitors->is_nonempty()) {
 457       bool relocked = Deoptimization::relock_objects(thread, monitors, deoptee_thread, deoptee,
 458                                                      exec_mode, realloc_failures);
 459       deoptimized_objects = deoptimized_objects || relocked;
 460 #ifndef PRODUCT
 461       if (PrintDeoptimizationDetails) {
 462         ResourceMark rm;
 463         stringStream st;
 464         for (int j = 0; j < monitors->length(); j++) {
 465           MonitorInfo* mi = monitors->at(j);
 466           if (mi->eliminated()) {
 467             if (first) {
 468               first = false;
 469               st.print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, p2i(thread));
 470             }
 471             if (exec_mode == Deoptimization::Unpack_none) {
 472               ObjectMonitor* monitor = deoptee_thread->current_waiting_monitor();
 473               if (monitor != nullptr && monitor->object() == mi->owner()) {
 474                 st.print_cr("     object <" INTPTR_FORMAT "> DEFERRED relocking after wait", p2i(mi->owner()));
 475                 continue;
 476               }
 477             }
 478             if (mi->owner_is_scalar_replaced()) {
 479               Klass* k = java_lang_Class::as_Klass(mi->owner_klass());
 480               st.print_cr("     failed reallocation for klass %s", k->external_name());
 481             } else {
 482               st.print_cr("     object <" INTPTR_FORMAT "> locked", p2i(mi->owner()));
 483             }
 484           }
 485         }
 486         tty->print_raw(st.freeze());
 487       }
 488 #endif // !PRODUCT
 489     }
 490   }
 491 }
 492 
 493 // Deoptimize objects, that is reallocate and relock them, just before they escape through JVMTI.
 494 // The given vframes cover one physical frame.
 495 bool Deoptimization::deoptimize_objects_internal(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk,
 496                                                  bool& realloc_failures) {
 497   frame deoptee = chunk->at(0)->fr();
 498   JavaThread* deoptee_thread = chunk->at(0)->thread();
 499   nmethod* nm = deoptee.cb()->as_nmethod_or_null();
 500   RegisterMap map(chunk->at(0)->register_map());
 501   bool deoptimized_objects = false;
 502 
 503   bool const jvmci_enabled = JVMCI_ONLY(EnableJVMCI) NOT_JVMCI(false);
 504 
 505   // Reallocate the non-escaping objects and restore their fields.
 506   if (jvmci_enabled COMPILER2_PRESENT(|| (DoEscapeAnalysis && EliminateAllocations)
 507                                       || EliminateAutoBox || EnableVectorAggressiveReboxing)) {
 508     realloc_failures = rematerialize_objects(thread, Unpack_none, nm, deoptee, map, chunk, deoptimized_objects);
 509   }
 510 
 511   // MonitorInfo structures used in eliminate_locks are not GC safe.
 512   NoSafepointVerifier no_safepoint;
 513 
 514   // Now relock objects if synchronization on them was eliminated.
 515   if (jvmci_enabled COMPILER2_PRESENT(|| ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks))) {
 516     restore_eliminated_locks(thread, chunk, realloc_failures, deoptee, Unpack_none, deoptimized_objects);
 517   }
 518   return deoptimized_objects;
 519 }
 520 #endif // COMPILER2_OR_JVMCI
 521 
 522 // This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)
 523 Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* current, int exec_mode) {
 524   JFR_ONLY(Jfr::check_and_process_sample_request(current);)
 525   // When we get here we are about to unwind the deoptee frame. In order to
 526   // catch not yet safe to use frames, the following stack watermark barrier
 527   // poll will make such frames safe to use.
 528   StackWatermarkSet::before_unwind(current);
 529 
 530   // Note: there is a safepoint safety issue here. No matter whether we enter
 531   // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once
 532   // the vframeArray is created.
 533   //
 534 
 535   // Allocate our special deoptimization ResourceMark
 536   DeoptResourceMark* dmark = new DeoptResourceMark(current);
 537   assert(current->deopt_mark() == nullptr, "Pending deopt!");
 538   current->set_deopt_mark(dmark);
 539 
 540   frame stub_frame = current->last_frame(); // Makes stack walkable as side effect
 541   RegisterMap map(current,
 542                   RegisterMap::UpdateMap::include,
 543                   RegisterMap::ProcessFrames::include,
 544                   RegisterMap::WalkContinuation::skip);
 545   RegisterMap dummy_map(current,
 546                         RegisterMap::UpdateMap::skip,
 547                         RegisterMap::ProcessFrames::include,
 548                         RegisterMap::WalkContinuation::skip);
 549   // Now get the deoptee with a valid map
 550   frame deoptee = stub_frame.sender(&map);
 551   // Set the deoptee nmethod
 552   assert(current->deopt_compiled_method() == nullptr, "Pending deopt!");
 553   nmethod* nm = deoptee.cb()->as_nmethod_or_null();
 554   current->set_deopt_compiled_method(nm);
 555 
 556   if (VerifyStack) {
 557     current->validate_frame_layout();
 558   }
 559 
 560   // Create a growable array of VFrames where each VFrame represents an inlined
 561   // Java frame.  This storage is allocated with the usual system arena.
 562   assert(deoptee.is_compiled_frame(), "Wrong frame type");
 563   GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);
 564   vframe* vf = vframe::new_vframe(&deoptee, &map, current);
 565   while (!vf->is_top()) {
 566     assert(vf->is_compiled_frame(), "Wrong frame type");
 567     chunk->push(compiledVFrame::cast(vf));
 568     vf = vf->sender();
 569   }
 570   assert(vf->is_compiled_frame(), "Wrong frame type");
 571   chunk->push(compiledVFrame::cast(vf));
 572 
 573   bool realloc_failures = false;
 574 
 575 #if COMPILER2_OR_JVMCI
 576   bool const jvmci_enabled = JVMCI_ONLY(EnableJVMCI) NOT_JVMCI(false);
 577 
 578   // Reallocate the non-escaping objects and restore their fields. Then
 579   // relock objects if synchronization on them was eliminated.
 580   if (jvmci_enabled COMPILER2_PRESENT( || (DoEscapeAnalysis && EliminateAllocations)
 581                                        || EliminateAutoBox || EnableVectorAggressiveReboxing )) {
 582     bool unused;
 583     realloc_failures = rematerialize_objects(current, exec_mode, nm, deoptee, map, chunk, unused);
 584   }
 585 #endif // COMPILER2_OR_JVMCI
 586 
 587   // Ensure that no safepoint is taken after pointers have been stored
 588   // in fields of rematerialized objects.  If a safepoint occurs from here on
 589   // out the java state residing in the vframeArray will be missed.
 590   // Locks may be rebaised in a safepoint.
 591   NoSafepointVerifier no_safepoint;
 592 
 593 #if COMPILER2_OR_JVMCI
 594   if ((jvmci_enabled COMPILER2_PRESENT( || ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks) ))
 595       && !EscapeBarrier::objs_are_deoptimized(current, deoptee.id())) {
 596     bool unused = false;
 597     restore_eliminated_locks(current, chunk, realloc_failures, deoptee, exec_mode, unused);
 598   }
 599 #endif // COMPILER2_OR_JVMCI
 600 
 601   ScopeDesc* trap_scope = chunk->at(0)->scope();
 602   Handle exceptionObject;
 603   if (trap_scope->rethrow_exception()) {
 604 #ifndef PRODUCT
 605     if (PrintDeoptimizationDetails) {
 606       tty->print_cr("Exception to be rethrown in the interpreter for method %s::%s at bci %d", trap_scope->method()->method_holder()->name()->as_C_string(), trap_scope->method()->name()->as_C_string(), trap_scope->bci());
 607     }
 608 #endif // !PRODUCT
 609 
 610     GrowableArray<ScopeValue*>* expressions = trap_scope->expressions();
 611     guarantee(expressions != nullptr && expressions->length() == 1, "should have only exception on stack");
 612     guarantee(exec_mode != Unpack_exception, "rethrow_exception set with Unpack_exception");
 613     ScopeValue* topOfStack = expressions->top();
 614     exceptionObject = StackValue::create_stack_value(&deoptee, &map, topOfStack)->get_obj();
 615     guarantee(exceptionObject() != nullptr, "exception oop can not be null");
 616   }
 617 
 618   vframeArray* array = create_vframeArray(current, deoptee, &map, chunk, realloc_failures);
 619 #if COMPILER2_OR_JVMCI
 620   if (realloc_failures) {
 621     // This destroys all ScopedValue bindings.
 622     current->clear_scopedValueBindings();
 623     pop_frames_failed_reallocs(current, array);
 624   }
 625 #endif
 626 
 627   assert(current->vframe_array_head() == nullptr, "Pending deopt!");
 628   current->set_vframe_array_head(array);
 629 
 630   // Now that the vframeArray has been created if we have any deferred local writes
 631   // added by jvmti then we can free up that structure as the data is now in the
 632   // vframeArray
 633 
 634   JvmtiDeferredUpdates::delete_updates_for_frame(current, array->original().id());
 635 
 636   // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.
 637   CodeBlob* cb = stub_frame.cb();
 638   // Verify we have the right vframeArray
 639   assert(cb->frame_size() >= 0, "Unexpected frame size");
 640   intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();
 641 
 642   // If the deopt call site is a MethodHandle invoke call site we have
 643   // to adjust the unpack_sp.
 644   nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();
 645   if (deoptee_nm != nullptr && deoptee_nm->is_method_handle_return(deoptee.pc()))
 646     unpack_sp = deoptee.unextended_sp();
 647 
 648 #ifdef ASSERT
 649   assert(cb->is_deoptimization_stub() ||
 650          cb->is_uncommon_trap_stub() ||
 651          strcmp("Stub<DeoptimizationStub.deoptimizationHandler>", cb->name()) == 0 ||
 652          strcmp("Stub<UncommonTrapStub.uncommonTrapHandler>", cb->name()) == 0,
 653          "unexpected code blob: %s", cb->name());
 654 #endif
 655 
 656   // This is a guarantee instead of an assert because if vframe doesn't match
 657   // we will unpack the wrong deoptimized frame and wind up in strange places
 658   // where it will be very difficult to figure out what went wrong. Better
 659   // to die an early death here than some very obscure death later when the
 660   // trail is cold.
 661   guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");
 662 
 663   int number_of_frames = array->frames();
 664 
 665   // Compute the vframes' sizes.  Note that frame_sizes[] entries are ordered from outermost to innermost
 666   // virtual activation, which is the reverse of the elements in the vframes array.
 667   intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);
 668   // +1 because we always have an interpreter return address for the final slot.
 669   address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);
 670   int popframe_extra_args = 0;
 671   // Create an interpreter return address for the stub to use as its return
 672   // address so the skeletal frames are perfectly walkable
 673   frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);
 674 
 675   // PopFrame requires that the preserved incoming arguments from the recently-popped topmost
 676   // activation be put back on the expression stack of the caller for reexecution
 677   if (JvmtiExport::can_pop_frame() && current->popframe_forcing_deopt_reexecution()) {
 678     popframe_extra_args = in_words(current->popframe_preserved_args_size_in_words());
 679   }
 680 
 681   // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized
 682   // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather
 683   // than simply use array->sender.pc(). This requires us to walk the current set of frames
 684   //
 685   frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame
 686   deopt_sender = deopt_sender.sender(&dummy_map);     // Now deoptee caller
 687 
 688   // It's possible that the number of parameters at the call site is
 689   // different than number of arguments in the callee when method
 690   // handles are used.  If the caller is interpreted get the real
 691   // value so that the proper amount of space can be added to it's
 692   // frame.
 693   bool caller_was_method_handle = false;
 694   if (deopt_sender.is_interpreted_frame()) {
 695     methodHandle method(current, deopt_sender.interpreter_frame_method());
 696     Bytecode_invoke cur(method, deopt_sender.interpreter_frame_bci());
 697     if (cur.has_member_arg()) {
 698       // This should cover all real-world cases.  One exception is a pathological chain of
 699       // MH.linkToXXX() linker calls, which only trusted code could do anyway.  To handle that case, we
 700       // would need to get the size from the resolved method entry.  Another exception would
 701       // be an invokedynamic with an adapter that is really a MethodHandle linker.
 702       caller_was_method_handle = true;
 703     }
 704   }
 705 
 706   //
 707   // frame_sizes/frame_pcs[0] oldest frame (int or c2i)
 708   // frame_sizes/frame_pcs[1] next oldest frame (int)
 709   // frame_sizes/frame_pcs[n] youngest frame (int)
 710   //
 711   // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame
 712   // owns the space for the return address to it's caller).  Confusing ain't it.
 713   //
 714   // The vframe array can address vframes with indices running from
 715   // 0.._frames-1. Index  0 is the youngest frame and _frame - 1 is the oldest (root) frame.
 716   // When we create the skeletal frames we need the oldest frame to be in the zero slot
 717   // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.
 718   // so things look a little strange in this loop.
 719   //
 720   int callee_parameters = 0;
 721   int callee_locals = 0;
 722   for (int index = 0; index < array->frames(); index++ ) {
 723     // frame[number_of_frames - 1 ] = on_stack_size(youngest)
 724     // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))
 725     // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))
 726     frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,
 727                                                                                                     callee_locals,
 728                                                                                                     index == 0,
 729                                                                                                     popframe_extra_args);
 730     // This pc doesn't have to be perfect just good enough to identify the frame
 731     // as interpreted so the skeleton frame will be walkable
 732     // The correct pc will be set when the skeleton frame is completely filled out
 733     // The final pc we store in the loop is wrong and will be overwritten below
 734     frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;
 735 
 736     callee_parameters = array->element(index)->method()->size_of_parameters();
 737     callee_locals = array->element(index)->method()->max_locals();
 738     popframe_extra_args = 0;
 739   }
 740 
 741   // Compute whether the root vframe returns a float or double value.
 742   BasicType return_type;
 743   {
 744     methodHandle method(current, array->element(0)->method());
 745     Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());
 746     return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;
 747   }
 748 
 749   // Compute information for handling adapters and adjusting the frame size of the caller.
 750   int caller_adjustment = 0;
 751 
 752   // Compute the amount the oldest interpreter frame will have to adjust
 753   // its caller's stack by. If the caller is a compiled frame then
 754   // we pretend that the callee has no parameters so that the
 755   // extension counts for the full amount of locals and not just
 756   // locals-parms. This is because without a c2i adapter the parm
 757   // area as created by the compiled frame will not be usable by
 758   // the interpreter. (Depending on the calling convention there
 759   // may not even be enough space).
 760 
 761   // QQQ I'd rather see this pushed down into last_frame_adjust
 762   // and have it take the sender (aka caller).
 763 
 764   if (!deopt_sender.is_interpreted_frame() || caller_was_method_handle) {
 765     caller_adjustment = last_frame_adjust(0, callee_locals);
 766   } else if (callee_locals > callee_parameters) {
 767     // The caller frame may need extending to accommodate
 768     // non-parameter locals of the first unpacked interpreted frame.
 769     // Compute that adjustment.
 770     caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
 771   }
 772 
 773   // If the sender is deoptimized we must retrieve the address of the handler
 774   // since the frame will "magically" show the original pc before the deopt
 775   // and we'd undo the deopt.
 776 
 777   frame_pcs[0] = Continuation::is_cont_barrier_frame(deoptee) ? StubRoutines::cont_returnBarrier() : deopt_sender.raw_pc();
 778   if (Continuation::is_continuation_enterSpecial(deopt_sender)) {
 779     ContinuationEntry::from_frame(deopt_sender)->set_argsize(0);
 780   }
 781 
 782   assert(CodeCache::find_blob(frame_pcs[0]) != nullptr, "bad pc");
 783 
 784 #if INCLUDE_JVMCI
 785   if (exceptionObject() != nullptr) {
 786     current->set_exception_oop(exceptionObject());
 787     exec_mode = Unpack_exception;
 788     assert(array->element(0)->rethrow_exception(), "must be");
 789   }
 790 #endif
 791 
 792   if (current->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) {
 793     assert(current->has_pending_exception(), "should have thrown OOME");
 794     current->set_exception_oop(current->pending_exception());
 795     current->clear_pending_exception();
 796     exec_mode = Unpack_exception;
 797   }
 798 
 799 #if INCLUDE_JVMCI
 800   if (current->frames_to_pop_failed_realloc() > 0) {
 801     current->set_pending_monitorenter(false);
 802   }
 803 #endif
 804 
 805   int caller_actual_parameters = -1; // value not used except for interpreted frames, see below
 806   if (deopt_sender.is_interpreted_frame()) {
 807     caller_actual_parameters = callee_parameters + (caller_was_method_handle ? 1 : 0);
 808   }
 809 
 810   UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,
 811                                       caller_adjustment * BytesPerWord,
 812                                       caller_actual_parameters,
 813                                       number_of_frames,
 814                                       frame_sizes,
 815                                       frame_pcs,
 816                                       return_type,
 817                                       exec_mode);
 818   // On some platforms, we need a way to pass some platform dependent
 819   // information to the unpacking code so the skeletal frames come out
 820   // correct (initial fp value, unextended sp, ...)
 821   info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());
 822 
 823   if (array->frames() > 1) {
 824     if (VerifyStack && TraceDeoptimization) {
 825       tty->print_cr("Deoptimizing method containing inlining");
 826     }
 827   }
 828 
 829   array->set_unroll_block(info);
 830   return info;
 831 }
 832 
 833 // Called to cleanup deoptimization data structures in normal case
 834 // after unpacking to stack and when stack overflow error occurs
 835 void Deoptimization::cleanup_deopt_info(JavaThread *thread,
 836                                         vframeArray *array) {
 837 
 838   // Get array if coming from exception
 839   if (array == nullptr) {
 840     array = thread->vframe_array_head();
 841   }
 842   thread->set_vframe_array_head(nullptr);
 843 
 844   // Free the previous UnrollBlock
 845   vframeArray* old_array = thread->vframe_array_last();
 846   thread->set_vframe_array_last(array);
 847 
 848   if (old_array != nullptr) {
 849     UnrollBlock* old_info = old_array->unroll_block();
 850     old_array->set_unroll_block(nullptr);
 851     delete old_info;
 852     delete old_array;
 853   }
 854 
 855   // Deallocate any resource creating in this routine and any ResourceObjs allocated
 856   // inside the vframeArray (StackValueCollections)
 857 
 858   delete thread->deopt_mark();
 859   thread->set_deopt_mark(nullptr);
 860   thread->set_deopt_compiled_method(nullptr);
 861 
 862 
 863   if (JvmtiExport::can_pop_frame()) {
 864     // Regardless of whether we entered this routine with the pending
 865     // popframe condition bit set, we should always clear it now
 866     thread->clear_popframe_condition();
 867   }
 868 
 869   // unpack_frames() is called at the end of the deoptimization handler
 870   // and (in C2) at the end of the uncommon trap handler. Note this fact
 871   // so that an asynchronous stack walker can work again. This counter is
 872   // incremented at the beginning of fetch_unroll_info() and (in C2) at
 873   // the beginning of uncommon_trap().
 874   thread->dec_in_deopt_handler();
 875 }
 876 
 877 // Moved from cpu directories because none of the cpus has callee save values.
 878 // If a cpu implements callee save values, move this to deoptimization_<cpu>.cpp.
 879 void Deoptimization::unwind_callee_save_values(frame* f, vframeArray* vframe_array) {
 880 
 881   // This code is sort of the equivalent of C2IAdapter::setup_stack_frame back in
 882   // the days we had adapter frames. When we deoptimize a situation where a
 883   // compiled caller calls a compiled caller will have registers it expects
 884   // to survive the call to the callee. If we deoptimize the callee the only
 885   // way we can restore these registers is to have the oldest interpreter
 886   // frame that we create restore these values. That is what this routine
 887   // will accomplish.
 888 
 889   // At the moment we have modified c2 to not have any callee save registers
 890   // so this problem does not exist and this routine is just a place holder.
 891 
 892   assert(f->is_interpreted_frame(), "must be interpreted");
 893 }
 894 
 895 #ifndef PRODUCT
 896 #ifdef ASSERT
 897 // Return true if the execution after the provided bytecode continues at the
 898 // next bytecode in the code. This is not the case for gotos, returns, and
 899 // throws.
 900 static bool falls_through(Bytecodes::Code bc) {
 901   switch (bc) {
 902     case Bytecodes::_goto:
 903     case Bytecodes::_goto_w:
 904     case Bytecodes::_athrow:
 905     case Bytecodes::_areturn:
 906     case Bytecodes::_dreturn:
 907     case Bytecodes::_freturn:
 908     case Bytecodes::_ireturn:
 909     case Bytecodes::_lreturn:
 910     case Bytecodes::_jsr:
 911     case Bytecodes::_ret:
 912     case Bytecodes::_return:
 913     case Bytecodes::_lookupswitch:
 914     case Bytecodes::_tableswitch:
 915       return false;
 916     default:
 917       return true;
 918   }
 919 }
 920 #endif
 921 #endif
 922 
 923 // Return BasicType of value being returned
 924 JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
 925   assert(thread == JavaThread::current(), "pre-condition");
 926 
 927   // We are already active in the special DeoptResourceMark any ResourceObj's we
 928   // allocate will be freed at the end of the routine.
 929 
 930   // JRT_LEAF methods don't normally allocate handles and there is a
 931   // NoHandleMark to enforce that. It is actually safe to use Handles
 932   // in a JRT_LEAF method, and sometimes desirable, but to do so we
 933   // must use ResetNoHandleMark to bypass the NoHandleMark, and
 934   // then use a HandleMark to ensure any Handles we do create are
 935   // cleaned up in this scope.
 936   ResetNoHandleMark rnhm;
 937   HandleMark hm(thread);
 938 
 939   frame stub_frame = thread->last_frame();
 940 
 941   Continuation::notify_deopt(thread, stub_frame.sp());
 942 
 943   // Since the frame to unpack is the top frame of this thread, the vframe_array_head
 944   // must point to the vframeArray for the unpack frame.
 945   vframeArray* array = thread->vframe_array_head();
 946   UnrollBlock* info = array->unroll_block();
 947 
 948   // We set the last_Java frame. But the stack isn't really parsable here. So we
 949   // clear it to make sure JFR understands not to try and walk stacks from events
 950   // in here.
 951   intptr_t* sp = thread->frame_anchor()->last_Java_sp();
 952   thread->frame_anchor()->set_last_Java_sp(nullptr);
 953 
 954   // Unpack the interpreter frames and any adapter frame (c2 only) we might create.
 955   array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
 956 
 957   thread->frame_anchor()->set_last_Java_sp(sp);
 958 
 959   BasicType bt = info->return_type();
 960 
 961   // If we have an exception pending, claim that the return type is an oop
 962   // so the deopt_blob does not overwrite the exception_oop.
 963 
 964   if (exec_mode == Unpack_exception)
 965     bt = T_OBJECT;
 966 
 967   // Cleanup thread deopt data
 968   cleanup_deopt_info(thread, array);
 969 
 970 #ifndef PRODUCT
 971   if (VerifyStack) {
 972     ResourceMark res_mark;
 973     // Clear pending exception to not break verification code (restored afterwards)
 974     PreserveExceptionMark pm(thread);
 975 
 976     thread->validate_frame_layout();
 977 
 978     // Verify that the just-unpacked frames match the interpreter's
 979     // notions of expression stack and locals
 980     vframeArray* cur_array = thread->vframe_array_last();
 981     RegisterMap rm(thread,
 982                    RegisterMap::UpdateMap::skip,
 983                    RegisterMap::ProcessFrames::include,
 984                    RegisterMap::WalkContinuation::skip);
 985     rm.set_include_argument_oops(false);
 986     int callee_size_of_parameters = 0;
 987     for (int frame_idx = 0; frame_idx < cur_array->frames(); frame_idx++) {
 988       bool is_top_frame = (frame_idx == 0);
 989       vframeArrayElement* el = cur_array->element(frame_idx);
 990       frame* iframe = el->iframe();
 991       guarantee(iframe->is_interpreted_frame(), "Wrong frame type");
 992       methodHandle mh(thread, iframe->interpreter_frame_method());
 993       bool reexecute = el->should_reexecute();
 994 
 995       int cur_invoke_parameter_size = 0;
 996       int top_frame_expression_stack_adjustment = 0;
 997       int max_bci = mh->code_size();
 998       BytecodeStream str(mh, iframe->interpreter_frame_bci());
 999       assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
1000       Bytecodes::Code cur_code = str.next();
1001 
1002       if (!reexecute && !Bytecodes::is_invoke(cur_code)) {
1003         // We can only compute OopMaps for the before state, so we need to roll forward
1004         // to the next bytecode.
1005         assert(is_top_frame, "must be");
1006         assert(falls_through(cur_code), "must be");
1007         assert(cur_code != Bytecodes::_illegal, "illegal bytecode");
1008         assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
1009 
1010         // Need to subtract off the size of the result type of
1011         // the bytecode because this is not described in the
1012         // debug info but returned to the interpreter in the TOS
1013         // caching register
1014         BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
1015         if (bytecode_result_type != T_ILLEGAL) {
1016           top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
1017         }
1018         assert(top_frame_expression_stack_adjustment >= 0, "stack adjustment must be positive");
1019 
1020         cur_code = str.next();
1021         // Reflect the fact that we have rolled forward and now need
1022         // top_frame_expression_stack_adjustment
1023         reexecute = true;
1024       }
1025 
1026       assert(cur_code != Bytecodes::_illegal, "illegal bytecode");
1027       assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
1028 
1029       // Get the oop map for this bci
1030       InterpreterOopMap mask;
1031       OopMapCache::compute_one_oop_map(mh, str.bci(), &mask);
1032       // Check to see if we can grab the number of outgoing arguments
1033       // at an uncommon trap for an invoke (where the compiler
1034       // generates debug info before the invoke has executed)
1035       if (Bytecodes::is_invoke(cur_code)) {
1036         Bytecode_invoke invoke(mh, str.bci());
1037         cur_invoke_parameter_size = invoke.size_of_parameters();
1038         if (!is_top_frame && invoke.has_member_arg()) {
1039           callee_size_of_parameters++;
1040         }
1041       }
1042 
1043       // Verify stack depth and oops in frame
1044       auto match = [&]() {
1045         int iframe_expr_ssize = iframe->interpreter_frame_expression_stack_size();
1046 #if INCLUDE_JVMCI
1047         if (is_top_frame && el->rethrow_exception()) {
1048           return iframe_expr_ssize == 1;
1049         }
1050 #endif
1051         // This should only be needed for C1
1052         if (is_top_frame && exec_mode == Unpack_exception && iframe_expr_ssize == 0) {
1053           return true;
1054         }
1055         if (reexecute) {
1056           int expr_ssize_before = iframe_expr_ssize + top_frame_expression_stack_adjustment;
1057           int oopmap_expr_invoke_ssize = mask.expression_stack_size() + cur_invoke_parameter_size;
1058           return expr_ssize_before == oopmap_expr_invoke_ssize;
1059         } else {
1060           int oopmap_expr_callee_ssize = mask.expression_stack_size() + callee_size_of_parameters;
1061           return iframe_expr_ssize == oopmap_expr_callee_ssize;
1062         }
1063       };
1064       if (!match()) {
1065         // Print out some information that will help us debug the problem
1066         tty->print_cr("Wrong number of expression stack elements during deoptimization");
1067         tty->print_cr("  Error occurred while verifying frame %d (0..%d, 0 is topmost)", frame_idx, cur_array->frames() - 1);
1068         tty->print_cr("  Current code %s", Bytecodes::name(cur_code));
1069         tty->print_cr("  Fabricated interpreter frame had %d expression stack elements",
1070                       iframe->interpreter_frame_expression_stack_size());
1071         tty->print_cr("  Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
1072         tty->print_cr("  callee_size_of_parameters = %d", callee_size_of_parameters);
1073         tty->print_cr("  top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
1074         tty->print_cr("  exec_mode = %d", exec_mode);
1075         tty->print_cr("  original should_reexecute = %s", el->should_reexecute() ? "true" : "false");
1076         tty->print_cr("  reexecute = %s%s", reexecute ? "true" : "false",
1077                       (reexecute != el->should_reexecute()) ? " (changed)" : "");
1078 #if INCLUDE_JVMCI
1079         tty->print_cr("  rethrow_exception = %s", el->rethrow_exception() ? "true" : "false");
1080 #endif
1081         tty->print_cr("  cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
1082         tty->print_cr("  Thread = " INTPTR_FORMAT ", thread ID = %d", p2i(thread), thread->osthread()->thread_id());
1083         tty->print_cr("  Interpreted frames:");
1084         for (int k = 0; k < cur_array->frames(); k++) {
1085           vframeArrayElement* el = cur_array->element(k);
1086           tty->print_cr("    %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
1087         }
1088         cur_array->print_on_2(tty);
1089         guarantee(false, "wrong number of expression stack elements during deopt");
1090       }
1091       VerifyOopClosure verify;
1092       iframe->oops_interpreted_do(&verify, &rm, false);
1093       callee_size_of_parameters = mh->size_of_parameters();
1094     }
1095   }
1096 #endif // !PRODUCT
1097 
1098   return bt;
1099 JRT_END
1100 
1101 class DeoptimizeMarkedHandshakeClosure : public HandshakeClosure {
1102  public:
1103   DeoptimizeMarkedHandshakeClosure() : HandshakeClosure("Deoptimize") {}
1104   void do_thread(Thread* thread) {
1105     JavaThread* jt = JavaThread::cast(thread);
1106     jt->deoptimize_marked_methods();
1107   }
1108 };
1109 
1110 void Deoptimization::deoptimize_all_marked() {
1111   ResourceMark rm;
1112 
1113   // Make the dependent methods not entrant
1114   CodeCache::make_marked_nmethods_deoptimized();
1115 
1116   DeoptimizeMarkedHandshakeClosure deopt;
1117   if (SafepointSynchronize::is_at_safepoint()) {
1118     Threads::java_threads_do(&deopt);
1119   } else {
1120     Handshake::execute(&deopt);
1121   }
1122 }
1123 
1124 Deoptimization::DeoptAction Deoptimization::_unloaded_action
1125   = Deoptimization::Action_reinterpret;
1126 
1127 #if INCLUDE_JVMCI
1128 template<typename CacheType>
1129 class BoxCacheBase : public CHeapObj<mtCompiler> {
1130 protected:
1131   static InstanceKlass* find_cache_klass(Thread* thread, Symbol* klass_name) {
1132     ResourceMark rm(thread);
1133     char* klass_name_str = klass_name->as_C_string();
1134     InstanceKlass* ik = SystemDictionary::find_instance_klass(thread, klass_name, Handle());
1135     guarantee(ik != nullptr, "%s must be loaded", klass_name_str);
1136     if (!ik->is_in_error_state()) {
1137       guarantee(ik->is_initialized(), "%s must be initialized", klass_name_str);
1138       CacheType::compute_offsets(ik);
1139     }
1140     return ik;
1141   }
1142 };
1143 
1144 template<typename PrimitiveType, typename CacheType, typename BoxType> class BoxCache  : public BoxCacheBase<CacheType> {
1145   PrimitiveType _low;
1146   PrimitiveType _high;
1147   jobject _cache;
1148 protected:
1149   static BoxCache<PrimitiveType, CacheType, BoxType> *_singleton;
1150   BoxCache(Thread* thread) {
1151     InstanceKlass* ik = BoxCacheBase<CacheType>::find_cache_klass(thread, CacheType::symbol());
1152     if (ik->is_in_error_state()) {
1153       _low = 1;
1154       _high = 0;
1155       _cache = nullptr;
1156     } else {
1157       objArrayOop cache = CacheType::cache(ik);
1158       assert(cache->length() > 0, "Empty cache");
1159       _low = BoxType::value(cache->obj_at(0));
1160       _high = checked_cast<PrimitiveType>(_low + cache->length() - 1);
1161       _cache = JNIHandles::make_global(Handle(thread, cache));
1162     }
1163   }
1164   ~BoxCache() {
1165     JNIHandles::destroy_global(_cache);
1166   }
1167 public:
1168   static BoxCache<PrimitiveType, CacheType, BoxType>* singleton(Thread* thread) {
1169     if (_singleton == nullptr) {
1170       BoxCache<PrimitiveType, CacheType, BoxType>* s = new BoxCache<PrimitiveType, CacheType, BoxType>(thread);
1171       if (!Atomic::replace_if_null(&_singleton, s)) {
1172         delete s;
1173       }
1174     }
1175     return _singleton;
1176   }
1177   oop lookup(PrimitiveType value) {
1178     if (_low <= value && value <= _high) {
1179       int offset = checked_cast<int>(value - _low);
1180       return objArrayOop(JNIHandles::resolve_non_null(_cache))->obj_at(offset);
1181     }
1182     return nullptr;
1183   }
1184   oop lookup_raw(intptr_t raw_value, bool& cache_init_error) {
1185     if (_cache == nullptr) {
1186       cache_init_error = true;
1187       return nullptr;
1188     }
1189     // Have to cast to avoid little/big-endian problems.
1190     if (sizeof(PrimitiveType) > sizeof(jint)) {
1191       jlong value = (jlong)raw_value;
1192       return lookup(value);
1193     }
1194     PrimitiveType value = (PrimitiveType)*((jint*)&raw_value);
1195     return lookup(value);
1196   }
1197 };
1198 
1199 typedef BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer> IntegerBoxCache;
1200 typedef BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long> LongBoxCache;
1201 typedef BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character> CharacterBoxCache;
1202 typedef BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short> ShortBoxCache;
1203 typedef BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte> ByteBoxCache;
1204 
1205 template<> BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>* BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>::_singleton = nullptr;
1206 template<> BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>* BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>::_singleton = nullptr;
1207 template<> BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>* BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>::_singleton = nullptr;
1208 template<> BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>* BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>::_singleton = nullptr;
1209 template<> BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>* BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>::_singleton = nullptr;
1210 
1211 class BooleanBoxCache : public BoxCacheBase<java_lang_Boolean> {
1212   jobject _true_cache;
1213   jobject _false_cache;
1214 protected:
1215   static BooleanBoxCache *_singleton;
1216   BooleanBoxCache(Thread *thread) {
1217     InstanceKlass* ik = find_cache_klass(thread, java_lang_Boolean::symbol());
1218     if (ik->is_in_error_state()) {
1219       _true_cache = nullptr;
1220       _false_cache = nullptr;
1221     } else {
1222       _true_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_TRUE(ik)));
1223       _false_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_FALSE(ik)));
1224     }
1225   }
1226   ~BooleanBoxCache() {
1227     JNIHandles::destroy_global(_true_cache);
1228     JNIHandles::destroy_global(_false_cache);
1229   }
1230 public:
1231   static BooleanBoxCache* singleton(Thread* thread) {
1232     if (_singleton == nullptr) {
1233       BooleanBoxCache* s = new BooleanBoxCache(thread);
1234       if (!Atomic::replace_if_null(&_singleton, s)) {
1235         delete s;
1236       }
1237     }
1238     return _singleton;
1239   }
1240   oop lookup_raw(intptr_t raw_value, bool& cache_in_error) {
1241     if (_true_cache == nullptr) {
1242       cache_in_error = true;
1243       return nullptr;
1244     }
1245     // Have to cast to avoid little/big-endian problems.
1246     jboolean value = (jboolean)*((jint*)&raw_value);
1247     return lookup(value);
1248   }
1249   oop lookup(jboolean value) {
1250     if (value != 0) {
1251       return JNIHandles::resolve_non_null(_true_cache);
1252     }
1253     return JNIHandles::resolve_non_null(_false_cache);
1254   }
1255 };
1256 
1257 BooleanBoxCache* BooleanBoxCache::_singleton = nullptr;
1258 
1259 oop Deoptimization::get_cached_box(AutoBoxObjectValue* bv, frame* fr, RegisterMap* reg_map, bool& cache_init_error, TRAPS) {
1260    Klass* k = java_lang_Class::as_Klass(bv->klass()->as_ConstantOopReadValue()->value()());
1261    BasicType box_type = vmClasses::box_klass_type(k);
1262    if (box_type != T_OBJECT) {
1263      StackValue* value = StackValue::create_stack_value(fr, reg_map, bv->field_at(box_type == T_LONG ? 1 : 0));
1264      switch(box_type) {
1265        case T_INT:     return IntegerBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1266        case T_CHAR:    return CharacterBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1267        case T_SHORT:   return ShortBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1268        case T_BYTE:    return ByteBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1269        case T_BOOLEAN: return BooleanBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1270        case T_LONG:    return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1271        default:;
1272      }
1273    }
1274    return nullptr;
1275 }
1276 #endif // INCLUDE_JVMCI
1277 
1278 #if COMPILER2_OR_JVMCI
1279 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) {
1280   Handle pending_exception(THREAD, thread->pending_exception());
1281   const char* exception_file = thread->exception_file();
1282   int exception_line = thread->exception_line();
1283   thread->clear_pending_exception();
1284 
1285   bool failures = false;
1286 
1287   for (int i = 0; i < objects->length(); i++) {
1288     assert(objects->at(i)->is_object(), "invalid debug information");
1289     ObjectValue* sv = (ObjectValue*) objects->at(i);
1290     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1291     k = get_refined_array_klass(k, fr, reg_map, sv, THREAD);
1292 
1293     // Check if the object may be null and has an additional null_marker input that needs
1294     // to be checked before using the field values. Skip re-allocation if it is null.
1295     if (k->is_inline_klass() && sv->has_properties()) {
1296       jint null_marker = StackValue::create_stack_value(fr, reg_map, sv->properties())->get_jint();
1297       if (null_marker == 0) {
1298         continue;
1299       }
1300     }
1301 
1302     oop obj = nullptr;
1303     bool cache_init_error = false;
1304     if (k->is_instance_klass()) {
1305 #if INCLUDE_JVMCI
1306       nmethod* nm = fr->cb()->as_nmethod_or_null();
1307       if (nm->is_compiled_by_jvmci() && sv->is_auto_box()) {
1308         AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv;
1309         obj = get_cached_box(abv, fr, reg_map, cache_init_error, THREAD);
1310         if (obj != nullptr) {
1311           // Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it.
1312           abv->set_cached(true);
1313         } else if (cache_init_error) {
1314           // Results in an OOME which is valid (as opposed to a class initialization error)
1315           // and is fine for the rare case a cache initialization failing.
1316           failures = true;
1317         }
1318       }
1319 #endif // INCLUDE_JVMCI
1320 
1321       InstanceKlass* ik = InstanceKlass::cast(k);
1322       if (obj == nullptr && !cache_init_error) {
1323         InternalOOMEMark iom(THREAD);
1324         if (EnableVectorSupport && VectorSupport::is_vector(ik)) {
1325           obj = VectorSupport::allocate_vector(ik, fr, reg_map, sv, THREAD);
1326         } else {
1327           obj = ik->allocate_instance(THREAD);
1328         }
1329       }
1330     } else if (k->is_flatArray_klass()) {
1331       FlatArrayKlass* ak = FlatArrayKlass::cast(k);
1332       // Inline type array must be zeroed because not all memory is reassigned
1333       obj = ak->allocate_instance(sv->field_size(), ak->properties(), THREAD);
1334     } else if (k->is_typeArray_klass()) {
1335       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1336       assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
1337       int len = sv->field_size() / type2size[ak->element_type()];
1338       InternalOOMEMark iom(THREAD);
1339       obj = ak->allocate_instance(len, THREAD);
1340     } else if (k->is_refArray_klass()) {
1341       RefArrayKlass* ak = RefArrayKlass::cast(k);
1342       InternalOOMEMark iom(THREAD);
1343       obj = ak->allocate_instance(sv->field_size(), ak->properties(), THREAD);
1344     }
1345 
1346     if (obj == nullptr) {
1347       failures = true;
1348     }
1349 
1350     assert(sv->value().is_null(), "redundant reallocation");
1351     assert(obj != nullptr || HAS_PENDING_EXCEPTION || cache_init_error, "allocation should succeed or we should get an exception");
1352     CLEAR_PENDING_EXCEPTION;
1353     sv->set_value(obj);
1354   }
1355 
1356   if (failures) {
1357     THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
1358   } else if (pending_exception.not_null()) {
1359     thread->set_pending_exception(pending_exception(), exception_file, exception_line);
1360   }
1361 
1362   return failures;
1363 }
1364 
1365 // We're deoptimizing at the return of a call, inline type fields are
1366 // in registers. When we go back to the interpreter, it will expect a
1367 // reference to an inline type instance. Allocate and initialize it from
1368 // the register values here.
1369 bool Deoptimization::realloc_inline_type_result(InlineKlass* vk, const RegisterMap& map, GrowableArray<Handle>& return_oops, TRAPS) {
1370   oop new_vt = vk->realloc_result(map, return_oops, THREAD);
1371   if (new_vt == nullptr) {
1372     CLEAR_PENDING_EXCEPTION;
1373     THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), true);
1374   }
1375   return_oops.clear();
1376   return_oops.push(Handle(THREAD, new_vt));
1377   return false;
1378 }
1379 
1380 #if INCLUDE_JVMCI
1381 /**
1382  * For primitive types whose kind gets "erased" at runtime (shorts become stack ints),
1383  * we need to somehow be able to recover the actual kind to be able to write the correct
1384  * amount of bytes.
1385  * For that purpose, this method assumes that, for an entry spanning n bytes at index i,
1386  * the entries at index n + 1 to n + i are 'markers'.
1387  * For example, if we were writing a short at index 4 of a byte array of size 8, the
1388  * expected form of the array would be:
1389  *
1390  * {b0, b1, b2, b3, INT, marker, b6, b7}
1391  *
1392  * Thus, in order to get back the size of the entry, we simply need to count the number
1393  * of marked entries
1394  *
1395  * @param virtualArray the virtualized byte array
1396  * @param i index of the virtual entry we are recovering
1397  * @return The number of bytes the entry spans
1398  */
1399 static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) {
1400   int index = i;
1401   while (++index < virtualArray->field_size() &&
1402            virtualArray->field_at(index)->is_marker()) {}
1403   return index - i;
1404 }
1405 
1406 /**
1407  * If there was a guarantee for byte array to always start aligned to a long, we could
1408  * do a simple check on the parity of the index. Unfortunately, that is not always the
1409  * case. Thus, we check alignment of the actual address we are writing to.
1410  * In the unlikely case index 0 is 5-aligned for example, it would then be possible to
1411  * write a long to index 3.
1412  */
1413 static jbyte* check_alignment_get_addr(typeArrayOop obj, int index, int expected_alignment) {
1414     jbyte* res = obj->byte_at_addr(index);
1415     assert((((intptr_t) res) % expected_alignment) == 0, "Non-aligned write");
1416     return res;
1417 }
1418 
1419 static void byte_array_put(typeArrayOop obj, StackValue* value, int index, int byte_count) {
1420   switch (byte_count) {
1421     case 1:
1422       obj->byte_at_put(index, (jbyte) value->get_jint());
1423       break;
1424     case 2:
1425       *((jshort *) check_alignment_get_addr(obj, index, 2)) = (jshort) value->get_jint();
1426       break;
1427     case 4:
1428       *((jint *) check_alignment_get_addr(obj, index, 4)) = value->get_jint();
1429       break;
1430     case 8:
1431       *((jlong *) check_alignment_get_addr(obj, index, 8)) = (jlong) value->get_intptr();
1432       break;
1433     default:
1434       ShouldNotReachHere();
1435   }
1436 }
1437 #endif // INCLUDE_JVMCI
1438 
1439 
1440 // restore elements of an eliminated type array
1441 void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
1442   int index = 0;
1443 
1444   for (int i = 0; i < sv->field_size(); i++) {
1445     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1446     switch(type) {
1447     case T_LONG: case T_DOUBLE: {
1448       assert(value->type() == T_INT, "Agreement.");
1449       StackValue* low =
1450         StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1451 #ifdef _LP64
1452       jlong res = (jlong)low->get_intptr();
1453 #else
1454       jlong res = jlong_from(value->get_jint(), low->get_jint());
1455 #endif
1456       obj->long_at_put(index, res);
1457       break;
1458     }
1459 
1460     case T_INT: case T_FLOAT: { // 4 bytes.
1461       assert(value->type() == T_INT, "Agreement.");
1462       bool big_value = false;
1463       if (i + 1 < sv->field_size() && type == T_INT) {
1464         if (sv->field_at(i)->is_location()) {
1465           Location::Type type = ((LocationValue*) sv->field_at(i))->location().type();
1466           if (type == Location::dbl || type == Location::lng) {
1467             big_value = true;
1468           }
1469         } else if (sv->field_at(i)->is_constant_int()) {
1470           ScopeValue* next_scope_field = sv->field_at(i + 1);
1471           if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1472             big_value = true;
1473           }
1474         }
1475       }
1476 
1477       if (big_value) {
1478         StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1479   #ifdef _LP64
1480         jlong res = (jlong)low->get_intptr();
1481   #else
1482         jlong res = jlong_from(value->get_jint(), low->get_jint());
1483   #endif
1484         obj->int_at_put(index, *(jint*)&res);
1485         obj->int_at_put(++index, *((jint*)&res + 1));
1486       } else {
1487         obj->int_at_put(index, value->get_jint());
1488       }
1489       break;
1490     }
1491 
1492     case T_SHORT:
1493       assert(value->type() == T_INT, "Agreement.");
1494       obj->short_at_put(index, (jshort)value->get_jint());
1495       break;
1496 
1497     case T_CHAR:
1498       assert(value->type() == T_INT, "Agreement.");
1499       obj->char_at_put(index, (jchar)value->get_jint());
1500       break;
1501 
1502     case T_BYTE: {
1503       assert(value->type() == T_INT, "Agreement.");
1504 #if INCLUDE_JVMCI
1505       // The value we get is erased as a regular int. We will need to find its actual byte count 'by hand'.
1506       int byte_count = count_number_of_bytes_for_entry(sv, i);
1507       byte_array_put(obj, value, index, byte_count);
1508       // According to byte_count contract, the values from i + 1 to i + byte_count are illegal values. Skip.
1509       i += byte_count - 1; // Balance the loop counter.
1510       index += byte_count;
1511       // index has been updated so continue at top of loop
1512       continue;
1513 #else
1514       obj->byte_at_put(index, (jbyte)value->get_jint());
1515       break;
1516 #endif // INCLUDE_JVMCI
1517     }
1518 
1519     case T_BOOLEAN: {
1520       assert(value->type() == T_INT, "Agreement.");
1521       obj->bool_at_put(index, (jboolean)value->get_jint());
1522       break;
1523     }
1524 
1525       default:
1526         ShouldNotReachHere();
1527     }
1528     index++;
1529   }
1530 }
1531 
1532 // restore fields of an eliminated object array
1533 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
1534   for (int i = 0; i < sv->field_size(); i++) {
1535     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1536     assert(value->type() == T_OBJECT, "object element expected");
1537     obj->obj_at_put(i, value->get_obj()());
1538   }
1539 }
1540 
1541 class ReassignedField {
1542 public:
1543   int _offset;
1544   BasicType _type;
1545   InstanceKlass* _klass;
1546   bool _is_flat;
1547   bool _is_null_free;
1548 public:
1549   ReassignedField() : _offset(0), _type(T_ILLEGAL), _klass(nullptr), _is_flat(false), _is_null_free(false) { }
1550 };
1551 
1552 // Gets the fields of `klass` that are eliminated by escape analysis and need to be reassigned
1553 static GrowableArray<ReassignedField>* get_reassigned_fields(InstanceKlass* klass, GrowableArray<ReassignedField>* fields, bool is_jvmci) {
1554   InstanceKlass* super = klass->superklass();
1555   if (super != nullptr) {
1556     get_reassigned_fields(super, fields, is_jvmci);
1557   }
1558   for (AllFieldStream fs(klass); !fs.done(); fs.next()) {
1559     if (!fs.access_flags().is_static() && (is_jvmci || !fs.field_flags().is_injected())) {
1560       ReassignedField field;
1561       field._offset = fs.offset();
1562       field._type = Signature::basic_type(fs.signature());
1563       if (fs.is_flat()) {
1564         field._is_flat = true;
1565         field._is_null_free = fs.is_null_free_inline_type();
1566         // Resolve klass of flat inline type field
1567         field._klass = InlineKlass::cast(klass->get_inline_type_field_klass(fs.index()));
1568       }
1569       fields->append(field);
1570     }
1571   }
1572   return fields;
1573 }
1574 
1575 // Restore fields of an eliminated instance object employing the same field order used by the
1576 // compiler when it scalarizes an object at safepoints.
1577 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) {
1578   GrowableArray<ReassignedField>* fields = get_reassigned_fields(klass, new GrowableArray<ReassignedField>(), is_jvmci);
1579   for (int i = 0; i < fields->length(); i++) {
1580     BasicType type = fields->at(i)._type;
1581     int offset = base_offset + fields->at(i)._offset;
1582     // Check for flat inline type field before accessing the ScopeValue because it might not have any fields
1583     if (fields->at(i)._is_flat) {
1584       // Recursively re-assign flat inline type fields
1585       InstanceKlass* vk = fields->at(i)._klass;
1586       assert(vk != nullptr, "must be resolved");
1587       offset -= InlineKlass::cast(vk)->payload_offset(); // Adjust offset to omit oop header
1588       svIndex = reassign_fields_by_klass(vk, fr, reg_map, sv, svIndex, obj, is_jvmci, offset, CHECK_0);
1589       if (!fields->at(i)._is_null_free) {
1590         ScopeValue* scope_field = sv->field_at(svIndex);
1591         StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1592         int nm_offset = offset + InlineKlass::cast(vk)->null_marker_offset();
1593         obj->bool_field_put(nm_offset, value->get_jint() & 1);
1594         svIndex++;
1595       }
1596       continue; // Continue because we don't need to increment svIndex
1597     }
1598 
1599     ScopeValue* scope_field = sv->field_at(svIndex);
1600     StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1601     switch (type) {
1602       case T_OBJECT:
1603       case T_ARRAY:
1604         assert(value->type() == T_OBJECT, "Agreement.");
1605         obj->obj_field_put(offset, value->get_obj()());
1606         break;
1607 
1608       case T_INT: case T_FLOAT: { // 4 bytes.
1609         assert(value->type() == T_INT, "Agreement.");
1610         bool big_value = false;
1611         if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {
1612           if (scope_field->is_location()) {
1613             Location::Type type = ((LocationValue*) scope_field)->location().type();
1614             if (type == Location::dbl || type == Location::lng) {
1615               big_value = true;
1616             }
1617           }
1618           if (scope_field->is_constant_int()) {
1619             ScopeValue* next_scope_field = sv->field_at(svIndex + 1);
1620             if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1621               big_value = true;
1622             }
1623           }
1624         }
1625 
1626         if (big_value) {
1627           i++;
1628           assert(i < fields->length(), "second T_INT field needed");
1629           assert(fields->at(i)._type == T_INT, "T_INT field needed");
1630         } else {
1631           obj->int_field_put(offset, value->get_jint());
1632           break;
1633         }
1634       }
1635         /* no break */
1636 
1637       case T_LONG: case T_DOUBLE: {
1638         assert(value->type() == T_INT, "Agreement.");
1639         StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++svIndex));
1640 #ifdef _LP64
1641         jlong res = (jlong)low->get_intptr();
1642 #else
1643         jlong res = jlong_from(value->get_jint(), low->get_jint());
1644 #endif
1645         obj->long_field_put(offset, res);
1646         break;
1647       }
1648 
1649       case T_SHORT:
1650         assert(value->type() == T_INT, "Agreement.");
1651         obj->short_field_put(offset, (jshort)value->get_jint());
1652         break;
1653 
1654       case T_CHAR:
1655         assert(value->type() == T_INT, "Agreement.");
1656         obj->char_field_put(offset, (jchar)value->get_jint());
1657         break;
1658 
1659       case T_BYTE:
1660         assert(value->type() == T_INT, "Agreement.");
1661         obj->byte_field_put(offset, (jbyte)value->get_jint());
1662         break;
1663 
1664       case T_BOOLEAN:
1665         assert(value->type() == T_INT, "Agreement.");
1666         obj->bool_field_put(offset, (jboolean)value->get_jint());
1667         break;
1668 
1669       default:
1670         ShouldNotReachHere();
1671     }
1672     svIndex++;
1673   }
1674 
1675   return svIndex;
1676 }
1677 
1678 // restore fields of an eliminated inline type array
1679 void Deoptimization::reassign_flat_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, flatArrayOop obj, FlatArrayKlass* vak, bool is_jvmci, TRAPS) {
1680   InlineKlass* vk = vak->element_klass();
1681   assert(vk->maybe_flat_in_array(), "should only be used for flat inline type arrays");
1682   // Adjust offset to omit oop header
1683   int base_offset = arrayOopDesc::base_offset_in_bytes(T_FLAT_ELEMENT) - InlineKlass::cast(vk)->payload_offset();
1684   // Initialize all elements of the flat inline type array
1685   for (int i = 0; i < sv->field_size(); i++) {
1686     ScopeValue* val = sv->field_at(i);
1687     int offset = base_offset + (i << Klass::layout_helper_log2_element_size(vak->layout_helper()));
1688     reassign_fields_by_klass(vk, fr, reg_map, val->as_ObjectValue(), 0, (oop)obj, is_jvmci, offset, CHECK);
1689   }
1690 }
1691 
1692 // restore fields of all eliminated objects and arrays
1693 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool is_jvmci, TRAPS) {
1694   for (int i = 0; i < objects->length(); i++) {
1695     assert(objects->at(i)->is_object(), "invalid debug information");
1696     ObjectValue* sv = (ObjectValue*) objects->at(i);
1697     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1698     k = get_refined_array_klass(k, fr, reg_map, sv, THREAD);
1699 
1700     Handle obj = sv->value();
1701     assert(obj.not_null() || realloc_failures || sv->has_properties(), "reallocation was missed");
1702 #ifndef PRODUCT
1703     if (PrintDeoptimizationDetails) {
1704       tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());
1705     }
1706 #endif // !PRODUCT
1707 
1708     if (obj.is_null()) {
1709       continue;
1710     }
1711 
1712 #if INCLUDE_JVMCI
1713     // Don't reassign fields of boxes that came from a cache. Caches may be in CDS.
1714     if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) {
1715       continue;
1716     }
1717 #endif // INCLUDE_JVMCI
1718     if (EnableVectorSupport && VectorSupport::is_vector(k)) {
1719       assert(sv->field_size() == 1, "%s not a vector", k->name()->as_C_string());
1720       ScopeValue* payload = sv->field_at(0);
1721       if (payload->is_location() &&
1722           payload->as_LocationValue()->location().type() == Location::vector) {
1723 #ifndef PRODUCT
1724         if (PrintDeoptimizationDetails) {
1725           tty->print_cr("skip field reassignment for this vector - it should be assigned already");
1726           if (Verbose) {
1727             Handle obj = sv->value();
1728             k->oop_print_on(obj(), tty);
1729           }
1730         }
1731 #endif // !PRODUCT
1732         continue; // Such vector's value was already restored in VectorSupport::allocate_vector().
1733       }
1734       // Else fall-through to do assignment for scalar-replaced boxed vector representation
1735       // which could be restored after vector object allocation.
1736     }
1737     if (k->is_instance_klass()) {
1738       InstanceKlass* ik = InstanceKlass::cast(k);
1739       reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), is_jvmci, 0, CHECK);
1740     } else if (k->is_flatArray_klass()) {
1741       FlatArrayKlass* vak = FlatArrayKlass::cast(k);
1742       reassign_flat_array_elements(fr, reg_map, sv, (flatArrayOop) obj(), vak, is_jvmci, CHECK);
1743     } else if (k->is_typeArray_klass()) {
1744       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1745       reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
1746     } else if (k->is_refArray_klass()) {
1747       reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
1748     }
1749   }
1750   // These objects may escape when we return to Interpreter after deoptimization.
1751   // We need barrier so that stores that initialize these objects can't be reordered
1752   // with subsequent stores that make these objects accessible by other threads.
1753   OrderAccess::storestore();
1754 }
1755 
1756 
1757 // relock objects for which synchronization was eliminated
1758 bool Deoptimization::relock_objects(JavaThread* thread, GrowableArray<MonitorInfo*>* monitors,
1759                                     JavaThread* deoptee_thread, frame& fr, int exec_mode, bool realloc_failures) {
1760   bool relocked_objects = false;
1761   for (int i = 0; i < monitors->length(); i++) {
1762     MonitorInfo* mon_info = monitors->at(i);
1763     if (mon_info->eliminated()) {
1764       assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
1765       relocked_objects = true;
1766       if (!mon_info->owner_is_scalar_replaced()) {
1767         Handle obj(thread, mon_info->owner());
1768         markWord mark = obj->mark();
1769         if (exec_mode == Unpack_none) {
1770           if (LockingMode == LM_LEGACY && mark.has_locker() && fr.sp() > (intptr_t*)mark.locker()) {
1771             // With exec_mode == Unpack_none obj may be thread local and locked in
1772             // a callee frame. Make the lock in the callee a recursive lock and restore the displaced header.
1773             markWord dmw = mark.displaced_mark_helper();
1774             mark.locker()->set_displaced_header(markWord::encode((BasicLock*) nullptr));
1775             obj->set_mark(dmw);
1776           }
1777           if (mark.has_monitor()) {
1778             // defer relocking if the deoptee thread is currently waiting for obj
1779             ObjectMonitor* waiting_monitor = deoptee_thread->current_waiting_monitor();
1780             if (waiting_monitor != nullptr && waiting_monitor->object() == obj()) {
1781               assert(fr.is_deoptimized_frame(), "frame must be scheduled for deoptimization");
1782               if (LockingMode == LM_LEGACY) {
1783                 mon_info->lock()->set_displaced_header(markWord::unused_mark());
1784               } else if (UseObjectMonitorTable) {
1785                 mon_info->lock()->clear_object_monitor_cache();
1786               }
1787 #ifdef ASSERT
1788               else {
1789                 assert(LockingMode == LM_MONITOR || !UseObjectMonitorTable, "must be");
1790                 mon_info->lock()->set_bad_metadata_deopt();
1791               }
1792 #endif
1793               JvmtiDeferredUpdates::inc_relock_count_after_wait(deoptee_thread);
1794               continue;
1795             }
1796           }
1797         }
1798         BasicLock* lock = mon_info->lock();
1799         if (LockingMode == LM_LIGHTWEIGHT) {
1800           // We have lost information about the correct state of the lock stack.
1801           // Entering may create an invalid lock stack. Inflate the lock if it
1802           // was fast_locked to restore the valid lock stack.
1803           if (UseObjectMonitorTable) {
1804             // UseObjectMonitorTable expects the BasicLock cache to be either a
1805             // valid ObjectMonitor* or nullptr. Right now it is garbage, set it
1806             // to nullptr.
1807             lock->clear_object_monitor_cache();
1808           }
1809           ObjectSynchronizer::enter_for(obj, lock, deoptee_thread);
1810           if (deoptee_thread->lock_stack().contains(obj())) {
1811             LightweightSynchronizer::inflate_fast_locked_object(obj(), ObjectSynchronizer::InflateCause::inflate_cause_vm_internal,
1812                                                                 deoptee_thread, thread);
1813           }
1814           assert(mon_info->owner()->is_locked(), "object must be locked now");
1815           assert(obj->mark().has_monitor(), "must be");
1816           assert(!deoptee_thread->lock_stack().contains(obj()), "must be");
1817           assert(ObjectSynchronizer::read_monitor(thread, obj(), obj->mark())->has_owner(deoptee_thread), "must be");
1818         } else {
1819           ObjectSynchronizer::enter_for(obj, lock, deoptee_thread);
1820           assert(mon_info->owner()->is_locked(), "object must be locked now");
1821         }
1822       }
1823     }
1824   }
1825   return relocked_objects;
1826 }
1827 #endif // COMPILER2_OR_JVMCI
1828 
1829 vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {
1830   Events::log_deopt_message(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, p2i(fr.pc()), p2i(fr.sp()));
1831 
1832   // Register map for next frame (used for stack crawl).  We capture
1833   // the state of the deopt'ing frame's caller.  Thus if we need to
1834   // stuff a C2I adapter we can properly fill in the callee-save
1835   // register locations.
1836   frame caller = fr.sender(reg_map);
1837   int frame_size = pointer_delta_as_int(caller.sp(), fr.sp());
1838 
1839   frame sender = caller;
1840 
1841   // Since the Java thread being deoptimized will eventually adjust it's own stack,
1842   // the vframeArray containing the unpacking information is allocated in the C heap.
1843   // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().
1844   vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);
1845 
1846   // Compare the vframeArray to the collected vframes
1847   assert(array->structural_compare(thread, chunk), "just checking");
1848 
1849   if (TraceDeoptimization) {
1850     ResourceMark rm;
1851     stringStream st;
1852     st.print_cr("DEOPT PACKING thread=" INTPTR_FORMAT " vframeArray=" INTPTR_FORMAT, p2i(thread), p2i(array));
1853     st.print("   ");
1854     fr.print_on(&st);
1855     st.print_cr("   Virtual frames (innermost/newest first):");
1856     for (int index = 0; index < chunk->length(); index++) {
1857       compiledVFrame* vf = chunk->at(index);
1858       int bci = vf->raw_bci();
1859       const char* code_name;
1860       if (bci == SynchronizationEntryBCI) {
1861         code_name = "sync entry";
1862       } else {
1863         Bytecodes::Code code = vf->method()->code_at(bci);
1864         code_name = Bytecodes::name(code);
1865       }
1866 
1867       st.print("      VFrame %d (" INTPTR_FORMAT ")", index, p2i(vf));
1868       st.print(" - %s", vf->method()->name_and_sig_as_C_string());
1869       st.print(" - %s", code_name);
1870       st.print_cr(" @ bci=%d ", bci);
1871     }
1872     tty->print_raw(st.freeze());
1873     tty->cr();
1874   }
1875 
1876   return array;
1877 }
1878 
1879 #if COMPILER2_OR_JVMCI
1880 void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {
1881   // Reallocation of some scalar replaced objects failed. Record
1882   // that we need to pop all the interpreter frames for the
1883   // deoptimized compiled frame.
1884   assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");
1885   thread->set_frames_to_pop_failed_realloc(array->frames());
1886   // Unlock all monitors here otherwise the interpreter will see a
1887   // mix of locked and unlocked monitors (because of failed
1888   // reallocations of synchronized objects) and be confused.
1889   for (int i = 0; i < array->frames(); i++) {
1890     MonitorChunk* monitors = array->element(i)->monitors();
1891     if (monitors != nullptr) {
1892       // Unlock in reverse order starting from most nested monitor.
1893       for (int j = (monitors->number_of_monitors() - 1); j >= 0; j--) {
1894         BasicObjectLock* src = monitors->at(j);
1895         if (src->obj() != nullptr) {
1896           ObjectSynchronizer::exit(src->obj(), src->lock(), thread);
1897         }
1898       }
1899       array->element(i)->free_monitors();
1900 #ifdef ASSERT
1901       array->element(i)->set_removed_monitors();
1902 #endif
1903     }
1904   }
1905 }
1906 #endif
1907 
1908 void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) {
1909   assert(fr.can_be_deoptimized(), "checking frame type");
1910 
1911   gather_statistics(reason, Action_none, Bytecodes::_illegal);
1912 
1913   if (LogCompilation && xtty != nullptr) {
1914     nmethod* nm = fr.cb()->as_nmethod_or_null();
1915     assert(nm != nullptr, "only compiled methods can deopt");
1916 
1917     ttyLocker ttyl;
1918     xtty->begin_head("deoptimized thread='%zu' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));
1919     nm->log_identity(xtty);
1920     xtty->end_head();
1921     for (ScopeDesc* sd = nm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1922       xtty->begin_elem("jvms bci='%d'", sd->bci());
1923       xtty->method(sd->method());
1924       xtty->end_elem();
1925       if (sd->is_top())  break;
1926     }
1927     xtty->tail("deoptimized");
1928   }
1929 
1930   Continuation::notify_deopt(thread, fr.sp());
1931 
1932   // Patch the compiled method so that when execution returns to it we will
1933   // deopt the execution state and return to the interpreter.
1934   fr.deoptimize(thread);
1935 }
1936 
1937 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) {
1938   // Deoptimize only if the frame comes from compiled code.
1939   // Do not deoptimize the frame which is already patched
1940   // during the execution of the loops below.
1941   if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1942     return;
1943   }
1944   ResourceMark rm;
1945   deoptimize_single_frame(thread, fr, reason);
1946 }
1947 
1948 #if INCLUDE_JVMCI
1949 address Deoptimization::deoptimize_for_missing_exception_handler(nmethod* nm) {
1950   // there is no exception handler for this pc => deoptimize
1951   nm->make_not_entrant(nmethod::InvalidationReason::MISSING_EXCEPTION_HANDLER);
1952 
1953   // Use Deoptimization::deoptimize for all of its side-effects:
1954   // gathering traps statistics, logging...
1955   // it also patches the return pc but we do not care about that
1956   // since we return a continuation to the deopt_blob below.
1957   JavaThread* thread = JavaThread::current();
1958   RegisterMap reg_map(thread,
1959                       RegisterMap::UpdateMap::skip,
1960                       RegisterMap::ProcessFrames::include,
1961                       RegisterMap::WalkContinuation::skip);
1962   frame runtime_frame = thread->last_frame();
1963   frame caller_frame = runtime_frame.sender(&reg_map);
1964   assert(caller_frame.cb()->as_nmethod_or_null() == nm, "expect top frame compiled method");
1965   vframe* vf = vframe::new_vframe(&caller_frame, &reg_map, thread);
1966   compiledVFrame* cvf = compiledVFrame::cast(vf);
1967   ScopeDesc* imm_scope = cvf->scope();
1968   MethodData* imm_mdo = get_method_data(thread, methodHandle(thread, imm_scope->method()), true);
1969   if (imm_mdo != nullptr) {
1970     // Lock to read ProfileData, and ensure lock is not broken by a safepoint
1971     MutexLocker ml(imm_mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
1972 
1973     ProfileData* pdata = imm_mdo->allocate_bci_to_data(imm_scope->bci(), nullptr);
1974     if (pdata != nullptr && pdata->is_BitData()) {
1975       BitData* bit_data = (BitData*) pdata;
1976       bit_data->set_exception_seen();
1977     }
1978   }
1979 
1980   Deoptimization::deoptimize(thread, caller_frame, Deoptimization::Reason_not_compiled_exception_handler);
1981 
1982   MethodData* trap_mdo = get_method_data(thread, methodHandle(thread, nm->method()), true);
1983   if (trap_mdo != nullptr) {
1984     trap_mdo->inc_trap_count(Deoptimization::Reason_not_compiled_exception_handler);
1985   }
1986 
1987   return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
1988 }
1989 #endif
1990 
1991 void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id, DeoptReason reason) {
1992   assert(thread == Thread::current() ||
1993          thread->is_handshake_safe_for(Thread::current()) ||
1994          SafepointSynchronize::is_at_safepoint(),
1995          "can only deoptimize other thread at a safepoint/handshake");
1996   // Compute frame and register map based on thread and sp.
1997   RegisterMap reg_map(thread,
1998                       RegisterMap::UpdateMap::skip,
1999                       RegisterMap::ProcessFrames::include,
2000                       RegisterMap::WalkContinuation::skip);
2001   frame fr = thread->last_frame();
2002   while (fr.id() != id) {
2003     fr = fr.sender(&reg_map);
2004   }
2005   deoptimize(thread, fr, reason);
2006 }
2007 
2008 
2009 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id, DeoptReason reason) {
2010   Thread* current = Thread::current();
2011   if (thread == current || thread->is_handshake_safe_for(current)) {
2012     Deoptimization::deoptimize_frame_internal(thread, id, reason);
2013   } else {
2014     VM_DeoptimizeFrame deopt(thread, id, reason);
2015     VMThread::execute(&deopt);
2016   }
2017 }
2018 
2019 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {
2020   deoptimize_frame(thread, id, Reason_constraint);
2021 }
2022 
2023 // JVMTI PopFrame support
2024 JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))
2025 {
2026   assert(thread == JavaThread::current(), "pre-condition");
2027   thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);
2028 }
2029 JRT_END
2030 
2031 MethodData*
2032 Deoptimization::get_method_data(JavaThread* thread, const methodHandle& m,
2033                                 bool create_if_missing) {
2034   JavaThread* THREAD = thread; // For exception macros.
2035   MethodData* mdo = m()->method_data();
2036   if (mdo == nullptr && create_if_missing && !HAS_PENDING_EXCEPTION) {
2037     // Build an MDO.  Ignore errors like OutOfMemory;
2038     // that simply means we won't have an MDO to update.
2039     Method::build_profiling_method_data(m, THREAD);
2040     if (HAS_PENDING_EXCEPTION) {
2041       // Only metaspace OOM is expected. No Java code executed.
2042       assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), "we expect only an OOM error here");
2043       CLEAR_PENDING_EXCEPTION;
2044     }
2045     mdo = m()->method_data();
2046   }
2047   return mdo;
2048 }
2049 
2050 #if COMPILER2_OR_JVMCI
2051 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index, TRAPS) {
2052   // In case of an unresolved klass entry, load the class.
2053   // This path is exercised from case _ldc in Parse::do_one_bytecode,
2054   // and probably nowhere else.
2055   // Even that case would benefit from simply re-interpreting the
2056   // bytecode, without paying special attention to the class index.
2057   // So this whole "class index" feature should probably be removed.
2058 
2059   if (constant_pool->tag_at(index).is_unresolved_klass()) {
2060     Klass* tk = constant_pool->klass_at(index, THREAD);
2061     if (HAS_PENDING_EXCEPTION) {
2062       // Exception happened during classloading. We ignore the exception here, since it
2063       // is going to be rethrown since the current activation is going to be deoptimized and
2064       // the interpreter will re-execute the bytecode.
2065       // Do not clear probable Async Exceptions.
2066       CLEAR_PENDING_NONASYNC_EXCEPTION;
2067       // Class loading called java code which may have caused a stack
2068       // overflow. If the exception was thrown right before the return
2069       // to the runtime the stack is no longer guarded. Reguard the
2070       // stack otherwise if we return to the uncommon trap blob and the
2071       // stack bang causes a stack overflow we crash.
2072       JavaThread* jt = THREAD;
2073       bool guard_pages_enabled = jt->stack_overflow_state()->reguard_stack_if_needed();
2074       assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");
2075     }
2076     return;
2077   }
2078 
2079   assert(!constant_pool->tag_at(index).is_symbol(),
2080          "no symbolic names here, please");
2081 }
2082 
2083 #if INCLUDE_JFR
2084 
2085 class DeoptReasonSerializer : public JfrSerializer {
2086  public:
2087   void serialize(JfrCheckpointWriter& writer) {
2088     writer.write_count((u4)(Deoptimization::Reason_LIMIT + 1)); // + Reason::many (-1)
2089     for (int i = -1; i < Deoptimization::Reason_LIMIT; ++i) {
2090       writer.write_key((u8)i);
2091       writer.write(Deoptimization::trap_reason_name(i));
2092     }
2093   }
2094 };
2095 
2096 class DeoptActionSerializer : public JfrSerializer {
2097  public:
2098   void serialize(JfrCheckpointWriter& writer) {
2099     static const u4 nof_actions = Deoptimization::Action_LIMIT;
2100     writer.write_count(nof_actions);
2101     for (u4 i = 0; i < Deoptimization::Action_LIMIT; ++i) {
2102       writer.write_key(i);
2103       writer.write(Deoptimization::trap_action_name((int)i));
2104     }
2105   }
2106 };
2107 
2108 static void register_serializers() {
2109   static int critical_section = 0;
2110   if (1 == critical_section || Atomic::cmpxchg(&critical_section, 0, 1) == 1) {
2111     return;
2112   }
2113   JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONREASON, true, new DeoptReasonSerializer());
2114   JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONACTION, true, new DeoptActionSerializer());
2115 }
2116 
2117 static void post_deoptimization_event(nmethod* nm,
2118                                       const Method* method,
2119                                       int trap_bci,
2120                                       int instruction,
2121                                       Deoptimization::DeoptReason reason,
2122                                       Deoptimization::DeoptAction action) {
2123   assert(nm != nullptr, "invariant");
2124   assert(method != nullptr, "invariant");
2125   if (EventDeoptimization::is_enabled()) {
2126     static bool serializers_registered = false;
2127     if (!serializers_registered) {
2128       register_serializers();
2129       serializers_registered = true;
2130     }
2131     EventDeoptimization event;
2132     event.set_compileId(nm->compile_id());
2133     event.set_compiler(nm->compiler_type());
2134     event.set_method(method);
2135     event.set_lineNumber(method->line_number_from_bci(trap_bci));
2136     event.set_bci(trap_bci);
2137     event.set_instruction(instruction);
2138     event.set_reason(reason);
2139     event.set_action(action);
2140     event.commit();
2141   }
2142 }
2143 
2144 #endif // INCLUDE_JFR
2145 
2146 static void log_deopt(nmethod* nm, Method* tm, intptr_t pc, frame& fr, int trap_bci,
2147                               const char* reason_name, const char* reason_action) {
2148   LogTarget(Debug, deoptimization) lt;
2149   if (lt.is_enabled()) {
2150     LogStream ls(lt);
2151     bool is_osr = nm->is_osr_method();
2152     ls.print("cid=%4d %s level=%d",
2153              nm->compile_id(), (is_osr ? "osr" : "   "), nm->comp_level());
2154     ls.print(" %s", tm->name_and_sig_as_C_string());
2155     ls.print(" trap_bci=%d ", trap_bci);
2156     if (is_osr) {
2157       ls.print("osr_bci=%d ", nm->osr_entry_bci());
2158     }
2159     ls.print("%s ", reason_name);
2160     ls.print("%s ", reason_action);
2161     ls.print_cr("pc=" INTPTR_FORMAT " relative_pc=" INTPTR_FORMAT,
2162              pc, fr.pc() - nm->code_begin());
2163   }
2164 }
2165 
2166 JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* current, jint trap_request)) {
2167   HandleMark hm(current);
2168 
2169   // uncommon_trap() is called at the beginning of the uncommon trap
2170   // handler. Note this fact before we start generating temporary frames
2171   // that can confuse an asynchronous stack walker. This counter is
2172   // decremented at the end of unpack_frames().
2173 
2174   current->inc_in_deopt_handler();
2175 
2176 #if INCLUDE_JVMCI
2177   // JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid
2178   RegisterMap reg_map(current,
2179                       RegisterMap::UpdateMap::include,
2180                       RegisterMap::ProcessFrames::include,
2181                       RegisterMap::WalkContinuation::skip);
2182 #else
2183   RegisterMap reg_map(current,
2184                       RegisterMap::UpdateMap::skip,
2185                       RegisterMap::ProcessFrames::include,
2186                       RegisterMap::WalkContinuation::skip);
2187 #endif
2188   frame stub_frame = current->last_frame();
2189   frame fr = stub_frame.sender(&reg_map);
2190 
2191   // Log a message
2192   Events::log_deopt_message(current, "Uncommon trap: trap_request=" INT32_FORMAT_X_0 " fr.pc=" INTPTR_FORMAT " relative=" INTPTR_FORMAT,
2193               trap_request, p2i(fr.pc()), fr.pc() - fr.cb()->code_begin());
2194 
2195   {
2196     ResourceMark rm;
2197 
2198     DeoptReason reason = trap_request_reason(trap_request);
2199     DeoptAction action = trap_request_action(trap_request);
2200 #if INCLUDE_JVMCI
2201     int debug_id = trap_request_debug_id(trap_request);
2202 #endif
2203     jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1
2204 
2205     vframe*  vf  = vframe::new_vframe(&fr, &reg_map, current);
2206     compiledVFrame* cvf = compiledVFrame::cast(vf);
2207 
2208     nmethod* nm = cvf->code();
2209 
2210     ScopeDesc*      trap_scope  = cvf->scope();
2211 
2212     bool is_receiver_constraint_failure = COMPILER2_PRESENT(VerifyReceiverTypes &&) (reason == Deoptimization::Reason_receiver_constraint);
2213 
2214     if (is_receiver_constraint_failure) {
2215       tty->print_cr("  bci=%d pc=" INTPTR_FORMAT ", relative_pc=" INTPTR_FORMAT ", method=%s" JVMCI_ONLY(", debug_id=%d"),
2216                     trap_scope->bci(), p2i(fr.pc()), fr.pc() - nm->code_begin(), trap_scope->method()->name_and_sig_as_C_string()
2217                     JVMCI_ONLY(COMMA debug_id));
2218     }
2219 
2220     methodHandle    trap_method(current, trap_scope->method());
2221     int             trap_bci    = trap_scope->bci();
2222 #if INCLUDE_JVMCI
2223     jlong           speculation = current->pending_failed_speculation();
2224     if (nm->is_compiled_by_jvmci()) {
2225       nm->update_speculation(current);
2226     } else {
2227       assert(speculation == 0, "There should not be a speculation for methods compiled by non-JVMCI compilers");
2228     }
2229 
2230     if (trap_bci == SynchronizationEntryBCI) {
2231       trap_bci = 0;
2232       current->set_pending_monitorenter(true);
2233     }
2234 
2235     if (reason == Deoptimization::Reason_transfer_to_interpreter) {
2236       current->set_pending_transfer_to_interpreter(true);
2237     }
2238 #endif
2239 
2240     Bytecodes::Code trap_bc     = trap_method->java_code_at(trap_bci);
2241     // Record this event in the histogram.
2242     gather_statistics(reason, action, trap_bc);
2243 
2244     // Ensure that we can record deopt. history:
2245     bool create_if_missing = ProfileTraps;
2246 
2247     methodHandle profiled_method;
2248 #if INCLUDE_JVMCI
2249     if (nm->is_compiled_by_jvmci()) {
2250       profiled_method = methodHandle(current, nm->method());
2251     } else {
2252       profiled_method = trap_method;
2253     }
2254 #else
2255     profiled_method = trap_method;
2256 #endif
2257 
2258     MethodData* trap_mdo =
2259       get_method_data(current, profiled_method, create_if_missing);
2260 
2261     { // Log Deoptimization event for JFR, UL and event system
2262       Method* tm = trap_method();
2263       const char* reason_name = trap_reason_name(reason);
2264       const char* reason_action = trap_action_name(action);
2265       intptr_t pc = p2i(fr.pc());
2266 
2267       JFR_ONLY(post_deoptimization_event(nm, tm, trap_bci, trap_bc, reason, action);)
2268       log_deopt(nm, tm, pc, fr, trap_bci, reason_name, reason_action);
2269       Events::log_deopt_message(current, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d %s",
2270                                 reason_name, reason_action, pc,
2271                                 tm->name_and_sig_as_C_string(), trap_bci, nm->compiler_name());
2272     }
2273 
2274     // Print a bunch of diagnostics, if requested.
2275     if (TraceDeoptimization || LogCompilation || is_receiver_constraint_failure) {
2276       ResourceMark rm;
2277 
2278       // Lock to read ProfileData, and ensure lock is not broken by a safepoint
2279       // We must do this already now, since we cannot acquire this lock while
2280       // holding the tty lock (lock ordering by rank).
2281       MutexLocker ml(trap_mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
2282 
2283       ttyLocker ttyl;
2284 
2285       char buf[100];
2286       if (xtty != nullptr) {
2287         xtty->begin_head("uncommon_trap thread='%zu' %s",
2288                          os::current_thread_id(),
2289                          format_trap_request(buf, sizeof(buf), trap_request));
2290 #if INCLUDE_JVMCI
2291         if (speculation != 0) {
2292           xtty->print(" speculation='" JLONG_FORMAT "'", speculation);
2293         }
2294 #endif
2295         nm->log_identity(xtty);
2296       }
2297       Symbol* class_name = nullptr;
2298       bool unresolved = false;
2299       if (unloaded_class_index >= 0) {
2300         constantPoolHandle constants (current, trap_method->constants());
2301         if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {
2302           class_name = constants->klass_name_at(unloaded_class_index);
2303           unresolved = true;
2304           if (xtty != nullptr)
2305             xtty->print(" unresolved='1'");
2306         } else if (constants->tag_at(unloaded_class_index).is_symbol()) {
2307           class_name = constants->symbol_at(unloaded_class_index);
2308         }
2309         if (xtty != nullptr)
2310           xtty->name(class_name);
2311       }
2312       if (xtty != nullptr && trap_mdo != nullptr && (int)reason < (int)MethodData::_trap_hist_limit) {
2313         // Dump the relevant MDO state.
2314         // This is the deopt count for the current reason, any previous
2315         // reasons or recompiles seen at this point.
2316         int dcnt = trap_mdo->trap_count(reason);
2317         if (dcnt != 0)
2318           xtty->print(" count='%d'", dcnt);
2319 
2320         // We need to lock to read the ProfileData. But to keep the locks ordered, we need to
2321         // lock extra_data_lock before the tty lock.
2322         ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);
2323         int dos = (pdata == nullptr)? 0: pdata->trap_state();
2324         if (dos != 0) {
2325           xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));
2326           if (trap_state_is_recompiled(dos)) {
2327             int recnt2 = trap_mdo->overflow_recompile_count();
2328             if (recnt2 != 0)
2329               xtty->print(" recompiles2='%d'", recnt2);
2330           }
2331         }
2332       }
2333       if (xtty != nullptr) {
2334         xtty->stamp();
2335         xtty->end_head();
2336       }
2337       if (TraceDeoptimization) {  // make noise on the tty
2338         stringStream st;
2339         st.print("UNCOMMON TRAP method=%s", trap_scope->method()->name_and_sig_as_C_string());
2340         st.print("  bci=%d pc=" INTPTR_FORMAT ", relative_pc=" INTPTR_FORMAT JVMCI_ONLY(", debug_id=%d"),
2341                  trap_scope->bci(), p2i(fr.pc()), fr.pc() - nm->code_begin() JVMCI_ONLY(COMMA debug_id));
2342         st.print(" compiler=%s compile_id=%d", nm->compiler_name(), nm->compile_id());
2343 #if INCLUDE_JVMCI
2344         if (nm->is_compiled_by_jvmci()) {
2345           const char* installed_code_name = nm->jvmci_name();
2346           if (installed_code_name != nullptr) {
2347             st.print(" (JVMCI: installed code name=%s) ", installed_code_name);
2348           }
2349         }
2350 #endif
2351         st.print(" (@" INTPTR_FORMAT ") thread=%zu reason=%s action=%s unloaded_class_index=%d" JVMCI_ONLY(" debug_id=%d"),
2352                    p2i(fr.pc()),
2353                    os::current_thread_id(),
2354                    trap_reason_name(reason),
2355                    trap_action_name(action),
2356                    unloaded_class_index
2357 #if INCLUDE_JVMCI
2358                    , debug_id
2359 #endif
2360                    );
2361         if (class_name != nullptr) {
2362           st.print(unresolved ? " unresolved class: " : " symbol: ");
2363           class_name->print_symbol_on(&st);
2364         }
2365         st.cr();
2366         tty->print_raw(st.freeze());
2367       }
2368       if (xtty != nullptr) {
2369         // Log the precise location of the trap.
2370         for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {
2371           xtty->begin_elem("jvms bci='%d'", sd->bci());
2372           xtty->method(sd->method());
2373           xtty->end_elem();
2374           if (sd->is_top())  break;
2375         }
2376         xtty->tail("uncommon_trap");
2377       }
2378     }
2379     // (End diagnostic printout.)
2380 
2381     if (is_receiver_constraint_failure) {
2382       fatal("missing receiver type check");
2383     }
2384 
2385     // Load class if necessary
2386     if (unloaded_class_index >= 0) {
2387       constantPoolHandle constants(current, trap_method->constants());
2388       load_class_by_index(constants, unloaded_class_index, THREAD);
2389     }
2390 
2391     // Flush the nmethod if necessary and desirable.
2392     //
2393     // We need to avoid situations where we are re-flushing the nmethod
2394     // because of a hot deoptimization site.  Repeated flushes at the same
2395     // point need to be detected by the compiler and avoided.  If the compiler
2396     // cannot avoid them (or has a bug and "refuses" to avoid them), this
2397     // module must take measures to avoid an infinite cycle of recompilation
2398     // and deoptimization.  There are several such measures:
2399     //
2400     //   1. If a recompilation is ordered a second time at some site X
2401     //   and for the same reason R, the action is adjusted to 'reinterpret',
2402     //   to give the interpreter time to exercise the method more thoroughly.
2403     //   If this happens, the method's overflow_recompile_count is incremented.
2404     //
2405     //   2. If the compiler fails to reduce the deoptimization rate, then
2406     //   the method's overflow_recompile_count will begin to exceed the set
2407     //   limit PerBytecodeRecompilationCutoff.  If this happens, the action
2408     //   is adjusted to 'make_not_compilable', and the method is abandoned
2409     //   to the interpreter.  This is a performance hit for hot methods,
2410     //   but is better than a disastrous infinite cycle of recompilations.
2411     //   (Actually, only the method containing the site X is abandoned.)
2412     //
2413     //   3. In parallel with the previous measures, if the total number of
2414     //   recompilations of a method exceeds the much larger set limit
2415     //   PerMethodRecompilationCutoff, the method is abandoned.
2416     //   This should only happen if the method is very large and has
2417     //   many "lukewarm" deoptimizations.  The code which enforces this
2418     //   limit is elsewhere (class nmethod, class Method).
2419     //
2420     // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance
2421     // to recompile at each bytecode independently of the per-BCI cutoff.
2422     //
2423     // The decision to update code is up to the compiler, and is encoded
2424     // in the Action_xxx code.  If the compiler requests Action_none
2425     // no trap state is changed, no compiled code is changed, and the
2426     // computation suffers along in the interpreter.
2427     //
2428     // The other action codes specify various tactics for decompilation
2429     // and recompilation.  Action_maybe_recompile is the loosest, and
2430     // allows the compiled code to stay around until enough traps are seen,
2431     // and until the compiler gets around to recompiling the trapping method.
2432     //
2433     // The other actions cause immediate removal of the present code.
2434 
2435     // Traps caused by injected profile shouldn't pollute trap counts.
2436     bool injected_profile_trap = trap_method->has_injected_profile() &&
2437                                  (reason == Reason_intrinsic || reason == Reason_unreached);
2438 
2439     bool update_trap_state = (reason != Reason_tenured) && !injected_profile_trap;
2440     bool make_not_entrant = false;
2441     bool make_not_compilable = false;
2442     bool reprofile = false;
2443     switch (action) {
2444     case Action_none:
2445       // Keep the old code.
2446       update_trap_state = false;
2447       break;
2448     case Action_maybe_recompile:
2449       // Do not need to invalidate the present code, but we can
2450       // initiate another
2451       // Start compiler without (necessarily) invalidating the nmethod.
2452       // The system will tolerate the old code, but new code should be
2453       // generated when possible.
2454       break;
2455     case Action_reinterpret:
2456       // Go back into the interpreter for a while, and then consider
2457       // recompiling form scratch.
2458       make_not_entrant = true;
2459       // Reset invocation counter for outer most method.
2460       // This will allow the interpreter to exercise the bytecodes
2461       // for a while before recompiling.
2462       // By contrast, Action_make_not_entrant is immediate.
2463       //
2464       // Note that the compiler will track null_check, null_assert,
2465       // range_check, and class_check events and log them as if they
2466       // had been traps taken from compiled code.  This will update
2467       // the MDO trap history so that the next compilation will
2468       // properly detect hot trap sites.
2469       reprofile = true;
2470       break;
2471     case Action_make_not_entrant:
2472       // Request immediate recompilation, and get rid of the old code.
2473       // Make them not entrant, so next time they are called they get
2474       // recompiled.  Unloaded classes are loaded now so recompile before next
2475       // time they are called.  Same for uninitialized.  The interpreter will
2476       // link the missing class, if any.
2477       make_not_entrant = true;
2478       break;
2479     case Action_make_not_compilable:
2480       // Give up on compiling this method at all.
2481       make_not_entrant = true;
2482       make_not_compilable = true;
2483       break;
2484     default:
2485       ShouldNotReachHere();
2486     }
2487 
2488 #if INCLUDE_JVMCI
2489     // Deoptimization count is used by the CompileBroker to reason about compilations
2490     // it requests so do not pollute the count for deoptimizations in non-default (i.e.
2491     // non-CompilerBroker) compilations.
2492     if (nm->jvmci_skip_profile_deopt()) {
2493       update_trap_state = false;
2494     }
2495 #endif
2496     // Setting +ProfileTraps fixes the following, on all platforms:
2497     // The result is infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the
2498     // recompile relies on a MethodData* to record heroic opt failures.
2499 
2500     // Whether the interpreter is producing MDO data or not, we also need
2501     // to use the MDO to detect hot deoptimization points and control
2502     // aggressive optimization.
2503     bool inc_recompile_count = false;
2504 
2505     // Lock to read ProfileData, and ensure lock is not broken by a safepoint
2506     ConditionalMutexLocker ml((trap_mdo != nullptr) ? trap_mdo->extra_data_lock() : nullptr,
2507                               (trap_mdo != nullptr),
2508                               Mutex::_no_safepoint_check_flag);
2509     ProfileData* pdata = nullptr;
2510     if (ProfileTraps && CompilerConfig::is_c2_or_jvmci_compiler_enabled() && update_trap_state && trap_mdo != nullptr) {
2511       assert(trap_mdo == get_method_data(current, profiled_method, false), "sanity");
2512       uint this_trap_count = 0;
2513       bool maybe_prior_trap = false;
2514       bool maybe_prior_recompile = false;
2515 
2516       pdata = query_update_method_data(trap_mdo, trap_bci, reason, true,
2517 #if INCLUDE_JVMCI
2518                                    nm->is_compiled_by_jvmci() && nm->is_osr_method(),
2519 #endif
2520                                    nm->method(),
2521                                    //outputs:
2522                                    this_trap_count,
2523                                    maybe_prior_trap,
2524                                    maybe_prior_recompile);
2525       // Because the interpreter also counts null, div0, range, and class
2526       // checks, these traps from compiled code are double-counted.
2527       // This is harmless; it just means that the PerXTrapLimit values
2528       // are in effect a little smaller than they look.
2529 
2530       DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2531       if (per_bc_reason != Reason_none) {
2532         // Now take action based on the partially known per-BCI history.
2533         if (maybe_prior_trap
2534             && this_trap_count >= (uint)PerBytecodeTrapLimit) {
2535           // If there are too many traps at this BCI, force a recompile.
2536           // This will allow the compiler to see the limit overflow, and
2537           // take corrective action, if possible.  The compiler generally
2538           // does not use the exact PerBytecodeTrapLimit value, but instead
2539           // changes its tactics if it sees any traps at all.  This provides
2540           // a little hysteresis, delaying a recompile until a trap happens
2541           // several times.
2542           //
2543           // Actually, since there is only one bit of counter per BCI,
2544           // the possible per-BCI counts are {0,1,(per-method count)}.
2545           // This produces accurate results if in fact there is only
2546           // one hot trap site, but begins to get fuzzy if there are
2547           // many sites.  For example, if there are ten sites each
2548           // trapping two or more times, they each get the blame for
2549           // all of their traps.
2550           make_not_entrant = true;
2551         }
2552 
2553         // Detect repeated recompilation at the same BCI, and enforce a limit.
2554         if (make_not_entrant && maybe_prior_recompile) {
2555           // More than one recompile at this point.
2556           inc_recompile_count = maybe_prior_trap;
2557         }
2558       } else {
2559         // For reasons which are not recorded per-bytecode, we simply
2560         // force recompiles unconditionally.
2561         // (Note that PerMethodRecompilationCutoff is enforced elsewhere.)
2562         make_not_entrant = true;
2563       }
2564 
2565       // Go back to the compiler if there are too many traps in this method.
2566       if (this_trap_count >= per_method_trap_limit(reason)) {
2567         // If there are too many traps in this method, force a recompile.
2568         // This will allow the compiler to see the limit overflow, and
2569         // take corrective action, if possible.
2570         // (This condition is an unlikely backstop only, because the
2571         // PerBytecodeTrapLimit is more likely to take effect first,
2572         // if it is applicable.)
2573         make_not_entrant = true;
2574       }
2575 
2576       // Here's more hysteresis:  If there has been a recompile at
2577       // this trap point already, run the method in the interpreter
2578       // for a while to exercise it more thoroughly.
2579       if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {
2580         reprofile = true;
2581       }
2582     }
2583 
2584     // Take requested actions on the method:
2585 
2586     // Recompile
2587     if (make_not_entrant) {
2588       if (!nm->make_not_entrant(nmethod::InvalidationReason::UNCOMMON_TRAP)) {
2589         return; // the call did not change nmethod's state
2590       }
2591 
2592       if (pdata != nullptr) {
2593         // Record the recompilation event, if any.
2594         int tstate0 = pdata->trap_state();
2595         int tstate1 = trap_state_set_recompiled(tstate0, true);
2596         if (tstate1 != tstate0)
2597           pdata->set_trap_state(tstate1);
2598       }
2599 
2600       // For code aging we count traps separately here, using make_not_entrant()
2601       // as a guard against simultaneous deopts in multiple threads.
2602       if (reason == Reason_tenured && trap_mdo != nullptr) {
2603         trap_mdo->inc_tenure_traps();
2604       }
2605     }
2606     if (inc_recompile_count) {
2607       trap_mdo->inc_overflow_recompile_count();
2608       if ((uint)trap_mdo->overflow_recompile_count() >
2609           (uint)PerBytecodeRecompilationCutoff) {
2610         // Give up on the method containing the bad BCI.
2611         if (trap_method() == nm->method()) {
2612           make_not_compilable = true;
2613         } else {
2614           trap_method->set_not_compilable("overflow_recompile_count > PerBytecodeRecompilationCutoff", CompLevel_full_optimization);
2615           // But give grace to the enclosing nm->method().
2616         }
2617       }
2618     }
2619 
2620     // Reprofile
2621     if (reprofile) {
2622       CompilationPolicy::reprofile(trap_scope, nm->is_osr_method());
2623     }
2624 
2625     // Give up compiling
2626     if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {
2627       assert(make_not_entrant, "consistent");
2628       nm->method()->set_not_compilable("give up compiling", CompLevel_full_optimization);
2629     }
2630 
2631     if (ProfileExceptionHandlers && trap_mdo != nullptr) {
2632       BitData* exception_handler_data = trap_mdo->exception_handler_bci_to_data_or_null(trap_bci);
2633       if (exception_handler_data != nullptr) {
2634         // uncommon trap at the start of an exception handler.
2635         // C2 generates these for un-entered exception handlers.
2636         // mark the handler as entered to avoid generating
2637         // another uncommon trap the next time the handler is compiled
2638         exception_handler_data->set_exception_handler_entered();
2639       }
2640     }
2641 
2642   } // Free marked resources
2643 
2644 }
2645 JRT_END
2646 
2647 ProfileData*
2648 Deoptimization::query_update_method_data(MethodData* trap_mdo,
2649                                          int trap_bci,
2650                                          Deoptimization::DeoptReason reason,
2651                                          bool update_total_trap_count,
2652 #if INCLUDE_JVMCI
2653                                          bool is_osr,
2654 #endif
2655                                          Method* compiled_method,
2656                                          //outputs:
2657                                          uint& ret_this_trap_count,
2658                                          bool& ret_maybe_prior_trap,
2659                                          bool& ret_maybe_prior_recompile) {
2660   trap_mdo->check_extra_data_locked();
2661 
2662   bool maybe_prior_trap = false;
2663   bool maybe_prior_recompile = false;
2664   uint this_trap_count = 0;
2665   if (update_total_trap_count) {
2666     uint idx = reason;
2667 #if INCLUDE_JVMCI
2668     if (is_osr) {
2669       // Upper half of history array used for traps in OSR compilations
2670       idx += Reason_TRAP_HISTORY_LENGTH;
2671     }
2672 #endif
2673     uint prior_trap_count = trap_mdo->trap_count(idx);
2674     this_trap_count  = trap_mdo->inc_trap_count(idx);
2675 
2676     // If the runtime cannot find a place to store trap history,
2677     // it is estimated based on the general condition of the method.
2678     // If the method has ever been recompiled, or has ever incurred
2679     // a trap with the present reason , then this BCI is assumed
2680     // (pessimistically) to be the culprit.
2681     maybe_prior_trap      = (prior_trap_count != 0);
2682     maybe_prior_recompile = (trap_mdo->decompile_count() != 0);
2683   }
2684   ProfileData* pdata = nullptr;
2685 
2686 
2687   // For reasons which are recorded per bytecode, we check per-BCI data.
2688   DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2689   assert(per_bc_reason != Reason_none || update_total_trap_count, "must be");
2690   if (per_bc_reason != Reason_none) {
2691     // Find the profile data for this BCI.  If there isn't one,
2692     // try to allocate one from the MDO's set of spares.
2693     // This will let us detect a repeated trap at this point.
2694     pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : nullptr);
2695 
2696     if (pdata != nullptr) {
2697       if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {
2698         if (LogCompilation && xtty != nullptr) {
2699           ttyLocker ttyl;
2700           // no more room for speculative traps in this MDO
2701           xtty->elem("speculative_traps_oom");
2702         }
2703       }
2704       // Query the trap state of this profile datum.
2705       int tstate0 = pdata->trap_state();
2706       if (!trap_state_has_reason(tstate0, per_bc_reason))
2707         maybe_prior_trap = false;
2708       if (!trap_state_is_recompiled(tstate0))
2709         maybe_prior_recompile = false;
2710 
2711       // Update the trap state of this profile datum.
2712       int tstate1 = tstate0;
2713       // Record the reason.
2714       tstate1 = trap_state_add_reason(tstate1, per_bc_reason);
2715       // Store the updated state on the MDO, for next time.
2716       if (tstate1 != tstate0)
2717         pdata->set_trap_state(tstate1);
2718     } else {
2719       if (LogCompilation && xtty != nullptr) {
2720         ttyLocker ttyl;
2721         // Missing MDP?  Leave a small complaint in the log.
2722         xtty->elem("missing_mdp bci='%d'", trap_bci);
2723       }
2724     }
2725   }
2726 
2727   // Return results:
2728   ret_this_trap_count = this_trap_count;
2729   ret_maybe_prior_trap = maybe_prior_trap;
2730   ret_maybe_prior_recompile = maybe_prior_recompile;
2731   return pdata;
2732 }
2733 
2734 void
2735 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2736   ResourceMark rm;
2737   // Ignored outputs:
2738   uint ignore_this_trap_count;
2739   bool ignore_maybe_prior_trap;
2740   bool ignore_maybe_prior_recompile;
2741   assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
2742   // JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts
2743   bool update_total_counts = true JVMCI_ONLY( && !UseJVMCICompiler);
2744 
2745   // Lock to read ProfileData, and ensure lock is not broken by a safepoint
2746   MutexLocker ml(trap_mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
2747 
2748   query_update_method_data(trap_mdo, trap_bci,
2749                            (DeoptReason)reason,
2750                            update_total_counts,
2751 #if INCLUDE_JVMCI
2752                            false,
2753 #endif
2754                            nullptr,
2755                            ignore_this_trap_count,
2756                            ignore_maybe_prior_trap,
2757                            ignore_maybe_prior_recompile);
2758 }
2759 
2760 Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* current, jint trap_request, jint exec_mode) {
2761   // Enable WXWrite: current function is called from methods compiled by C2 directly
2762   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
2763 
2764   // Still in Java no safepoints
2765   {
2766     // This enters VM and may safepoint
2767     uncommon_trap_inner(current, trap_request);
2768   }
2769   HandleMark hm(current);
2770   return fetch_unroll_info_helper(current, exec_mode);
2771 }
2772 
2773 // Local derived constants.
2774 // Further breakdown of DataLayout::trap_state, as promised by DataLayout.
2775 const int DS_REASON_MASK   = ((uint)DataLayout::trap_mask) >> 1;
2776 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
2777 
2778 //---------------------------trap_state_reason---------------------------------
2779 Deoptimization::DeoptReason
2780 Deoptimization::trap_state_reason(int trap_state) {
2781   // This assert provides the link between the width of DataLayout::trap_bits
2782   // and the encoding of "recorded" reasons.  It ensures there are enough
2783   // bits to store all needed reasons in the per-BCI MDO profile.
2784   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2785   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2786   trap_state -= recompile_bit;
2787   if (trap_state == DS_REASON_MASK) {
2788     return Reason_many;
2789   } else {
2790     assert((int)Reason_none == 0, "state=0 => Reason_none");
2791     return (DeoptReason)trap_state;
2792   }
2793 }
2794 //-------------------------trap_state_has_reason-------------------------------
2795 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2796   assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");
2797   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2798   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2799   trap_state -= recompile_bit;
2800   if (trap_state == DS_REASON_MASK) {
2801     return -1;  // true, unspecifically (bottom of state lattice)
2802   } else if (trap_state == reason) {
2803     return 1;   // true, definitely
2804   } else if (trap_state == 0) {
2805     return 0;   // false, definitely (top of state lattice)
2806   } else {
2807     return 0;   // false, definitely
2808   }
2809 }
2810 //-------------------------trap_state_add_reason-------------------------------
2811 int Deoptimization::trap_state_add_reason(int trap_state, int reason) {
2812   assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");
2813   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2814   trap_state -= recompile_bit;
2815   if (trap_state == DS_REASON_MASK) {
2816     return trap_state + recompile_bit;     // already at state lattice bottom
2817   } else if (trap_state == reason) {
2818     return trap_state + recompile_bit;     // the condition is already true
2819   } else if (trap_state == 0) {
2820     return reason + recompile_bit;          // no condition has yet been true
2821   } else {
2822     return DS_REASON_MASK + recompile_bit;  // fall to state lattice bottom
2823   }
2824 }
2825 //-----------------------trap_state_is_recompiled------------------------------
2826 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2827   return (trap_state & DS_RECOMPILE_BIT) != 0;
2828 }
2829 //-----------------------trap_state_set_recompiled-----------------------------
2830 int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {
2831   if (z)  return trap_state |  DS_RECOMPILE_BIT;
2832   else    return trap_state & ~DS_RECOMPILE_BIT;
2833 }
2834 //---------------------------format_trap_state---------------------------------
2835 // This is used for debugging and diagnostics, including LogFile output.
2836 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2837                                               int trap_state) {
2838   assert(buflen > 0, "sanity");
2839   DeoptReason reason      = trap_state_reason(trap_state);
2840   bool        recomp_flag = trap_state_is_recompiled(trap_state);
2841   // Re-encode the state from its decoded components.
2842   int decoded_state = 0;
2843   if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)
2844     decoded_state = trap_state_add_reason(decoded_state, reason);
2845   if (recomp_flag)
2846     decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);
2847   // If the state re-encodes properly, format it symbolically.
2848   // Because this routine is used for debugging and diagnostics,
2849   // be robust even if the state is a strange value.
2850   size_t len;
2851   if (decoded_state != trap_state) {
2852     // Random buggy state that doesn't decode??
2853     len = jio_snprintf(buf, buflen, "#%d", trap_state);
2854   } else {
2855     len = jio_snprintf(buf, buflen, "%s%s",
2856                        trap_reason_name(reason),
2857                        recomp_flag ? " recompiled" : "");
2858   }
2859   return buf;
2860 }
2861 
2862 
2863 //--------------------------------statics--------------------------------------
2864 const char* Deoptimization::_trap_reason_name[] = {
2865   // Note:  Keep this in sync. with enum DeoptReason.
2866   "none",
2867   "null_check",
2868   "null_assert" JVMCI_ONLY("_or_unreached0"),
2869   "range_check",
2870   "class_check",
2871   "array_check",
2872   "intrinsic" JVMCI_ONLY("_or_type_checked_inlining"),
2873   "bimorphic" JVMCI_ONLY("_or_optimized_type_check"),
2874   "profile_predicate",
2875   "auto_vectorization_check",
2876   "unloaded",
2877   "uninitialized",
2878   "initialized",
2879   "unreached",
2880   "unhandled",
2881   "constraint",
2882   "div0_check",
2883   "age",
2884   "predicate",
2885   "loop_limit_check",
2886   "speculate_class_check",
2887   "speculate_null_check",
2888   "speculate_null_assert",
2889   "unstable_if",
2890   "unstable_fused_if",
2891   "receiver_constraint",
2892   "short_running_loop" JVMCI_ONLY("_or_aliasing"),
2893 #if INCLUDE_JVMCI
2894   "transfer_to_interpreter",
2895   "not_compiled_exception_handler",
2896   "unresolved",
2897   "jsr_mismatch",
2898 #endif
2899   "tenured"
2900 };
2901 const char* Deoptimization::_trap_action_name[] = {
2902   // Note:  Keep this in sync. with enum DeoptAction.
2903   "none",
2904   "maybe_recompile",
2905   "reinterpret",
2906   "make_not_entrant",
2907   "make_not_compilable"
2908 };
2909 
2910 const char* Deoptimization::trap_reason_name(int reason) {
2911   // Check that every reason has a name
2912   STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT);
2913 
2914   if (reason == Reason_many)  return "many";
2915   if ((uint)reason < Reason_LIMIT)
2916     return _trap_reason_name[reason];
2917   static char buf[20];
2918   os::snprintf_checked(buf, sizeof(buf), "reason%d", reason);
2919   return buf;
2920 }
2921 const char* Deoptimization::trap_action_name(int action) {
2922   // Check that every action has a name
2923   STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT);
2924 
2925   if ((uint)action < Action_LIMIT)
2926     return _trap_action_name[action];
2927   static char buf[20];
2928   os::snprintf_checked(buf, sizeof(buf), "action%d", action);
2929   return buf;
2930 }
2931 
2932 // This is used for debugging and diagnostics, including LogFile output.
2933 const char* Deoptimization::format_trap_request(char* buf, size_t buflen,
2934                                                 int trap_request) {
2935   jint unloaded_class_index = trap_request_index(trap_request);
2936   const char* reason = trap_reason_name(trap_request_reason(trap_request));
2937   const char* action = trap_action_name(trap_request_action(trap_request));
2938 #if INCLUDE_JVMCI
2939   int debug_id = trap_request_debug_id(trap_request);
2940 #endif
2941   size_t len;
2942   if (unloaded_class_index < 0) {
2943     len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"),
2944                        reason, action
2945 #if INCLUDE_JVMCI
2946                        ,debug_id
2947 #endif
2948                        );
2949   } else {
2950     len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"),
2951                        reason, action, unloaded_class_index
2952 #if INCLUDE_JVMCI
2953                        ,debug_id
2954 #endif
2955                        );
2956   }
2957   return buf;
2958 }
2959 
2960 juint Deoptimization::_deoptimization_hist
2961         [Deoptimization::Reason_LIMIT]
2962     [1 + Deoptimization::Action_LIMIT]
2963         [Deoptimization::BC_CASE_LIMIT]
2964   = {0};
2965 
2966 enum {
2967   LSB_BITS = 8,
2968   LSB_MASK = right_n_bits(LSB_BITS)
2969 };
2970 
2971 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2972                                        Bytecodes::Code bc) {
2973   assert(reason >= 0 && reason < Reason_LIMIT, "oob");
2974   assert(action >= 0 && action < Action_LIMIT, "oob");
2975   _deoptimization_hist[Reason_none][0][0] += 1;  // total
2976   _deoptimization_hist[reason][0][0]      += 1;  // per-reason total
2977   juint* cases = _deoptimization_hist[reason][1+action];
2978   juint* bc_counter_addr = nullptr;
2979   juint  bc_counter      = 0;
2980   // Look for an unused counter, or an exact match to this BC.
2981   if (bc != Bytecodes::_illegal) {
2982     for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2983       juint* counter_addr = &cases[bc_case];
2984       juint  counter = *counter_addr;
2985       if ((counter == 0 && bc_counter_addr == nullptr)
2986           || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
2987         // this counter is either free or is already devoted to this BC
2988         bc_counter_addr = counter_addr;
2989         bc_counter = counter | bc;
2990       }
2991     }
2992   }
2993   if (bc_counter_addr == nullptr) {
2994     // Overflow, or no given bytecode.
2995     bc_counter_addr = &cases[BC_CASE_LIMIT-1];
2996     bc_counter = (*bc_counter_addr & ~LSB_MASK);  // clear LSB
2997   }
2998   *bc_counter_addr = bc_counter + (1 << LSB_BITS);
2999 }
3000 
3001 jint Deoptimization::total_deoptimization_count() {
3002   return _deoptimization_hist[Reason_none][0][0];
3003 }
3004 
3005 // Get the deopt count for a specific reason and a specific action. If either
3006 // one of 'reason' or 'action' is null, the method returns the sum of all
3007 // deoptimizations with the specific 'action' or 'reason' respectively.
3008 // If both arguments are null, the method returns the total deopt count.
3009 jint Deoptimization::deoptimization_count(const char *reason_str, const char *action_str) {
3010   if (reason_str == nullptr && action_str == nullptr) {
3011     return total_deoptimization_count();
3012   }
3013   juint counter = 0;
3014   for (int reason = 0; reason < Reason_LIMIT; reason++) {
3015     if (reason_str == nullptr || !strcmp(reason_str, trap_reason_name(reason))) {
3016       for (int action = 0; action < Action_LIMIT; action++) {
3017         if (action_str == nullptr || !strcmp(action_str, trap_action_name(action))) {
3018           juint* cases = _deoptimization_hist[reason][1+action];
3019           for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
3020             counter += cases[bc_case] >> LSB_BITS;
3021           }
3022         }
3023       }
3024     }
3025   }
3026   return counter;
3027 }
3028 
3029 void Deoptimization::print_statistics() {
3030   juint total = total_deoptimization_count();
3031   juint account = total;
3032   if (total != 0) {
3033     ttyLocker ttyl;
3034     if (xtty != nullptr)  xtty->head("statistics type='deoptimization'");
3035     tty->print_cr("Deoptimization traps recorded:");
3036     #define PRINT_STAT_LINE(name, r) \
3037       tty->print_cr("  %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
3038     PRINT_STAT_LINE("total", total);
3039     // For each non-zero entry in the histogram, print the reason,
3040     // the action, and (if specifically known) the type of bytecode.
3041     for (int reason = 0; reason < Reason_LIMIT; reason++) {
3042       for (int action = 0; action < Action_LIMIT; action++) {
3043         juint* cases = _deoptimization_hist[reason][1+action];
3044         for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
3045           juint counter = cases[bc_case];
3046           if (counter != 0) {
3047             char name[1*K];
3048             Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
3049             if (bc_case == BC_CASE_LIMIT && (int)bc == 0)
3050               bc = Bytecodes::_illegal;
3051             os::snprintf_checked(name, sizeof(name), "%s/%s/%s",
3052                     trap_reason_name(reason),
3053                     trap_action_name(action),
3054                     Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
3055             juint r = counter >> LSB_BITS;
3056             tty->print_cr("  %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);
3057             account -= r;
3058           }
3059         }
3060       }
3061     }
3062     if (account != 0) {
3063       PRINT_STAT_LINE("unaccounted", account);
3064     }
3065     #undef PRINT_STAT_LINE
3066     if (xtty != nullptr)  xtty->tail("statistics");
3067   }
3068 }
3069 
3070 #else // COMPILER2_OR_JVMCI
3071 
3072 
3073 // Stubs for C1 only system.
3074 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
3075   return false;
3076 }
3077 
3078 const char* Deoptimization::trap_reason_name(int reason) {
3079   return "unknown";
3080 }
3081 
3082 jint Deoptimization::total_deoptimization_count() {
3083   return 0;
3084 }
3085 
3086 jint Deoptimization::deoptimization_count(const char *reason_str, const char *action_str) {
3087   return 0;
3088 }
3089 
3090 void Deoptimization::print_statistics() {
3091   // no output
3092 }
3093 
3094 void
3095 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
3096   // no update
3097 }
3098 
3099 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
3100   return 0;
3101 }
3102 
3103 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
3104                                        Bytecodes::Code bc) {
3105   // no update
3106 }
3107 
3108 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
3109                                               int trap_state) {
3110   jio_snprintf(buf, buflen, "#%d", trap_state);
3111   return buf;
3112 }
3113 
3114 #endif // COMPILER2_OR_JVMCI