1 /*
   2  * Copyright (c) 2015, 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 "code/compiledIC.hpp"
  27 #include "code/compiledMethod.inline.hpp"
  28 #include "code/exceptionHandlerTable.hpp"
  29 #include "code/scopeDesc.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "code/icBuffer.hpp"
  32 #include "gc/shared/barrierSet.hpp"
  33 #include "gc/shared/barrierSetNMethod.hpp"
  34 #include "gc/shared/gcBehaviours.hpp"
  35 #include "interpreter/bytecode.inline.hpp"
  36 #include "logging/log.hpp"
  37 #include "logging/logTag.hpp"
  38 #include "memory/resourceArea.hpp"
  39 #include "oops/methodData.hpp"
  40 #include "oops/method.inline.hpp"
  41 #include "prims/methodHandles.hpp"
  42 #include "runtime/atomic.hpp"
  43 #include "runtime/deoptimization.hpp"
  44 #include "runtime/handles.inline.hpp"
  45 #include "runtime/mutexLocker.hpp"
  46 #include "runtime/sharedRuntime.hpp"
  47 
  48 CompiledMethod::CompiledMethod(Method* method, const char* name, CompilerType type, const CodeBlobLayout& layout,
  49                                int frame_complete_offset, int frame_size, ImmutableOopMapSet* oop_maps,
  50                                bool caller_must_gc_arguments)
  51   : CodeBlob(name, type, layout, frame_complete_offset, frame_size, oop_maps, caller_must_gc_arguments),
  52     _mark_for_deoptimization_status(not_marked),
  53     _method(method),
  54     _gc_data(NULL)
  55 {
  56   init_defaults();
  57 }
  58 
  59 CompiledMethod::CompiledMethod(Method* method, const char* name, CompilerType type, int size,
  60                                int header_size, CodeBuffer* cb, int frame_complete_offset, int frame_size,
  61                                OopMapSet* oop_maps, bool caller_must_gc_arguments)
  62   : CodeBlob(name, type, CodeBlobLayout((address) this, size, header_size, cb), cb,
  63              frame_complete_offset, frame_size, oop_maps, caller_must_gc_arguments),
  64     _mark_for_deoptimization_status(not_marked),
  65     _method(method),
  66     _gc_data(NULL)
  67 {
  68   init_defaults();
  69 }
  70 
  71 void CompiledMethod::init_defaults() {
  72   { // avoid uninitialized fields, even for short time periods
  73     _is_far_code                = false;
  74     _scopes_data_begin          = NULL;
  75     _deopt_handler_begin        = NULL;
  76     _deopt_mh_handler_begin     = NULL;
  77     _exception_cache            = NULL;
  78   }
  79   _has_unsafe_access          = 0;
  80   _has_method_handle_invokes  = 0;
  81   _lazy_critical_native       = 0;
  82   _has_wide_vectors           = 0;
  83 }
  84 
  85 bool CompiledMethod::is_method_handle_return(address return_pc) {
  86   if (!has_method_handle_invokes())  return false;
  87   PcDesc* pd = pc_desc_at(return_pc);
  88   if (pd == NULL)
  89     return false;
  90   return pd->is_method_handle_invoke();
  91 }
  92 
  93 // Returns a string version of the method state.
  94 const char* CompiledMethod::state() const {
  95   int state = get_state();
  96   switch (state) {
  97   case not_installed:
  98     return "not installed";
  99   case in_use:
 100     return "in use";
 101   case not_used:
 102     return "not_used";
 103   case not_entrant:
 104     return "not_entrant";
 105   case zombie:
 106     return "zombie";
 107   case unloaded:
 108     return "unloaded";
 109   default:
 110     fatal("unexpected method state: %d", state);
 111     return NULL;
 112   }
 113 }
 114 
 115 //-----------------------------------------------------------------------------
 116 void CompiledMethod::mark_for_deoptimization(bool inc_recompile_counts) {
 117   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,
 118                  Mutex::_no_safepoint_check_flag);
 119   _mark_for_deoptimization_status = (inc_recompile_counts ? deoptimize : deoptimize_noupdate);
 120 }
 121 
 122 //-----------------------------------------------------------------------------
 123 
 124 ExceptionCache* CompiledMethod::exception_cache_acquire() const {
 125   return Atomic::load_acquire(&_exception_cache);
 126 }
 127 
 128 void CompiledMethod::add_exception_cache_entry(ExceptionCache* new_entry) {
 129   assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock");
 130   assert(new_entry != NULL,"Must be non null");
 131   assert(new_entry->next() == NULL, "Must be null");
 132 
 133   for (;;) {
 134     ExceptionCache *ec = exception_cache();
 135     if (ec != NULL) {
 136       Klass* ex_klass = ec->exception_type();
 137       if (!ex_klass->is_loader_alive()) {
 138         // We must guarantee that entries are not inserted with new next pointer
 139         // edges to ExceptionCache entries with dead klasses, due to bad interactions
 140         // with concurrent ExceptionCache cleanup. Therefore, the inserts roll
 141         // the head pointer forward to the first live ExceptionCache, so that the new
 142         // next pointers always point at live ExceptionCaches, that are not removed due
 143         // to concurrent ExceptionCache cleanup.
 144         ExceptionCache* next = ec->next();
 145         if (Atomic::cmpxchg(&_exception_cache, ec, next) == ec) {
 146           CodeCache::release_exception_cache(ec);
 147         }
 148         continue;
 149       }
 150       ec = exception_cache();
 151       if (ec != NULL) {
 152         new_entry->set_next(ec);
 153       }
 154     }
 155     if (Atomic::cmpxchg(&_exception_cache, ec, new_entry) == ec) {
 156       return;
 157     }
 158   }
 159 }
 160 
 161 void CompiledMethod::clean_exception_cache() {
 162   // For each nmethod, only a single thread may call this cleanup function
 163   // at the same time, whether called in STW cleanup or concurrent cleanup.
 164   // Note that if the GC is processing exception cache cleaning in a concurrent phase,
 165   // then a single writer may contend with cleaning up the head pointer to the
 166   // first ExceptionCache node that has a Klass* that is alive. That is fine,
 167   // as long as there is no concurrent cleanup of next pointers from concurrent writers.
 168   // And the concurrent writers do not clean up next pointers, only the head.
 169   // Also note that concurent readers will walk through Klass* pointers that are not
 170   // alive. That does not cause ABA problems, because Klass* is deleted after
 171   // a handshake with all threads, after all stale ExceptionCaches have been
 172   // unlinked. That is also when the CodeCache::exception_cache_purge_list()
 173   // is deleted, with all ExceptionCache entries that were cleaned concurrently.
 174   // That similarly implies that CAS operations on ExceptionCache entries do not
 175   // suffer from ABA problems as unlinking and deletion is separated by a global
 176   // handshake operation.
 177   ExceptionCache* prev = NULL;
 178   ExceptionCache* curr = exception_cache_acquire();
 179 
 180   while (curr != NULL) {
 181     ExceptionCache* next = curr->next();
 182 
 183     if (!curr->exception_type()->is_loader_alive()) {
 184       if (prev == NULL) {
 185         // Try to clean head; this is contended by concurrent inserts, that
 186         // both lazily clean the head, and insert entries at the head. If
 187         // the CAS fails, the operation is restarted.
 188         if (Atomic::cmpxchg(&_exception_cache, curr, next) != curr) {
 189           prev = NULL;
 190           curr = exception_cache_acquire();
 191           continue;
 192         }
 193       } else {
 194         // It is impossible to during cleanup connect the next pointer to
 195         // an ExceptionCache that has not been published before a safepoint
 196         // prior to the cleanup. Therefore, release is not required.
 197         prev->set_next(next);
 198       }
 199       // prev stays the same.
 200 
 201       CodeCache::release_exception_cache(curr);
 202     } else {
 203       prev = curr;
 204     }
 205 
 206     curr = next;
 207   }
 208 }
 209 
 210 // public method for accessing the exception cache
 211 // These are the public access methods.
 212 address CompiledMethod::handler_for_exception_and_pc(Handle exception, address pc) {
 213   // We never grab a lock to read the exception cache, so we may
 214   // have false negatives. This is okay, as it can only happen during
 215   // the first few exception lookups for a given nmethod.
 216   ExceptionCache* ec = exception_cache_acquire();
 217   while (ec != NULL) {
 218     address ret_val;
 219     if ((ret_val = ec->match(exception,pc)) != NULL) {
 220       return ret_val;
 221     }
 222     ec = ec->next();
 223   }
 224   return NULL;
 225 }
 226 
 227 void CompiledMethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) {
 228   // There are potential race conditions during exception cache updates, so we
 229   // must own the ExceptionCache_lock before doing ANY modifications. Because
 230   // we don't lock during reads, it is possible to have several threads attempt
 231   // to update the cache with the same data. We need to check for already inserted
 232   // copies of the current data before adding it.
 233 
 234   MutexLocker ml(ExceptionCache_lock);
 235   ExceptionCache* target_entry = exception_cache_entry_for_exception(exception);
 236 
 237   if (target_entry == NULL || !target_entry->add_address_and_handler(pc,handler)) {
 238     target_entry = new ExceptionCache(exception,pc,handler);
 239     add_exception_cache_entry(target_entry);
 240   }
 241 }
 242 
 243 // private method for handling exception cache
 244 // These methods are private, and used to manipulate the exception cache
 245 // directly.
 246 ExceptionCache* CompiledMethod::exception_cache_entry_for_exception(Handle exception) {
 247   ExceptionCache* ec = exception_cache_acquire();
 248   while (ec != NULL) {
 249     if (ec->match_exception_with_space(exception)) {
 250       return ec;
 251     }
 252     ec = ec->next();
 253   }
 254   return NULL;
 255 }
 256 
 257 //-------------end of code for ExceptionCache--------------
 258 
 259 bool CompiledMethod::is_at_poll_return(address pc) {
 260   RelocIterator iter(this, pc, pc+1);
 261   while (iter.next()) {
 262     if (iter.type() == relocInfo::poll_return_type)
 263       return true;
 264   }
 265   return false;
 266 }
 267 
 268 
 269 bool CompiledMethod::is_at_poll_or_poll_return(address pc) {
 270   RelocIterator iter(this, pc, pc+1);
 271   while (iter.next()) {
 272     relocInfo::relocType t = iter.type();
 273     if (t == relocInfo::poll_return_type || t == relocInfo::poll_type)
 274       return true;
 275   }
 276   return false;
 277 }
 278 
 279 void CompiledMethod::verify_oop_relocations() {
 280   // Ensure sure that the code matches the current oop values
 281   RelocIterator iter(this, NULL, NULL);
 282   while (iter.next()) {
 283     if (iter.type() == relocInfo::oop_type) {
 284       oop_Relocation* reloc = iter.oop_reloc();
 285       if (!reloc->oop_is_immediate()) {
 286         reloc->verify_oop_relocation();
 287       }
 288     }
 289   }
 290 }
 291 
 292 
 293 ScopeDesc* CompiledMethod::scope_desc_at(address pc) {
 294   PcDesc* pd = pc_desc_at(pc);
 295   guarantee(pd != NULL, "scope must be present");
 296   return new ScopeDesc(this, pd->scope_decode_offset(),
 297                        pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(),
 298                        pd->return_oop());
 299 }
 300 
 301 ScopeDesc* CompiledMethod::scope_desc_near(address pc) {
 302   PcDesc* pd = pc_desc_near(pc);
 303   guarantee(pd != NULL, "scope must be present");
 304   return new ScopeDesc(this, pd->scope_decode_offset(),
 305                        pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(),
 306                        pd->return_oop());
 307 }
 308 
 309 address CompiledMethod::oops_reloc_begin() const {
 310   // If the method is not entrant or zombie then a JMP is plastered over the
 311   // first few bytes.  If an oop in the old code was there, that oop
 312   // should not get GC'd.  Skip the first few bytes of oops on
 313   // not-entrant methods.
 314   if (frame_complete_offset() != CodeOffsets::frame_never_safe &&
 315       code_begin() + frame_complete_offset() >
 316       verified_entry_point() + NativeJump::instruction_size)
 317   {
 318     // If we have a frame_complete_offset after the native jump, then there
 319     // is no point trying to look for oops before that. This is a requirement
 320     // for being allowed to scan oops concurrently.
 321     return code_begin() + frame_complete_offset();
 322   }
 323 
 324   // It is not safe to read oops concurrently using entry barriers, if their
 325   // location depend on whether the nmethod is entrant or not.
 326   assert(BarrierSet::barrier_set()->barrier_set_nmethod() == NULL, "Not safe oop scan");
 327 
 328   address low_boundary = verified_entry_point();
 329   if (!is_in_use() && is_nmethod()) {
 330     low_boundary += NativeJump::instruction_size;
 331     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
 332     // This means that the low_boundary is going to be a little too high.
 333     // This shouldn't matter, since oops of non-entrant methods are never used.
 334     // In fact, why are we bothering to look at oops in a non-entrant method??
 335   }
 336   return low_boundary;
 337 }
 338 
 339 int CompiledMethod::verify_icholder_relocations() {
 340   ResourceMark rm;
 341   int count = 0;
 342 
 343   RelocIterator iter(this);
 344   while(iter.next()) {
 345     if (iter.type() == relocInfo::virtual_call_type) {
 346       if (CompiledIC::is_icholder_call_site(iter.virtual_call_reloc(), this)) {
 347         CompiledIC *ic = CompiledIC_at(&iter);
 348         if (TraceCompiledIC) {
 349           tty->print("noticed icholder " INTPTR_FORMAT " ", p2i(ic->cached_icholder()));
 350           ic->print();
 351         }
 352         assert(ic->cached_icholder() != NULL, "must be non-NULL");
 353         count++;
 354       }
 355     }
 356   }
 357 
 358   return count;
 359 }
 360 
 361 // Method that knows how to preserve outgoing arguments at call. This method must be
 362 // called with a frame corresponding to a Java invoke
 363 void CompiledMethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
 364   if (method() != NULL && !method()->is_native()) {
 365     address pc = fr.pc();
 366     SimpleScopeDesc ssd(this, pc);
 367     Bytecode_invoke call(methodHandle(Thread::current(), ssd.method()), ssd.bci());
 368     bool has_receiver = call.has_receiver();
 369     bool has_appendix = call.has_appendix();
 370     Symbol* signature = call.signature();
 371 
 372     // The method attached by JIT-compilers should be used, if present.
 373     // Bytecode can be inaccurate in such case.
 374     Method* callee = attached_method_before_pc(pc);
 375     if (callee != NULL) {
 376       has_receiver = !(callee->access_flags().is_static());
 377       has_appendix = false;
 378       signature = callee->signature();
 379     }
 380 
 381     fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
 382   }
 383 }
 384 
 385 Method* CompiledMethod::attached_method(address call_instr) {
 386   assert(code_contains(call_instr), "not part of the nmethod");
 387   RelocIterator iter(this, call_instr, call_instr + 1);
 388   while (iter.next()) {
 389     if (iter.addr() == call_instr) {
 390       switch(iter.type()) {
 391         case relocInfo::static_call_type:      return iter.static_call_reloc()->method_value();
 392         case relocInfo::opt_virtual_call_type: return iter.opt_virtual_call_reloc()->method_value();
 393         case relocInfo::virtual_call_type:     return iter.virtual_call_reloc()->method_value();
 394         default:                               break;
 395       }
 396     }
 397   }
 398   return NULL; // not found
 399 }
 400 
 401 Method* CompiledMethod::attached_method_before_pc(address pc) {
 402   if (NativeCall::is_call_before(pc)) {
 403     NativeCall* ncall = nativeCall_before(pc);
 404     return attached_method(ncall->instruction_address());
 405   }
 406   return NULL; // not a call
 407 }
 408 
 409 void CompiledMethod::clear_inline_caches() {
 410   assert(SafepointSynchronize::is_at_safepoint(), "cleaning of IC's only allowed at safepoint");
 411   if (is_zombie()) {
 412     return;
 413   }
 414 
 415   RelocIterator iter(this);
 416   while (iter.next()) {
 417     iter.reloc()->clear_inline_cache();
 418   }
 419 }
 420 
 421 // Clear IC callsites, releasing ICStubs of all compiled ICs
 422 // as well as any associated CompiledICHolders.
 423 void CompiledMethod::clear_ic_callsites() {
 424   assert(CompiledICLocker::is_safe(this), "mt unsafe call");
 425   ResourceMark rm;
 426   RelocIterator iter(this);
 427   while(iter.next()) {
 428     if (iter.type() == relocInfo::virtual_call_type) {
 429       CompiledIC* ic = CompiledIC_at(&iter);
 430       ic->set_to_clean(false);
 431     }
 432   }
 433 }
 434 
 435 #ifdef ASSERT
 436 // Check class_loader is alive for this bit of metadata.
 437 class CheckClass : public MetadataClosure {
 438   void do_metadata(Metadata* md) {
 439     Klass* klass = NULL;
 440     if (md->is_klass()) {
 441       klass = ((Klass*)md);
 442     } else if (md->is_method()) {
 443       klass = ((Method*)md)->method_holder();
 444     } else if (md->is_methodData()) {
 445       klass = ((MethodData*)md)->method()->method_holder();
 446     } else {
 447       md->print();
 448       ShouldNotReachHere();
 449     }
 450     assert(klass->is_loader_alive(), "must be alive");
 451   }
 452 };
 453 #endif // ASSERT
 454 
 455 
 456 bool CompiledMethod::clean_ic_if_metadata_is_dead(CompiledIC *ic) {
 457   if (ic->is_clean()) {
 458     return true;
 459   }
 460   if (ic->is_icholder_call()) {
 461     // The only exception is compiledICHolder metdata which may
 462     // yet be marked below. (We check this further below).
 463     CompiledICHolder* cichk_metdata = ic->cached_icholder();
 464 
 465     if (cichk_metdata->is_loader_alive()) {
 466       return true;
 467     }
 468   } else {
 469     Metadata* ic_metdata = ic->cached_metadata();
 470     if (ic_metdata != NULL) {
 471       if (ic_metdata->is_klass()) {
 472         if (((Klass*)ic_metdata)->is_loader_alive()) {
 473           return true;
 474         }
 475       } else if (ic_metdata->is_method()) {
 476         Method* method = (Method*)ic_metdata;
 477         assert(!method->is_old(), "old method should have been cleaned");
 478         if (method->method_holder()->is_loader_alive()) {
 479           return true;
 480         }
 481       } else {
 482         ShouldNotReachHere();
 483       }
 484     }
 485   }
 486 
 487   return ic->set_to_clean();
 488 }
 489 
 490 // Clean references to unloaded nmethods at addr from this one, which is not unloaded.
 491 template <class CompiledICorStaticCall>
 492 static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, CompiledMethod* from,
 493                                          bool clean_all) {
 494   // Ok, to lookup references to zombies here
 495   CodeBlob *cb = CodeCache::find_blob_unsafe(addr);
 496   CompiledMethod* nm = (cb != NULL) ? cb->as_compiled_method_or_null() : NULL;
 497   if (nm != NULL) {
 498     // Clean inline caches pointing to both zombie and not_entrant methods
 499     if (clean_all || !nm->is_in_use() || nm->is_unloading() || (nm->method()->code() != nm)) {
 500       // Inline cache cleaning should only be initiated on CompiledMethods that have been
 501       // observed to be is_alive(). However, with concurrent code cache unloading, it is
 502       // possible that by now, the state has become !is_alive. This can happen in two ways:
 503       // 1) It can be racingly flipped to unloaded if the nmethod // being cleaned (from the
 504       // sweeper) is_unloading(). This is fine, because if that happens, then the inline
 505       // caches have already been cleaned under the same CompiledICLocker that we now hold during
 506       // inline cache cleaning, and we will simply walk the inline caches again, and likely not
 507       // find much of interest to clean. However, this race prevents us from asserting that the
 508       // nmethod is_alive(). The is_unloading() function is completely monotonic; once set due
 509       // to an oop dying, it remains set forever until freed. Because of that, all unloaded
 510       // nmethods are is_unloading(), but notably, an unloaded nmethod may also subsequently
 511       // become zombie (when the sweeper converts it to zombie).
 512       // 2) It can be racingly flipped to zombie if the nmethod being cleaned (by the concurrent
 513       // GC) cleans a zombie nmethod that is concurrently made zombie by the sweeper. In this
 514       // scenario, the sweeper will first transition the nmethod to zombie, and then when
 515       // unregistering from the GC, it will wait until the GC is done. The GC will then clean
 516       // the inline caches *with IC stubs*, even though no IC stubs are needed. This is fine,
 517       // as long as the IC stubs are guaranteed to be released until the next safepoint, where
 518       // IC finalization requires live IC stubs to not be associated with zombie nmethods.
 519       // This is guaranteed, because the sweeper does not have a single safepoint check until
 520       // after it completes the whole transition function; it will wake up after the GC is
 521       // done with concurrent code cache cleaning (which blocks out safepoints using the
 522       // suspendible threads set), and then call clear_ic_callsites, which will release the
 523       // associated IC stubs, before a subsequent safepoint poll can be reached. This
 524       // guarantees that the spuriously created IC stubs are released appropriately before
 525       // IC finalization in a safepoint gets to run. Therefore, this race is fine. This is also
 526       // valid in a scenario where an inline cache of a zombie nmethod gets a spurious IC stub,
 527       // and then when cleaning another inline cache, fails to request an IC stub because we
 528       // exhausted the IC stub buffer. In this scenario, the GC will request a safepoint after
 529       // yielding the suspendible therad set, effectively unblocking safepoints. Before such
 530       // a safepoint can be reached, the sweeper similarly has to wake up, clear the IC stubs,
 531       // and reach the next safepoint poll, after the whole transition function has completed.
 532       // Due to the various races that can cause an nmethod to first be is_alive() and then
 533       // racingly become !is_alive(), it is unfortunately not possible to assert the nmethod
 534       // is_alive(), !is_unloaded() or !is_zombie() here.
 535       if (!ic->set_to_clean(!from->is_unloading())) {
 536         return false;
 537       }
 538       assert(ic->is_clean(), "nmethod " PTR_FORMAT "not clean %s", p2i(from), from->method()->name_and_sig_as_C_string());
 539     }
 540   }
 541   return true;
 542 }
 543 
 544 static bool clean_if_nmethod_is_unloaded(CompiledIC *ic, CompiledMethod* from,
 545                                          bool clean_all) {
 546   return clean_if_nmethod_is_unloaded(ic, ic->ic_destination(), from, clean_all);
 547 }
 548 
 549 static bool clean_if_nmethod_is_unloaded(CompiledStaticCall *csc, CompiledMethod* from,
 550                                          bool clean_all) {
 551   return clean_if_nmethod_is_unloaded(csc, csc->destination(), from, clean_all);
 552 }
 553 
 554 // Cleans caches in nmethods that point to either classes that are unloaded
 555 // or nmethods that are unloaded.
 556 //
 557 // Can be called either in parallel by G1 currently or after all
 558 // nmethods are unloaded.  Return postponed=true in the parallel case for
 559 // inline caches found that point to nmethods that are not yet visited during
 560 // the do_unloading walk.
 561 bool CompiledMethod::unload_nmethod_caches(bool unloading_occurred) {
 562   ResourceMark rm;
 563 
 564   // Exception cache only needs to be called if unloading occurred
 565   if (unloading_occurred) {
 566     clean_exception_cache();
 567   }
 568 
 569   if (!cleanup_inline_caches_impl(unloading_occurred, false)) {
 570     return false;
 571   }
 572 
 573 #ifdef ASSERT
 574   // Check that the metadata embedded in the nmethod is alive
 575   CheckClass check_class;
 576   metadata_do(&check_class);
 577 #endif
 578   return true;
 579 }
 580 
 581 void CompiledMethod::run_nmethod_entry_barrier() {
 582   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
 583   if (bs_nm != NULL) {
 584     // We want to keep an invariant that nmethods found through iterations of a Thread's
 585     // nmethods found in safepoints have gone through an entry barrier and are not armed.
 586     // By calling this nmethod entry barrier, it plays along and acts
 587     // like any other nmethod found on the stack of a thread (fewer surprises).
 588     nmethod* nm = as_nmethod_or_null();
 589     if (nm != NULL) {
 590       bool alive = bs_nm->nmethod_entry_barrier(nm);
 591       assert(alive, "should be alive");
 592     }
 593   }
 594 }
 595 
 596 void CompiledMethod::cleanup_inline_caches(bool clean_all) {
 597   for (;;) {
 598     ICRefillVerifier ic_refill_verifier;
 599     { CompiledICLocker ic_locker(this);
 600       if (cleanup_inline_caches_impl(false, clean_all)) {
 601         return;
 602       }
 603     }
 604     // Call this nmethod entry barrier from the sweeper.
 605     run_nmethod_entry_barrier();
 606     InlineCacheBuffer::refill_ic_stubs();
 607   }
 608 }
 609 
 610 // Called to clean up after class unloading for live nmethods and from the sweeper
 611 // for all methods.
 612 bool CompiledMethod::cleanup_inline_caches_impl(bool unloading_occurred, bool clean_all) {
 613   assert(CompiledICLocker::is_safe(this), "mt unsafe call");
 614   ResourceMark rm;
 615 
 616   // Find all calls in an nmethod and clear the ones that point to non-entrant,
 617   // zombie and unloaded nmethods.
 618   RelocIterator iter(this, oops_reloc_begin());
 619   bool is_in_static_stub = false;
 620   while(iter.next()) {
 621 
 622     switch (iter.type()) {
 623 
 624     case relocInfo::virtual_call_type:
 625       if (unloading_occurred) {
 626         // If class unloading occurred we first clear ICs where the cached metadata
 627         // is referring to an unloaded klass or method.
 628         if (!clean_ic_if_metadata_is_dead(CompiledIC_at(&iter))) {
 629           return false;
 630         }
 631       }
 632 
 633       if (!clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), this, clean_all)) {
 634         return false;
 635       }
 636       break;
 637 
 638     case relocInfo::opt_virtual_call_type:
 639       if (!clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), this, clean_all)) {
 640         return false;
 641       }
 642       break;
 643 
 644     case relocInfo::static_call_type:
 645       if (!clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), this, clean_all)) {
 646         return false;
 647       }
 648       break;
 649 
 650     case relocInfo::static_stub_type: {
 651       is_in_static_stub = true;
 652       break;
 653     }
 654 
 655     case relocInfo::metadata_type: {
 656       // Only the metadata relocations contained in static/opt virtual call stubs
 657       // contains the Method* passed to c2i adapters. It is the only metadata
 658       // relocation that needs to be walked, as it is the one metadata relocation
 659       // that violates the invariant that all metadata relocations have an oop
 660       // in the compiled method (due to deferred resolution and code patching).
 661 
 662       // This causes dead metadata to remain in compiled methods that are not
 663       // unloading. Unless these slippery metadata relocations of the static
 664       // stubs are at least cleared, subsequent class redefinition operations
 665       // will access potentially free memory, and JavaThread execution
 666       // concurrent to class unloading may call c2i adapters with dead methods.
 667       if (!is_in_static_stub) {
 668         // The first metadata relocation after a static stub relocation is the
 669         // metadata relocation of the static stub used to pass the Method* to
 670         // c2i adapters.
 671         continue;
 672       }
 673       is_in_static_stub = false;
 674       if (is_unloading()) {
 675         // If the nmethod itself is dying, then it may point at dead metadata.
 676         // Nobody should follow that metadata; it is strictly unsafe.
 677         continue;
 678       }
 679       metadata_Relocation* r = iter.metadata_reloc();
 680       Metadata* md = r->metadata_value();
 681       if (md != NULL && md->is_method()) {
 682         Method* method = static_cast<Method*>(md);
 683         if (!method->method_holder()->is_loader_alive()) {
 684           Atomic::store(r->metadata_addr(), (Method*)NULL);
 685 
 686           if (!r->metadata_is_immediate()) {
 687             r->fix_metadata_relocation();
 688           }
 689         }
 690       }
 691       break;
 692     }
 693 
 694     default:
 695       break;
 696     }
 697   }
 698 
 699   return true;
 700 }
 701 
 702 address CompiledMethod::continuation_for_implicit_exception(address pc, bool for_div0_check) {
 703   // Exception happened outside inline-cache check code => we are inside
 704   // an active nmethod => use cpc to determine a return address
 705   int exception_offset = pc - code_begin();
 706   int cont_offset = ImplicitExceptionTable(this).continuation_offset( exception_offset );
 707 #ifdef ASSERT
 708   if (cont_offset == 0) {
 709     Thread* thread = Thread::current();
 710     ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY
 711     HandleMark hm(thread);
 712     ResourceMark rm(thread);
 713     CodeBlob* cb = CodeCache::find_blob(pc);
 714     assert(cb != NULL && cb == this, "");
 715     ttyLocker ttyl;
 716     tty->print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc));
 717     print();
 718     method()->print_codes();
 719     print_code();
 720     print_pcs();
 721   }
 722 #endif
 723   if (cont_offset == 0) {
 724     // Let the normal error handling report the exception
 725     return NULL;
 726   }
 727   if (cont_offset == exception_offset) {
 728 #if INCLUDE_JVMCI
 729     Deoptimization::DeoptReason deopt_reason = for_div0_check ? Deoptimization::Reason_div0_check : Deoptimization::Reason_null_check;
 730     JavaThread *thread = JavaThread::current();
 731     thread->set_jvmci_implicit_exception_pc(pc);
 732     thread->set_pending_deoptimization(Deoptimization::make_trap_request(deopt_reason,
 733                                                                          Deoptimization::Action_reinterpret));
 734     return (SharedRuntime::deopt_blob()->implicit_exception_uncommon_trap());
 735 #else
 736     ShouldNotReachHere();
 737 #endif
 738   }
 739   return code_begin() + cont_offset;
 740 }
 741 
 742 class HasEvolDependency : public MetadataClosure {
 743   bool _has_evol_dependency;
 744  public:
 745   HasEvolDependency() : _has_evol_dependency(false) {}
 746   void do_metadata(Metadata* md) {
 747     if (md->is_method()) {
 748       Method* method = (Method*)md;
 749       if (method->is_old()) {
 750         _has_evol_dependency = true;
 751       }
 752     }
 753   }
 754   bool has_evol_dependency() const { return _has_evol_dependency; }
 755 };
 756 
 757 bool CompiledMethod::has_evol_metadata() {
 758   // Check the metadata in relocIter and CompiledIC and also deoptimize
 759   // any nmethod that has reference to old methods.
 760   HasEvolDependency check_evol;
 761   metadata_do(&check_evol);
 762   if (check_evol.has_evol_dependency() && log_is_enabled(Debug, redefine, class, nmethod)) {
 763     ResourceMark rm;
 764     log_debug(redefine, class, nmethod)
 765             ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on in nmethod metadata",
 766              _method->method_holder()->external_name(),
 767              _method->name()->as_C_string(),
 768              _method->signature()->as_C_string(),
 769              compile_id());
 770   }
 771   return check_evol.has_evol_dependency();
 772 }