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