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