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