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