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