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