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