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